本文整理汇总了Python中six.BytesIO方法的典型用法代码示例。如果您正苦于以下问题:Python six.BytesIO方法的具体用法?Python six.BytesIO怎么用?Python six.BytesIO使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six
的用法示例。
在下文中一共展示了six.BytesIO方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testLeapCountDecodesProperly
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def testLeapCountDecodesProperly(self):
# This timezone has leapcnt, and failed to decode until
# Eugene Oden notified about the issue.
# As leap information is currently unused (and unstored) by tzfile() we
# can only indirectly test this: Take advantage of tzfile() not closing
# the input file if handed in as an opened file and assert that the
# full file content has been read by tzfile(). Note: For this test to
# work NEW_YORK must be in TZif version 1 format i.e. no more data
# after TZif v1 header + data has been read
fileobj = BytesIO(base64.b64decode(NEW_YORK))
tz.tzfile(fileobj)
# we expect no remaining file content now, i.e. zero-length; if there's
# still data we haven't read the file format correctly
remaining_tzfile_content = fileobj.read()
self.assertEqual(len(remaining_tzfile_content), 0)
示例2: keep_file
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def keep_file(self, task, response, min_size=None, max_size=None):
"""Decide whether to keep the image
Compare image size with ``min_size`` and ``max_size`` to decide.
Args:
response (Response): response of requests.
min_size (tuple or None): minimum size of required images.
max_size (tuple or None): maximum size of required images.
Returns:
bool: whether to keep the image.
"""
try:
img = Image.open(BytesIO(response.content))
except (IOError, OSError):
return False
task['img_size'] = img.size
if min_size and not self._size_gt(img.size, min_size):
return False
if max_size and not self._size_lt(img.size, max_size):
return False
return True
示例3: unpacked
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def unpacked(cls, raw):
# B = unsigned char
# !I = network-order (big-endian) unsigned int
raw = six.BytesIO(raw)
raw_chars = raw.read(4)
if raw_chars:
version, type, seq_no, flags = struct.unpack(
'BBBB',
raw_chars
)
session_id, length = struct.unpack('!II', raw.read(8))
return cls(version, type, session_id, length, seq_no, flags)
else:
raise ValueError(
"Unable to extract data from header. Likely the TACACS+ key does not match between server and client"
)
示例4: unpacked
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def unpacked(cls, raw):
# 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
#
# +----------------+----------------+----------------+----------------+
# | status | flags | server_msg len |
# +----------------+----------------+----------------+----------------+
# | data len | server_msg ...
# +----------------+----------------+----------------+----------------+
# | data ...
# +----------------+----------------+
# B = unsigned char
# !H = network-order (big-endian) unsigned short
raw = six.BytesIO(raw)
status, flags = struct.unpack('BB', raw.read(2))
server_msg_len, data_len = struct.unpack('!HH', raw.read(4))
server_msg = raw.read(server_msg_len)
data = raw.read(data_len)
return cls(status, flags, server_msg, data)
示例5: unpacked
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def unpacked(cls, raw):
# 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
# +----------------+----------------+----------------+----------------+
# | server_msg len | data_len |
# +----------------+----------------+----------------+----------------+
# | status | server_msg ...
# +----------------+----------------+----------------+----------------+
# | data ...
# +----------------+
# B = unsigned char
# !H = network-order (big-endian) unsigned short
raw = six.BytesIO(raw)
server_msg_len, data_len = struct.unpack('!HH', raw.read(4))
status = struct.unpack('B', raw.read(1))[0]
server_msg = raw.read(server_msg_len)
data = raw.read(data_len) if data_len else b''
return cls(status, server_msg, data)
示例6: FigureToSummary
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def FigureToSummary(name, fig):
"""Create tf.Summary proto from matplotlib.figure.Figure.
Args:
name: Summary name.
fig: A matplotlib figure object.
Returns:
A `tf.Summary` proto containing the figure rendered to an image.
"""
canvas = backend_agg.FigureCanvasAgg(fig)
fig.canvas.draw()
ncols, nrows = fig.canvas.get_width_height()
png_file = six.BytesIO()
canvas.print_figure(png_file)
png_str = png_file.getvalue()
return tf.Summary(value=[
tf.Summary.Value(
tag='%s/image' % name,
image=tf.Summary.Image(
height=nrows,
width=ncols,
colorspace=3,
encoded_image_string=png_str))
])
示例7: __getitem__
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def __getitem__(self, index):
img, target = None, None
env = self.env
with env.begin(write=False) as txn:
imgbuf = txn.get(self.keys[index])
buf = six.BytesIO()
buf.write(imgbuf)
buf.seek(0)
img = Image.open(buf).convert('RGB')
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
示例8: _generate_time_steps
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def _generate_time_steps(self, trajectory_list):
"""Transforms time step observations to frames of a video."""
for time_step in gym_env_problem.GymEnvProblem._generate_time_steps(
self, trajectory_list):
# Convert the rendered observations from numpy to png format.
frame_np = np.array(time_step.pop(env_problem.OBSERVATION_FIELD))
frame_np = frame_np.reshape(
[self.frame_height, self.frame_width, self.num_channels])
# TODO(msaffar) Add support for non RGB rendered environments
frame = png.from_array(frame_np, "RGB", info={"bitdepth": 8})
frame_buffer = six.BytesIO()
frame.save(frame_buffer)
# Put the encoded frame back.
time_step[_IMAGE_ENCODED_FIELD] = [frame_buffer.getvalue()]
time_step[_IMAGE_FORMAT_FIELD] = [_FORMAT]
time_step[_IMAGE_HEIGHT_FIELD] = [self.frame_height]
time_step[_IMAGE_WIDTH_FIELD] = [self.frame_width]
# Add the frame number
time_step[_FRAME_NUMBER_FIELD] = time_step[env_problem.TIMESTEP_FIELD]
yield time_step
示例9: load
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def load(f, persistent_load=PersistentNdarrayLoad):
"""Load a file that was dumped to a zip file.
:param f: The file handle to the zip file to load the object from.
:type f: file
:param persistent_load: The persistent loading function to use for
unpickling. This must be compatible with the `persisten_id` function
used when pickling.
:type persistent_load: callable, optional
.. versionadded:: 0.8
"""
with closing(zipfile.ZipFile(f, 'r')) as zip_file:
p = pickle.Unpickler(BytesIO(zip_file.open('pkl').read()))
p.persistent_load = persistent_load(zip_file)
return p.load()
示例10: test_serialize_and_deserialize_multi_np
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def test_serialize_and_deserialize_multi_np():
x = np.random.random((1, ))
y = np.random.random((2, 3))
z = np.random.random((1, 5, 2))
values = {'x': x, 'y': y, 'z': z}
# write out values in x
f = BytesIO()
serde_weights.write_np_values(values, f)
# reset file so it appears to be freshly opened for deserialize_weights
f.seek(0)
de_values = serde_weights.read_np_values(f)
assert values.keys() == de_values.keys()
for k, v in values.items():
assert (de_values[k] == v).all()
示例11: test_read_file
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def test_read_file(self):
ASSET_FILE_NAMES = [u'Read.txt', u'读.txt']
for assert_file_name in ASSET_FILE_NAMES:
REMOTE_PATH = join(UNIQUE_PATH, assert_file_name)
test_file = six.BytesIO()
test_file.write(u"你好世界 Hello World".encode('utf-8'))
test_file.seek(0)
self.storage.save(REMOTE_PATH, test_file)
fil = self.storage.open(REMOTE_PATH, 'r')
assert fil._is_read == False
content = fil.read()
assert content.startswith(u"你好")
assert fil._is_read == True
# Test open mode
fil = self.storage.open(REMOTE_PATH, 'rb')
bin_content = fil.read()
assert bin_content.startswith(u"你好".encode('utf-8'))
示例12: GetProperty
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def GetProperty(self, value_mask, items, is_checked=True):
buf = six.BytesIO()
buf.write(struct.pack("=xx2xI", value_mask))
if value_mask & CA.Counter:
counter = items.pop(0)
buf.write(struct.pack("=I", counter))
if value_mask & CA.Value:
value = items.pop(0)
buf.write(value.pack() if hasattr(value, "pack") else INT64.synthetic(*value).pack())
if value_mask & CA.ValueType:
valueType = items.pop(0)
buf.write(struct.pack("=I", valueType))
if value_mask & CA.Events:
events = items.pop(0)
buf.write(struct.pack("=I", events))
return self.send_request(59, buf, GetPropertyCookie, is_checked=is_checked)
示例13: test_50_get
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def test_50_get(self):
io = BytesIO()
self.webdav.download('handler.py', io)
self.assertEqual(utils.text(inspect.getsource(data_handler)), utils.text(io.getvalue()))
io.close()
io = BytesIO()
self.webdav.download('sample_handler.py', io)
self.assertEqual(utils.text(inspect.getsource(data_sample_handler)), utils.text(io.getvalue()))
io.close()
示例14: encode_image_array_as_png_str
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def encode_image_array_as_png_str(image):
"""Encodes a numpy array into a PNG string.
Args:
image: a numpy array with shape [height, width, 3].
Returns:
PNG encoded image string.
"""
image_pil = Image.fromarray(np.uint8(image))
output = six.BytesIO()
image_pil.save(output, format='PNG')
png_string = output.getvalue()
output.close()
return png_string
示例15: decode_img_from_buf
# 需要导入模块: import six [as 别名]
# 或者: from six import BytesIO [as 别名]
def decode_img_from_buf(buf, backend='cv2'):
if backend == 'pil':
buf = six.BytesIO(buf)
img = Image.open(buf).convert('RGB')
elif backend == 'cv2':
buf = np.frombuffer(buf, np.uint8)
img = cv2.imdecode(buf, 1)[..., ::-1]
else:
raise NotImplementedError
return img