本文整理汇总了Python中mceditlib.nbt.load函数的典型用法代码示例。如果您正苦于以下问题:Python load函数的具体用法?Python load怎么用?Python load使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了load函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: isLevel
def isLevel(cls, filename):
"""
Return True if the given level adapter can load the given filename, False otherwise.
Tries to call cls.canOpenFile on the filename, then
cls._isDataLevel on the file's data, then cls._isTagLevel on an NBT tree
loaded from that data. If none of these methods are present, return False.
Subclasses should implement one of canOpenFile, _isDataLevel, or _isTagLevel.
"""
if hasattr(cls, "canOpenFile"):
return cls.canOpenFile(filename)
if os.path.isfile(filename):
with open(filename, "rb") as f:
data = f.read()
if hasattr(cls, "_isDataLevel"):
return cls._isDataLevel(data)
if hasattr(cls, "_isTagLevel"):
try:
rootTag = nbt.load(filename, data)
except:
return False
return cls._isTagLevel(rootTag)
return False
示例2: testErrors
def testErrors(self):
"""
attempt to name elements of a TAG_List
named list elements are not allowed by the NBT spec,
so we must discard any names when writing a list.
"""
level = self.testCreate()
level["Map"]["Spawn"][0].name = "Torg Potter"
data = level.save()
newlevel = nbt.load(buf=data)
n = newlevel["Map"]["Spawn"][0].name
if n:
print "Named list element failed: %s" % n
# attempt to delete non-existent TAG_Compound elements
# this generates a KeyError like a python dict does.
level = self.testCreate()
try:
del level["DEADBEEF"]
except KeyError:
pass
else:
assert False
示例3: __init__
def __init__(self, filename, create=False):
raise NotImplementedError("No adapter for zipped world/schematic files yet!!!")
self.zipfilename = filename
tempdir = tempfile.mktemp("schematic")
if create is False:
zf = zipfile.ZipFile(filename)
zf.extractall(tempdir)
zf.close()
super(ZipSchematic, self).__init__(tempdir, create)
atexit.register(shutil.rmtree, self.worldFolder.filename, True)
try:
schematicDat = nbt.load(self.worldFolder.getFilePath("schematic.dat"))
self.Width = schematicDat['Width'].value
self.Height = schematicDat['Height'].value
self.Length = schematicDat['Length'].value
if "Materials" in schematicDat:
self.blocktypes = blocktypes_named[schematicDat["Materials"].value]
except Exception as e:
print "Exception reading schematic.dat, skipping: {0!r}".format(e)
self.Width = 0
self.Length = 0
示例4: repair
def repair(self):
"""
Fix the following problems with the region file:
- remove offset table entries pointing past the end of the file
- remove entries that overlap other entries
- relocate offsets for chunks whose xPos,yPos don't match
"""
lostAndFound = {}
_freeSectors = [True] * len(self.freeSectors)
_freeSectors[0] = _freeSectors[1] = False
deleted = 0
recovered = 0
log.info("Beginning repairs on {file} ({chunks} chunks)".format(file=os.path.basename(self.path), chunks=sum(self.offsets > 0)))
for index, offset in enumerate(self.offsets):
if offset:
cx = index & 0x1f
cz = index >> 5
sectorStart = offset >> 8
sectorCount = offset & 0xff
try:
if sectorStart + sectorCount > len(self.freeSectors):
raise RegionFormatError("Offset {start}:{end} ({offset}) at index {index} pointed outside of "
"the file".format(start=sectorStart, end=sectorStart + sectorCount, index=index, offset=offset))
data = self.readChunkBytes(cx, cz)
chunkTag = nbt.load(buf=data)
lev = chunkTag["Level"]
xPos = lev["xPos"].value & 0x1f
zPos = lev["zPos"].value & 0x1f
overlaps = False
for i in xrange(sectorStart, sectorStart + sectorCount):
if _freeSectors[i] is False:
overlaps = True
_freeSectors[i] = False
if xPos != cx or zPos != cz or overlaps:
lostAndFound[xPos, zPos] = data
if (xPos, zPos) != (cx, cz):
raise RegionFormatError("Chunk {found} was found in the slot reserved for {expected}".format(found=(xPos, zPos), expected=(cx, cz)))
else:
raise RegionFormatError("Chunk {found} (in slot {expected}) has overlapping sectors with another chunk!".format(found=(xPos, zPos), expected=(cx, cz)))
except Exception as e:
log.info("Unexpected chunk data at sector {sector} ({exc})".format(sector=sectorStart, exc=e))
self._setOffset(cx, cz, 0)
deleted += 1
for cPos, foundData in lostAndFound.iteritems():
cx, cz = cPos
if self._getOffset(cx, cz) == 0:
log.info("Found chunk {found} and its slot is empty, recovering it".format(found=cPos))
self.writeChunk(cx, cz, foundData)
recovered += 1
log.info("Repair complete. Removed {0} chunks, recovered {1} chunks, net {2}".format(deleted, recovered, recovered - deleted))
示例5: getMapTag
def getMapTag(self, mapID):
mapPath = "data/map_%s.dat" % mapID
if not self.selectedRevision.containsFile(mapPath):
raise KeyError("Map %s not found" % mapID)
mapData = self.selectedRevision.readFile(mapPath)
mapNBT = nbt.load(buf=mapData)
return mapNBT
示例6: loadMetadata
def loadMetadata(self):
try:
metadataTag = nbt.load(buf=self.selectedRevision.readFile("level.dat"))
self.metadata = AnvilWorldMetadata(metadataTag)
self.loadBlockMapping()
except (EnvironmentError, zlib.error, NBTFormatError) as e:
log.info("Error loading level.dat, trying level.dat_old ({0})".format(e))
try:
metadataTag = nbt.load(buf=self.selectedRevision.readFile("level.dat_old"))
self.metadata = AnvilWorldMetadata(metadataTag)
self.metadata.dirty = True
log.info("level.dat restored from backup.")
except Exception as e:
traceback.print_exc()
log.info("%r while loading level.dat_old. Initializing with defaults.", e)
self._createMetadataTag()
assert self.metadata.version == VERSION_ANVIL, "Pre-Anvil world formats are not supported (for now)"
示例7: testBigEndianIntHeightMap
def testBigEndianIntHeightMap():
""" Test modifying, saving, and loading the new TAG_Int_Array heightmap
added with the Anvil format.
"""
region = RegionFile(TempFile("AnvilWorld/region/r.0.0.mca"))
chunk_data = region.readChunkBytes(0, 0)
chunk = nbt.load(buf=chunk_data)
hm = chunk["Level"]["HeightMap"]
hm.value[2] = 500
oldhm = numpy.array(hm.value)
filename = mktemp("ChangedChunk")
chunk.save(filename)
changedChunk = nbt.load(filename)
os.unlink(filename)
eq = (changedChunk["Level"]["HeightMap"].value == oldhm)
assert eq.all()
示例8: testBigEndianIntHeightMap
def testBigEndianIntHeightMap(tmpdir, temp_file):
""" Test modifying, saving, and loading the new TAG_Int_Array heightmap
added with the Anvil format.
"""
region = RegionFile(temp_file.strpath)
chunk_data = region.readChunkBytes(0, 0)
chunk = nbt.load(buf=chunk_data)
hm = chunk["Level"]["HeightMap"]
hm.value[2] = 500
oldhm = numpy.array(hm.value)
filename = tmpdir.join("ChangedChunk").strpath
chunk.save(filename)
changedChunk = nbt.load(filename)
os.unlink(filename)
eq = (changedChunk["Level"]["HeightMap"].value == oldhm)
assert eq.all()
示例9: testSpeed
def testSpeed(self):
d = join("test_files", "TileTicks_chunks.zip")
zf = zipfile.ZipFile(d)
files = [zf.read(f) for f in zf.namelist()[:40]]
startTime = time.time()
for f in files:
if len(f):
n = nbt.load(buf=f)
duration = time.time() - startTime
assert duration < 1.0 # Will fail when not using _nbt.pyx
示例10: getWorldInfo
def getWorldInfo(cls, filename, displayNameLimit=40):
try:
if os.path.isdir(filename):
folderName = os.path.basename(filename)
levelDat = os.path.join(filename, "level.dat")
else:
folderName = os.path.basename(os.path.dirname(filename))
levelDat = filename
levelTag = nbt.load(levelDat)
try:
displayName = levelTag['Data']['LevelName'].value
if len(displayName) > displayNameLimit:
displayName = displayName[:displayNameLimit] + "..."
if len(folderName) > displayNameLimit:
folderName = folderName[:displayNameLimit] + "..."
if folderName != displayName:
displayName = "%s (%s)" % (displayName, folderName)
except Exception as e:
log.warn("Failed to get display name for level.", exc_info=1)
displayName = folderName
try:
lastPlayedTime = levelTag['Data']['LastPlayed'].value
except Exception as e:
log.warn("Failed to get last-played time for level.", exc_info=1)
lastPlayedTime = 0
version = "Unknown Version"
try:
metadata = AnvilWorldMetadata(levelTag)
stackVersion = VERSION_1_8 if metadata.is1_8World() else VERSION_1_7
if stackVersion == VERSION_1_7:
version = "Minecraft 1.7"
if "FML" in metadata.metadataTag:
version = "MinecraftForge 1.7"
if stackVersion == VERSION_1_8:
version = "Minecraft 1.8"
except Exception as e:
log.warn("Failed to get version info for %s: %r", filename, e, exc_info=1)
return WorldInfo(displayName, lastPlayedTime, version)
except Exception as e:
log.error("Failed getting world info for %s: %r", filename, e)
return WorldInfo(str(e), 0, "")
示例11: testLoad
def testLoad(self):
"Load an indev level."
level = nbt.load("test_files/indev.mclevel")
# The root tag must have a name, and so must any tag within a TAG_Compound
print level.name
# Use the [] operator to look up subtags of a TAG_Compound.
print level["Environment"]["SurroundingGroundHeight"].value
# Numeric, string, and bytearray types have a value that can be accessed and changed.
print level["Map"]["Blocks"].value
return level
示例12: testErrors
def testErrors(created_nbt):
"""
attempt to name elements of a TAG_List
named list elements are not allowed by the NBT spec,
so we must discard any names when writing a list.
"""
level = created_nbt
level["Map"]["Spawn"][0].name = "Torg Potter"
data = level.save()
newlevel = nbt.load(buf=data)
n = newlevel["Map"]["Spawn"][0].name
assert not n, "Named list element failed: %s" % n
# attempt to delete non-existent TAG_Compound elements
# this generates a KeyError like a python dict does.
with pytest.raises(KeyError):
del level["DEADBEEF"]
示例13: readChunk
def readChunk(self, cx, cz, dimName):
"""
Return chunk (cx, cz) in the given dimension as an AnvilChunkData. Raise ChunkNotPresent if not found.
:type cx: int or dtype
:type cz: int or dtype
:type dimName: str
:return:
:rtype: AnvilChunkData
"""
try:
data = self.selectedRevision.readChunkBytes(cx, cz, dimName)
chunkTag = nbt.load(buf=data)
log.debug("_getChunkData: Chunk %s loaded (%s bytes)", (cx, cz), len(data))
chunkData = AnvilChunkData(self, cx, cz, dimName, chunkTag)
except ChunkNotPresent:
raise
except (KeyError, IndexError, zlib.error) as e: # Missing nbt keys, lists too short, decompression failure
raise AnvilChunkFormatError("Error loading chunk: %r" % e)
return chunkData
示例14: getPlayerTag
def getPlayerTag(self, playerUUID=""):
"""
Return the root NBT tag for the named player. Raise PlayerNotFound if not present.
:param playerUUID:
:type playerUUID: unicode
:return:
:rtype: PCPlayer
"""
if playerUUID == "":
if "Player" in self.metadata.rootTag:
# single-player world
playerTag = self.metadata.rootTag["Player"]
return playerTag
raise PlayerNotFound(playerUUID)
else:
playerFilePath = "playerdata/%s.dat" % playerUUID
if self.selectedRevision.containsFile(playerFilePath):
# multiplayer world, found this player
playerTag = nbt.load(buf=self.selectedRevision.readFile(playerFilePath))
return playerTag
else:
raise PlayerNotFound(playerUUID)
示例15: load_file
def load_file():
global test_file
test_file = nbt.load(buf=test_data)