本文整理汇总了Python中bitstring.BitStream.tofile方法的典型用法代码示例。如果您正苦于以下问题:Python BitStream.tofile方法的具体用法?Python BitStream.tofile怎么用?Python BitStream.tofile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bitstring.BitStream
的用法示例。
在下文中一共展示了BitStream.tofile方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Mem
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
class Mem(object):
def __init__(self):
self.real = BitStream(600*16)
self.jumps = 0
def load(self, file):
self.real = BitStream(filename=file)
def save(self, file):
self.real.tofile(file)
def jump(self, pos):
self.jumps += 1
self.real.bytepos = pos
def read(self, size=16):
return self.real.read(16)
def get(self, pos, size=16):
realpos = pos * 8
return self.real[realpos:realpos+size]
def set(self, pos, bits):
realpos = pos * 8
self.real[realpos:realpos+len(bits)] = bits
@property
def pos(self):
return self.real.bytepos
示例2: save
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
def save(self, filename, font_type = FONT_TYPES.font01, game = GAMES.dr):
data = BitStream(SPFT_MAGIC)
data += BitStream(uintle = len(self.data), length = 32)
mapping_table_len = self.find_max_char() + 1 # zero-indexed so +1 for the size.
mapping_table_start = 0x20
font_table_start = mapping_table_len * 2 + mapping_table_start
data += BitStream(uintle = font_table_start, length = 32)
data += BitStream(uintle = mapping_table_len, length = 32)
data += BitStream(uintle = mapping_table_start, length = 32)
data += UNKNOWN1[game][font_type] + UNKNOWN2
data += self.gen_mapping_table(mapping_table_len)
data += self.gen_font_table()
padding = BitStream(hex = '0x00') * (16 - ((data.len / 8) % 16))
data += padding
f = open(filename, "wb")
data.tofile(f)
f.close()
示例3: decode
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
def decode(self, in_stream, out_stream):
bs = BitStream()
dq = deque()
at_least_three = False
for word in self.words_from_file(in_stream):
if not word or word not in self.word_dict:
continue
#print >> sys.stderr, 'word:"', word, '"'
dq.append(self.word_dict[word])
if at_least_three or len(dq) == 3:
bs.append(pack(self.int_type, dq.popleft()))
at_least_three = True
if bs.len > self.bit_buffer:
cut = 0
for byte in bs.cut(self.bit_buffer):
cut += 1
byte.tofile(out_stream)
del bs[:cut * self.bit_buffer]
# dq has to have exactly 2 elements here, the last is the bit length of the first, unless it's 0
#print >> sys.stderr, 'dq:', dq
extra_bits = dq.pop()
bs.append(pack('uint:' + str(extra_bits), dq.popleft()))
bs.tofile(out_stream)
示例4: save
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
def save(self, filename):
data = BitStream(self.magic) + BitStream(uintle = len(self.lines), length = 16)
for line in self.lines:
data += line.to_data()
with open(filename, "wb") as f:
data.tofile(f)
示例5: create_archives
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
#.........这里部分代码省略.........
file_list = None
csv_template_f = open(archive["csv"], "rb")
csv_template = csv.reader(csv_template_f)
csv_out_path = os.path.join(temp_dir, "cpk.csv")
csv_out_f = open(csv_out_path, "wb")
csv_out = csv.writer(csv_out_f)
for row in csv_template:
if len(row) < 4:
continue
base_path = row[0]
real_path = os.path.join(archive["dir"], base_path)
out_path = os.path.join(temp_dir, archive["name"], base_path)
self.progress.setValue(self.progress.value() + 1)
self.progress.setLabelText("Reading...\n%s" % real_path)
# All items in the CPK list should be files.
# Therefore, if we have a directory, then it needs to be packed.
if os.path.isdir(real_path):
if self.__cache_outdated(real_path, out_path):
out_dir = os.path.dirname(out_path)
try:
os.makedirs(out_dir)
except:
pass
data = pack_dir(real_path)
with open(out_path, "wb") as out_file:
data.tofile(out_file)
del data
elif os.path.isfile(real_path):
# If it's a file, though, we can just use it directly.
out_path = real_path
row[0] = out_path
csv_out.writerow(row)
csv_template_f.close()
csv_out_f.close()
self.__pack_cpk(csv_out_path, archive["cpk"])
# We're playing fast and loose with the file count anyway, so why not?
self.file_count += 1
self.progress.setValue(self.file_count)
self.progress.setLabelText("Saving " + archive["name"] + "...")
if archive["toc"]:
for entry in table_of_contents:
if not entry in toc_info:
_LOGGER.warning("%s missing from %s table of contents." % (entry, archive["name"]))
continue
file_pos = table_of_contents[entry]["pos"]
file_size = table_of_contents[entry]["size"]
eboot.overwrite(BitStream(uintle = file_pos, length = 32), toc_info[entry][0] * 8)
eboot.overwrite(BitStream(uintle = file_size, length = 32), toc_info[entry][1] * 8)
del table_of_contents
示例6: GmoFile
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
class GmoFile():
def __init__(self, data = None, offset = 0, filename = None):
self.data = None
self.__gim_files = []
self.gimconv = GimConverter()
if not data == None:
self.load_data(data, offset)
elif not filename == None:
self.load_file(filename)
def load_file(self, filename):
data = BitStream(filename = filename)
self.load_data(data)
def load_data(self, data, offset = 0):
if not data[offset * 8 : offset * 8 + GMO_MAGIC.len] == GMO_MAGIC:
_LOGGER.error("GMO header not found at 0x%04X." % offset)
return
data.bytepos = offset + GMO_SIZE_OFFSET
gmo_size = data.read("uintle:32") + GMO_SIZE_DIFF
self.data = BitStream(data[offset * 8 : (offset + gmo_size) * 8])
self.__find_gims()
def save(self, filename):
with open(filename, "wb") as f:
self.data.tofile(f)
def __find_gims(self):
if self.data == None:
return
self.__gim_files = []
for gim_start in self.data.findall(GIM_MAGIC, bytealigned = True):
gim_size_pos = gim_start + (GIM_SIZE_OFFSET * 8) # Bit pos.
gim_size = self.data[gim_size_pos : gim_size_pos + 32].uintle + GIM_SIZE_DIFF
# And turn it into a byte position.
gim_start /= 8
self.__gim_files.append((gim_start, gim_size))
def gim_count(self):
return len(self.__gim_files)
def get_gim(self, gim_id):
if gim_id >= self.gim_count():
raise GimIndexError("Invalid GIM ID.")
gim_start, gim_size = self.__gim_files[gim_id]
gim_data = self.data[gim_start * 8 : (gim_start + gim_size) * 8]
return gim_data
def replace_png_file(self, gim_id, filename, quantize_to_fit = True):
if quantize_to_fit:
quantize_order = [QuantizeType.auto, QuantizeType.index8, QuantizeType.index4]
else:
quantize_order = [QuantizeType.auto]
quantize_id = 0
(fd, temp_gim) = tempfile.mkstemp(suffix = ".gim", prefix = "sdse-")
os.close(fd) # Don't need the open file handle.
while True:
self.gimconv.png_to_gim(filename, temp_gim, quantize_order[quantize_id])
try:
self.replace_gim_file(gim_id, temp_gim)
except GimSizeError:
quantize_id += 1
except GimIndexError:
os.remove(temp_gim)
raise
else:
# If we didn't except, that means we succeeded, so we can leave.
_LOGGER.debug("Quantized PNG to %s" % quantize_order[quantize_id])
break
if quantize_id > len(quantize_order):
_LOGGER.error("Unable to convert %s into a GIM small enough to insert." % filename)
break
os.remove(temp_gim)
def replace_gim_file(self, gim_id, filename):
gim_data = BitStream(filename = filename)
self.replace_gim(gim_id, gim_data)
def replace_gim(self, gim_id, gim_data):
if gim_id >= self.gim_count():
raise GimIndexError("Invalid GIM ID.")
gim_start, gim_size = self.__gim_files[gim_id]
#.........这里部分代码省略.........
示例7: extend_eboot
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
eboot = extend_eboot(eboot)
for patch in EBOOT_PATCHES:
enabled = patch[ENABLED]
if patch[CFG_ID] and patch[CFG_ID] in common.editor_config.hacks:
enabled = common.editor_config.hacks[patch[CFG_ID]]
# So we can undo patches if they've already been applied.
key = PATCH if enabled else ORIG
for item in patch[DATA]:
eboot.overwrite(item[key], item[POS] * 8)
eboot = apply_sys_lang(eboot)
eboot = apply_clt_patch(eboot)
return eboot
if __name__ == "__main__":
src = "Y:\\Danganronpa\\Danganronpa2\\EBOOT-DEC.BIN"
dst = "Y:\\Danganronpa\\Danganronpa2\\EBOOT-TEST.BIN"
test = BitStream(filename = src)
test = apply_eboot_patches(test)
with open(dst, "wb") as f:
test.tofile(f)
### EOF ###
示例8: setup_workspace
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
def setup_workspace(self):
data0 = os.path.join(self.iso_dir, DATA0_CPK)
self.generate_directories()
progress = QProgressDialog("", QtCore.QString(), 0, 11000, self)
progress.setWindowTitle("Setting up workspace...")
progress.setWindowModality(Qt.Qt.WindowModal)
progress.setMinimumDuration(0)
progress.setValue(0)
progress.setAutoClose(False)
progress.setAutoReset(False)
progress.setLabelText("Creating directories...")
# Do the easy stuff first.
if not os.path.isdir(self.changes_dir):
os.makedirs(self.changes_dir)
progress.setValue(progress.value() + 1)
if not os.path.isdir(self.backup_dir):
os.makedirs(self.backup_dir)
progress.setValue(progress.value() + 1)
thread_fns = [{"target": extract_cpk, "kwargs": {"filename": data0, "out_dir": self.data0_dir}}]
# Going to capture stdout because I don't feel like
# rewriting the extract functions to play nice with GUI.
stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
for thread_fn in thread_fns:
thread = threading.Thread(**thread_fn)
thread.start()
while thread.isAlive():
thread.join(THREAD_TIMEOUT)
output = [line for line in sys.stdout.getvalue().split("\n") if len(line) > 0]
progress.setValue(progress.value() + len(output))
if len(output) > 0:
progress.setLabelText("Extracting %s..." % output[-1])
sys.stdout = cStringIO.StringIO()
sys.stdout = stdout
# Give us an ISO directory for the editor to place modified files in.
progress.setLabelText("Copying ISO files...")
# ISO directory needs to not exist for copytree.
if os.path.isdir(self.edited_iso_dir):
shutil.rmtree(self.edited_iso_dir)
# One more thing we want threaded so it doesn't lock up the GUI.
thread = threading.Thread(target=shutil.copytree, kwargs={"src": self.iso_dir, "dst": self.edited_iso_dir})
thread.start()
while thread.isAlive():
thread.join(THREAD_TIMEOUT)
progress.setLabelText("Copying ISO files...")
# It has to increase by some amount or it won't update and the UI will lock up.
progress.setValue(progress.value() + 1)
# shutil.copytree(self.iso_dir, self.edited_iso_dir)
progress.setValue(progress.value() + 1)
# Files we want to make blank, because they're unnecessary.
blank_files = [
os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "DATA.BIN"),
os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "EBOOT.BIN"),
os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "PARAM.SFO"),
]
for blank in blank_files:
with open(blank, "wb") as f:
pass
# Copy the decrypted EBOOT into the ISO folder and apply our hacks to it.
progress.setLabelText("Hacking EBOOT...")
progress.setValue(progress.value() + 1)
hacked_eboot = BitStream(filename=self.eboot_path)
hacked_eboot = apply_eboot_patches(hacked_eboot)
with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f:
hacked_eboot.tofile(f)
# shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"))
progress.setLabelText("Extracting editor data...")
progress.setValue(progress.value() + 1)
# Extract the editor data.
editor_data = zipfile.ZipFile("data/editor_data.zip", "r")
editor_data.extractall(self.editor_data_dir)
editor_data.close()
progress.setValue(progress.maximum())
progress.close()
self.ui.grpStep4.setEnabled(False)
#.........这里部分代码省略.........
示例9: ModelPak
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
class ModelPak():
def __init__(self, filename = None):
self.__data = None
self.__gmo_files = []
if filename:
self.load_file(filename)
def load_file(self, filename):
data = BitStream(filename = filename)
self.load_data(data)
def load_data(self, data):
files = [entry_data for (entry_name, entry_data) in get_pak_files(data)]
# There are always at least four files in a model pak.
# The first three I don't know a lot about, and then
# the GMO files come after that.
if len(files) < 4:
_LOGGER.error("Invalid model PAK. %d files found, but at least 4 needed." % len(files))
return
# The name pak contains a list of null-terminated names for
# each of the models, stored in our standard pak format.
name_pak = files[0]
names = [entry_data.bytes.strip('\0') for (entry_name, entry_data) in get_pak_files(name_pak)]
# Most of the model paks in SDR2 have a fourth unknown file before the models
# start, so we'll just take everything from the back end and call it a day.
models = files[-len(names):]
# Now, we don't get file positions from the unpacker, so let's find those
# and start filling out our internal list of GMO files.
file_starts, file_ends = parse_pak_toc(data)
model_starts = file_starts[-len(names):]
for i, model in enumerate(models):
# First of all, not all of the "models" present are actually GMO files.
# It's rare, but there is the occasional other unknown format.
# So let's make sure we have a GMO file.
if not model[:GMO_MAGIC.len] == GMO_MAGIC:
# print i, "Not a GMO."
continue
name = names[i]
gmo = GmoFile(data = model)
size = model.len / 8
start = model_starts[i]
self.__gmo_files.append({
_NAME: name,
_START: start,
_SIZE: size,
_DATA: gmo,
})
self.__data = BitStream(data)
def save(self, filename):
self.__update_data()
with open(filename, "wb") as f:
self.__data.tofile(f)
def __update_data(self):
for gmo in self.__gmo_files:
start = gmo[_START] * 8
data = gmo[_DATA].data
self.__data.overwrite(data, start)
def get_data(self):
self.__update_data()
return self.__data
def gmo_count(self):
return len(self.__gmo_files)
def get_gmo(self, index):
if index >= self.gmo_count() or index == None:
_LOGGER.error("Invalid GMO ID %d." % index)
return None
return self.__gmo_files[index][_DATA]
def get_gmos(self):
return [gmo[_DATA] for gmo in self.__gmo_files]
def get_name(self, index):
if index >= self.gmo_count():
_LOGGER.error("Invalid GMO ID %d." % index)
return None
return self.__gmo_files[index][_NAME]
def get_names(self):
return [gmo[_NAME] for gmo in self.__gmo_files]
def id_from_name(self, name):
for i in range(self.gmo_count()):
#.........这里部分代码省略.........
示例10: create_archives
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import tofile [as 别名]
def create_archives(self):
try:
self.width = self.parent.width()
self.height = self.parent.height()
self.x = self.parent.x()
self.y = self.parent.y()
except:
self.width = 1920
self.height = 1080
self.x = 0
self.y = 0
self.progress = QProgressDialog("Reading...", QtCore.QString(), 0, 7600, self.parent)
self.progress.setWindowModality(Qt.Qt.WindowModal)
self.progress.setValue(0)
self.progress.setAutoClose(False)
self.progress.setMinimumDuration(0)
USRDIR = os.path.join(common.editor_config.iso_dir, "PSP_GAME", "USRDIR")
eboot_path = os.path.join(common.editor_config.iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN")
eboot = BitStream(filename = eboot_path)
eboot = eboot_patch.apply_eboot_patches(eboot)
# So we can loop. :)
ARCHIVE_INFO = [
{
"dir": common.editor_config.data00_dir,
"cpk": os.path.join(USRDIR, "data00.cpk"),
"csv": os.path.join("data", "data00.csv" if not common.editor_config.quick_build else "data00-quick.csv"),
"name": "data00.cpk",
"pack": common.editor_config.pack_data00,
},
{
"dir": common.editor_config.data01_dir,
"cpk": os.path.join(USRDIR, "data01.cpk"),
"csv": os.path.join("data", "data01.csv" if not common.editor_config.quick_build else "data01-quick.csv"),
"name": "data01.cpk",
"pack": common.editor_config.pack_data01,
},
]
# temp_dir = tempfile.mkdtemp(prefix = "sdse-")
temp_dir = common.editor_config.build_cache
for archive in ARCHIVE_INFO:
if not archive["pack"]:
continue
self.progress.setWindowTitle("Building " + archive["name"])
csv_template_f = open(archive["csv"], "rb")
csv_template = csv.reader(csv_template_f)
csv_out_path = os.path.join(temp_dir, "cpk.csv")
csv_out_f = open(csv_out_path, "wb")
csv_out = csv.writer(csv_out_f)
for row in csv_template:
if len(row) < 4:
continue
base_path = row[0]
real_path = os.path.join(archive["dir"], base_path)
out_path = os.path.join(temp_dir, archive["name"], base_path)
self.progress.setValue(self.progress.value() + 1)
self.progress.setLabelText("Reading...\n%s" % real_path)
# All items in the CPK list should be files.
# Therefore, if we have a directory, then it needs to be packed.
if os.path.isdir(real_path):
if self.__cache_outdated(real_path, out_path):
out_dir = os.path.dirname(out_path)
try:
os.makedirs(out_dir)
except:
pass
data = pack_dir(real_path)
with open(out_path, "wb") as out_file:
data.tofile(out_file)
del data
elif os.path.isfile(real_path):
# If it's a file, though, we can just use it directly.
out_path = real_path
row[0] = out_path
csv_out.writerow(row)
csv_template_f.close()
csv_out_f.close()
self.__pack_cpk(csv_out_path, archive["cpk"])
self.progress.setWindowTitle("Building...")
#.........这里部分代码省略.........