本文整理汇总了Python中io.BytesIO方法的典型用法代码示例。如果您正苦于以下问题:Python io.BytesIO方法的具体用法?Python io.BytesIO怎么用?Python io.BytesIO使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类io
的用法示例。
在下文中一共展示了io.BytesIO方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _deserialize
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def _deserialize(self, data, type_):
if self.compress:
# decompress the data if needed
data = lz4.frame.decompress(data)
if type_ == _NUMPY:
# deserialize numpy arrays
buf = io.BytesIO(data)
data = np.load(buf)
elif type_ == _PICKLE:
# deserialize other python objects
data = pickle.loads(data)
else:
# Otherwise we just return data as it is (bytes)
pass
return data
示例2: hash
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def hash(self, state: str) -> str:
"""Generate a hash representing the current sample state.
:param state: string capturing the current system configuration state
This function must be overridden to generate a meaningful hash for the current
set of input samples."""
newstate = io.BytesIO(state.encode('utf-8'))
for k in ('input_patterns', 'samples_dir', 'val_dir', 'val_num', 'val_perc',
'test_dir', 'test_num', 'test_perc', 'random_seed'):
newstate.write(str(getattr(self, k)).encode('utf-8'))
md5 = hashlib.md5()
md5.update(newstate.getvalue())
return md5.hexdigest()
示例3: __init__
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def __init__(self, name, width, height, preact=True,
postact=False, model_nm=None, props=None):
super().__init__(name, preact=preact,
postact=postact, model_nm=model_nm,
props=props)
self.disp_census = True
self.width = width
self.height = height
self.max_dist = self.width * self.height
self.scatter_plot = None
self.plot_title = "Agent Positions"
# it only makes sense to plot agents in a spatial env, so add this here:
self.menu.view.add_menu_item("s",
menu.MenuLeaf("(s)catter plot",
self.plot))
self.image_bytes = io.BytesIO()
示例4: deserialize
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def deserialize(rawbytes):
'''
Deserialize given bytes according to the supported Avro schema.
:param rawbytes: A buffered I/O implementation using an in-memory bytes buffer.
:returns : List of ``str`` objects, extracted from the binary stream.
:rtype : ``list``
'''
decoder = avro.io.BinaryDecoder(io.BytesIO(rawbytes))
reader = avro.io.DatumReader(avro.schema.parse(AVSC))
try: return reader.read(decoder)[list.__name__]
except Exception as exc:
logging.getLogger('SPOT.INGEST.COMMON.SERIALIZER')\
.error('[{0}] {1}'.format(exc.__class__.__name__, exc.message))
return []
示例5: serialize
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def serialize(value):
'''
Convert a ``list`` object to an avro-encoded format.
:param value: List of ``str`` objects.
:returns : A buffered I/O implementation using an in-memory bytes buffer.
:rtype : ``str``
'''
writer = avro.io.DatumWriter(avro.schema.parse(AVSC))
rawbytes = io.BytesIO()
try:
writer.write({ list.__name__: value }, avro.io.BinaryEncoder(rawbytes))
return rawbytes
except avro.io.AvroTypeException:
logging.getLogger('SPOT.INGEST.COMMON.SERIALIZER')\
.error('The type of ``{0}`` is not supported by the Avro schema.'
.format(type(value).__name__))
return None
示例6: screenshot
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def screenshot(self, name):
'''
screenshot()
Takes a screenshot of the browser
'''
if do_crop:
print('cropping screenshot')
# Grab screenshot rather than saving
im = self.browser.get_screenshot_as_png()
im = Image.open(BytesIO(im))
# Crop to specifications
im = im.crop((crop_x, crop_y, crop_width, crop_height))
im.save(name)
else:
self.browser.save_screenshot(name)
print("success saving screenshot: %s" % name)
return name
示例7: _serialize_data
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def _serialize_data(self, data):
# Default to raw bytes
type_ = _BYTES
if isinstance(data, np.ndarray):
# When the data is a numpy array, use the more compact native
# numpy format.
buf = io.BytesIO()
np.save(buf, data)
data = buf.getvalue()
type_ = _NUMPY
elif not isinstance(data, (bytearray, bytes)):
# Everything else except byte data is serialized in pickle format.
data = pickle.dumps(data)
type_ = _PICKLE
if self.compress:
# Optional compression
data = lz4.frame.compress(data)
return type_, data
示例8: ls
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def ls(args):
bucket = resources.s3.Bucket(args.billing_reports_bucket.format(account_id=ARN.get_account_id()))
now = datetime.utcnow()
year = args.year or now.year
month = str(args.month or now.month).zfill(2)
next_year = year + ((args.month or now.month) + 1) // 12
next_month = str(((args.month or now.month) + 1) % 12).zfill(2)
manifest_name = "aegea/{report}/{yr}{mo}01-{next_yr}{next_mo}01/{report}-Manifest.json"
manifest_name = manifest_name.format(report=__name__, yr=year, mo=month, next_yr=next_year, next_mo=next_month)
try:
manifest = json.loads(bucket.Object(manifest_name).get().get("Body").read())
for report_key in manifest["reportKeys"]:
report = BytesIO(bucket.Object(report_key).get().get("Body").read())
with gzip.GzipFile(fileobj=report) as fh:
reader = csv.DictReader(fh)
for line in reader:
page_output(tabulate(filter_line_items(reader, args), args))
except ClientError as e:
msg = 'Unable to get report {} from {}: {}. Run "aegea billing configure" to enable reports.'
raise AegeaException(msg.format(manifest_name, bucket, e))
示例9: call_command
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def call_command():
from django.core.management import call_command
class CallCommand(object):
def __init__(self):
self.io = BytesIO()
def __call__(self, *args, **kwargs):
self.io = BytesIO()
stdout = sys.stdout
try:
sys.stdout = self.io
call_command(*args, **kwargs)
finally:
sys.stdout = stdout
return self
@property
def stdout(self):
return self.io.getvalue()
return CallCommand()
示例10: serialize_ndarray_npy
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def serialize_ndarray_npy(o):
"""
Serializes a :obj:`numpy.ndarray` using numpy's built-in :obj:`save` function.
This produces totally unreadable (and very un-JSON-like) results (in "npy"
format), but it's basically guaranteed to work in 100% of cases.
Args:
o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.
Returns:
A dictionary that can be passed to :obj:`json.dumps`.
"""
with io.BytesIO() as f:
np.save(f, o)
f.seek(0)
serialized = json.dumps(f.read().decode('latin-1'))
return dict(
_type='np.ndarray',
npy=serialized)
示例11: deserialize_ndarray_npy
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def deserialize_ndarray_npy(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's
:obj:`save` function.
Args:
d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created
using :obj:`numpy.save`.
Returns:
An :obj:`ndarray` object.
"""
with io.BytesIO() as f:
f.write(json.loads(d['npy']).encode('latin-1'))
f.seek(0)
return np.load(f)
示例12: download_image
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def download_image(image_id, url, x1, y1, x2, y2, output_dir):
"""Downloads one image, crops it, resizes it and saves it locally."""
output_filename = os.path.join(output_dir, image_id + '.png')
if os.path.exists(output_filename):
# Don't download image if it's already there
return True
try:
# Download image
url_file = urlopen(url)
if url_file.getcode() != 200:
return False
image_buffer = url_file.read()
# Crop, resize and save image
image = Image.open(BytesIO(image_buffer)).convert('RGB')
w = image.size[0]
h = image.size[1]
image = image.crop((int(x1 * w), int(y1 * h), int(x2 * w),
int(y2 * h)))
image = image.resize((299, 299), resample=Image.ANTIALIAS)
image.save(output_filename)
except IOError:
return False
return True
示例13: logscmd
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def logscmd(self, message):
""".logs <level>
Dumps logs. Loglevels below WARNING may contain personal info."""
args = utils.get_args(message)
if not len(args) == 1:
await message.edit(self.strings["set_loglevel"])
return
try:
lvl = int(args[0])
except ValueError:
# It's not an int. Maybe it's a loglevel
lvl = getattr(logging, args[0].upper(), None)
if lvl is None:
await message.edit(self.strings["bad_loglevel"])
return
await message.edit(self.strings["uploading_logs"])
[handler] = logging.getLogger().handlers
logs = ("\n".join(handler.dumps(lvl))).encode("utf-8")
if not len(logs) > 0:
await message.edit(self.strings["no_logs"].format(lvl))
return
logs = BytesIO(logs)
logs.name = self.strings["logs_filename"]
await message.client.send_file(message.to_id, logs, caption=self.strings["logs_caption"].format(lvl))
await message.delete()
示例14: upload_image
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def upload_image(self, filename=None, filedata=None, tag=None):
token = self.auth.upload_token(self.bucket)
if filedata is None:
with open(filename, 'rb') as f:
filedata = f.read()
with BytesIO(filedata) as f:
ext = imghdr.what(f)
prefix = tag or "img"
name = "%s/%02x.%s" % (prefix, self.counter.incr(), ext)
ret, info = self.qiniu.put_data(token, name, filedata)
if ret is None:
return
return self.base_url + name
示例15: get_image
# 需要导入模块: import io [as 别名]
# 或者: from io import BytesIO [as 别名]
def get_image(self):
"""
Get an image from the camera.
Returns image data as a BytesIO object.
"""
url = "http://{}/image.jpg".format(self.host)
encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')
headers = {
'Authorization': 'Basic ' + encoded
}
result = requests.get(url, headers=headers)
if result.ok:
return BytesIO(result.content)
else:
return None