本文整理汇总了Python中typing.BinaryIO.seek方法的典型用法代码示例。如果您正苦于以下问题:Python BinaryIO.seek方法的具体用法?Python BinaryIO.seek怎么用?Python BinaryIO.seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类typing.BinaryIO
的用法示例。
在下文中一共展示了BinaryIO.seek方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_index
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def get_index(
self, archive: BinaryIO, version: Optional[Version] = None
) -> Dict[str, ComplexIndexEntry]:
if not version:
version = self.version() if self.version else self.detect_version()
offset = 0
key: Optional[int] = None
if self.offset_and_key:
offset, key = self.offset_and_key
else:
offset, key = version.find_offset_and_key(archive)
archive.seek(offset)
index: Dict[bytes, IndexEntry] = pickle.loads(
zlib.decompress(archive.read()), encoding="bytes"
)
if key is not None:
normal_index = UnRPA.deobfuscate_index(key, index)
else:
normal_index = UnRPA.normalise_index(index)
return {
UnRPA.ensure_str_path(path).replace("/", os.sep): data
for path, data in normal_index.items()
}
示例2: __init__
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def __init__(self, archive: BinaryIO, offset: int, length: int, prefix: bytes):
archive.seek(offset)
self.name = archive.name
self.remaining = length
self.sources = [cast(io.BufferedIOBase, archive)]
if prefix:
self.sources.insert(0, cast(io.BufferedIOBase, io.BytesIO(prefix)))
示例3: put
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def put(
self, namespace: str, metadata: Dict[str, Any], bytes_io: BinaryIO,
) -> None:
"""Store a file."""
subset = dict_subset(metadata, lambda k, v: k in (
# We are not storing the 'file_name'
'image_width', 'image_height', 'original_id', 'version'))
self._convert_values_to_str(subset)
if hasattr(bytes_io, 'seekable') and bytes_io.seekable():
bytes_io.seek(0)
# When botocore.response.StreamingBody is passed in as bytes_io,
# the bucket.put_object() call below fails with
# "AttributeError: 'StreamingBody' object has no attribute 'tell'"
# so we have to read the stream, getting the bytes:
if not hasattr(bytes_io, 'tell'):
bytes_io = bytes_io.read() # type: ignore
result = self.bucket.put_object(
Key=self._get_path(namespace, metadata),
# done automatically by botocore: ContentMD5=encoded_md5,
ContentType=metadata['mime_type'],
ContentLength=metadata['length'], Body=bytes_io, Metadata=subset)
# print(result)
return result
示例4: read_offset_array
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def read_offset_array(file: BinaryIO, count: int):
"""Read an array of offsets to null-terminated strings from the file."""
cdmat_offsets = str_read(str(count) + 'i', file)
arr = [None] * count # type: List[str]
for ind, off in enumerate(cdmat_offsets):
file.seek(off)
arr[ind] = read_nullstr(file)
return arr
示例5: parse_header
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def parse_header(source: BinaryIO) -> Tuple[OFXHeaderType, str]:
"""
Consume source; feed to appropriate class constructor which performs
validation/type conversion on OFX header.
Using header, locate/read/decode (but do not parse) OFX data body.
Returns a 2-tuple of:
* instance of OFXHeaderV1/OFXHeaderV2 containing parsed data, and
* decoded text of OFX data body
"""
# Skip any empty lines at the beginning
while True:
# OFX header is read by nice clean machines, not meatbags -
# should not contain emoji, 漢字, or what have you.
line = source.readline().decode("ascii")
if line.strip():
break
# If the first non-empty line contains an XML declaration, it's OFX v2
xml_match = XML_REGEX.match(line)
if xml_match:
# OFXv2 spec doesn't require newlines between XML declaration,
# OFX declaration, and data elements; `line` may or may not
# contain the latter two.
#
# Just rewind, read the whole file (it must be UTF-8 encoded per
# the spec) and slice the OFX data body from the end of the
# OFX declaration
source.seek(0)
decoded_source = source.read().decode(OFXHeaderV2.codec)
header, header_end_index = OFXHeaderV2.parse(decoded_source)
message = decoded_source[header_end_index:]
else:
# OFX v1
rawheader = line + "\n"
# First line is OFXHEADER; need to read next 8 lines for a fixed
# total of 9 fields required by OFX v1 spec.
for n in range(8):
rawheader += source.readline().decode("ascii")
header, header_end_index = OFXHeaderV1.parse(rawheader)
# Input source stream position has advanced to the beginning of
# the OFX body tag soup, which is where subsequent calls
# to read()/readlines() will pick up.
#
# Decode the OFX data body according to the encoding declared
# in the OFX header
message = source.read().decode(header.codec)
return header, message.strip()
示例6: read_nullstr
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def read_nullstr(file: BinaryIO, pos: int=None):
"""Read a null-terminated string from the file."""
if pos is not None:
if pos == 0:
return ''
file.seek(pos)
text = []
while True:
char = file.read(1)
if char == b'\0':
return b''.join(text).decode('ascii')
if not char:
raise ValueError('Fell off end of file!')
text.append(char)
示例7: put
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def put(
self, namespace: str, metadata: Dict[str, Any], bytes_io: BinaryIO,
) -> None:
"""Store a file (``bytes_io``) inside ``namespace``."""
if bytes_io.tell():
bytes_io.seek(0)
outdir = self._dir_of(namespace)
if not outdir.exists():
outdir.mkdir(parents=True) # Create namespace directory as needed
outfile = outdir / self._get_filename(metadata)
with open(str(outfile), mode='wb', buffering=MEGABYTE) as writer:
while True:
chunk = bytes_io.read(MEGABYTE)
if chunk:
writer.write(chunk)
else:
break
assert outfile.lstat().st_size == metadata['length']
示例8: _compute_md5
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def _compute_md5(
self, bytes_io: BinaryIO, metadata: Dict[str, Any],
) -> None:
from hashlib import md5
two_megabytes = 1048576 * 2
the_hash = md5()
the_length = 0
bytes_io.seek(0)
while True:
segment = bytes_io.read(two_megabytes)
if segment == b'':
break
the_length += len(segment)
the_hash.update(segment)
metadata['md5'] = the_hash.hexdigest()
previous_length = metadata.get('length')
if previous_length is None:
metadata['length'] = the_length
else:
assert previous_length == the_length, "Bug? File lengths {}, {} " \
"don't match.".format(previous_length, the_length)
bytes_io.seek(0) # ...so it can be read again
示例9: mktar_from_dockerfile
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def mktar_from_dockerfile(fileobject: BinaryIO) -> IO:
"""
Create a zipped tar archive from a Dockerfile
**Remember to close the file object**
Args:
fileobj: a Dockerfile
Returns:
a NamedTemporaryFile() object
"""
f = tempfile.NamedTemporaryFile()
t = tarfile.open(mode="w:gz", fileobj=f)
if isinstance(fileobject, BytesIO):
dfinfo = tarfile.TarInfo("Dockerfile")
dfinfo.size = len(fileobject.getvalue())
fileobject.seek(0)
else:
dfinfo = t.gettarinfo(fileobj=fileobject, arcname="Dockerfile")
t.addfile(dfinfo, fileobject)
t.close()
f.seek(0)
return f
示例10: _read_sequences
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
def _read_sequences(f: BinaryIO, off, count) -> List[MDLSequence]:
"""Split this off to decrease stack in main parse method."""
f.seek(off)
sequences = [None] * count # type: List[MDLSequence]
for i in range(count):
start_pos = f.tell()
(
base_ptr,
label_pos,
act_name_pos,
flags,
_, # Seems to be a pointer.
act_weight,
event_count,
event_pos,
) = str_read('8i', f)
bbox_min = str_readvec(f)
bbox_max = str_readvec(f)
# Skip 20 ints, 9 floats to get to keyvalues = 29*4 bytes
# Then 8 unused ints.
(
keyvalue_pos,
keyvalue_size,
) = str_read('116xii32x', f)
end_pos = f.tell()
f.seek(start_pos + event_pos)
events = [None] * event_count # type: List[SeqEvent]
for j in range(event_count):
event_start = f.tell()
(
event_cycle,
event_index,
event_flags,
event_options,
event_nameloc,
) = str_read('fii64si', f)
event_end = f.tell()
# There are two event systems.
if event_flags == 1 << 10:
# New system, name in the file.
event_name = read_nullstr(f, event_start + event_nameloc)
if event_name.isdigit():
try:
event_type = ANIM_EVENT_BY_INDEX[int(event_name)]
except KeyError:
raise ValueError('Unknown event index!')
else:
try:
event_type = ANIM_EVENT_BY_NAME[event_name]
except KeyError:
# NPC-specific events, declared dynamically.
event_type = event_name
else:
# Old system, index.
try:
event_type = ANIM_EVENT_BY_INDEX[event_index]
except KeyError:
# raise ValueError('Unknown event index!')
print('Unknown: ', event_index, event_options.rstrip(b'\0'))
continue
f.seek(event_end)
events[j] = SeqEvent(
type=event_type,
cycle=event_cycle,
options=event_options.rstrip(b'\0').decode('ascii')
)
if keyvalue_size:
keyvalues = read_nullstr(f, start_pos + keyvalue_pos)
else:
keyvalues = ''
sequences[i] = MDLSequence(
label=read_nullstr(f, start_pos + label_pos),
act_name=read_nullstr(f, start_pos + act_name_pos),
flags=flags,
act_weight=act_weight,
events=events,
bbox_min=bbox_min,
bbox_max=bbox_max,
keyvalues=keyvalues,
)
f.seek(end_pos)
return sequences
示例11: _load
# 需要导入模块: from typing import BinaryIO [as 别名]
# 或者: from typing.BinaryIO import seek [as 别名]
#.........这里部分代码省略.........
includemodel_index,
# In-engine, this is a pointer to the combined version of this +
# included models. In the file it's useless.
virtualModel,
# mstudioanimblock_t
animblocks_name_index,
animblocks_count,
animblocks_index,
animblockModel, # Placeholder for mutable-void*
# Points to a series of bytes?
bonetablename_index,
vertex_base, # Placeholder for void*
offset_base, # Placeholder for void*
) = str_read('f 11I', f)
(
# Used with $constantdirectionallight from the QC
# Model should have flag #13 set if enabled
directionaldotproduct, # byte
# Preferred rather than clamped
rootLod, # byte
# 0 means any allowed, N means Lod 0 -> (N-1)
self.numAllowedRootLods, # byte
#unknown byte;
#unknown int;
# mstudioflexcontrollerui_t
flexcontrollerui_count,
flexcontrollerui_index,
) = str_read('3b 5x 2I', f)
# Build CDMaterials data
f.seek(cdmat_offset)
self.cdmaterials = read_offset_array(f, cdmat_count)
for ind, cdmat in enumerate(self.cdmaterials):
cdmat = cdmat.replace('\\', '/')
if cdmat[-1:] != '/':
cdmat += '/'
self.cdmaterials[ind] = cdmat
# All models fallback to checking the texture at a root folder.
if '/' not in self.cdmaterials:
self.cdmaterials.append('/')
# Build texture data
f.seek(texture_offset)
self.textures = [None] * texture_count # type: List[Tuple[str, int, int]]
tex_temp = [None] * texture_count # type: List[Tuple[int, Tuple[int, int, int]]]
for tex_ind in range(texture_count):
tex_temp[tex_ind] = (
f.tell(),
# Texture data:
# int: offset to the string, from start of struct.
# int: flags - appears to solely indicate 'teeth' materials...
# int: used, whatever that means.
# 4 unused bytes.
# 2 4-byte pointers in studiomdl to the material class, for
# server and client - shouldn't be in the file...
# 40 bytes of unused space (for expansion...)
str_read('iii 4x 8x 40x', f)
)
for tex_ind, (offset, data) in enumerate(tex_temp):
name_offset, flags, used = data
self.textures[tex_ind] = (
read_nullstr(f, offset + name_offset),
flags,
used,
)
f.seek(surfaceprop_index)
self.surfaceprop = read_nullstr(f)
if keyvalue_count:
self.keyvalues = read_nullstr(f, keyvalue_index)
else:
self.keyvalues = ''
f.seek(includemodel_index)
self.included_models = [None] * includemodel_count # type: List[IncludedMDL]
for i in range(includemodel_count):
pos = f.tell()
# This is two offsets from the start of the structures.
lbl_pos, filename_pos = str_read('II', f)
self.included_models[i] = IncludedMDL(
read_nullstr(f, pos + lbl_pos) if lbl_pos else '',
read_nullstr(f, pos + filename_pos) if filename_pos else '',
)
# Then return to after that struct - 4 bytes * 2.
f.seek(pos + 4 * 2)
self.sequences = self._read_sequences(f, sequence_off, sequence_count)