本文整理汇总了Python中six.BytesIO.seek方法的典型用法代码示例。如果您正苦于以下问题:Python BytesIO.seek方法的具体用法?Python BytesIO.seek怎么用?Python BytesIO.seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.BytesIO
的用法示例。
在下文中一共展示了BytesIO.seek方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_round_trip_rss
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def test_round_trip_rss():
now = datetime.utcnow().replace(microsecond=0)
feed = rss_gen.RSS2(
title='Feed Title',
link='http://example.com/link/',
description='feed description',
lastBuildDate=now,
items=[
rss_gen.RSSItem(
title='Item Title',
link='http://example.com/1/',
description='item description',
pubDate=now - timedelta(seconds=5),
),
rss_gen.RSSItem(
title='Second Item Title',
link='http://example.com/2/',
description='another item description',
pubDate=now - timedelta(seconds=10),
)
]
)
pseudofile = BytesIO()
feed.write_xml(pseudofile, encoding='utf-8')
pseudofile.flush()
pseudofile.seek(0)
parsed = parse_rss(pseudofile)
assert_feeds_equal(feed, parsed)
示例2: test_xmlrunner_check_for_valid_xml_streamout
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def test_xmlrunner_check_for_valid_xml_streamout(self):
"""
This test checks if the xml document is valid if there are more than
one testsuite and the output of the report is a single stream.
"""
class DummyTestA(unittest.TestCase):
def test_pass(self):
pass
class DummyTestB(unittest.TestCase):
def test_pass(self):
pass
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(DummyTestA))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(DummyTestB))
outdir = BytesIO()
runner = xmlrunner.XMLTestRunner(
stream=self.stream, output=outdir, verbosity=self.verbosity,
**self.runner_kwargs)
runner.run(suite)
outdir.seek(0)
output = outdir.read()
# Finally check if we have a valid XML document or not.
try:
minidom.parseString(output)
except Exception as e: # pragma: no cover
# note: we could remove the try/except, but it's more crude.
self.fail(e)
示例3: test_dump_and_load_
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def test_dump_and_load_(self):
in_resource = IdentifiableBook(
id=uuid.uuid4(),
purchased_from=From.Shop,
title='Consider Phlebas',
isbn='0-333-45430-8',
num_pages=471,
rrp=19.50,
fiction=True,
genre="sci-fi",
authors=[Author(name="Iain M. Banks")],
publisher=Publisher(name="Macmillan"),
published=[datetime.datetime(1987, 1, 1, tzinfo=utc)]
)
fp = BytesIO()
msgpack_codec.dump(in_resource, fp)
fp.seek(0)
out_resource = msgpack_codec.load(fp)
assert out_resource.id == in_resource.id
assert out_resource.purchased_from == in_resource.purchased_from
assert out_resource.title == in_resource.title
assert out_resource.isbn == in_resource.isbn
assert out_resource.num_pages == in_resource.num_pages
assert out_resource.rrp == in_resource.rrp
assert out_resource.fiction == in_resource.fiction
assert out_resource.genre == in_resource.genre
assert out_resource.authors[0].name == in_resource.authors[0].name
assert out_resource.publisher.name == in_resource.publisher.name
assert out_resource.published[0] == in_resource.published[0]
示例4: make_stream
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def make_stream(size):
"""Make a stream of a given size."""
s = BytesIO()
s.seek(size - 1)
s.write(b'\0')
s.seek(0)
return s
示例5: port_project
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def port_project(dir_name, schemas, spiders, extractors, selector='css'):
"""Create project layout, default files and project specific code."""
dir_name = class_name(dir_name)
zbuff = BytesIO()
archive = UpdatingZipFile(zbuff, "w", zipfile.ZIP_DEFLATED)
write_to_archive(archive, '', start_scrapy_project(dir_name).items())
items_py, schema_names = create_schemas(schemas)
write_to_archive(archive, dir_name, [('items.py', items_py)])
write_to_archive(archive, dir_name, create_library_files())
# XXX: Hack to load items.py file
items_no_relative = items_py.replace(
'from .utils.processors import', 'from portia2code.processors import'
)
mod = imp.new_module('%s.%s' % (dir_name, 'items'))
exec(items_no_relative, mod.__dict__)
items = vars(mod)
# Load schema objects from module
schema_names = {}
for _id, name in schemas.items():
name = '{}Item'.format(class_name(name.get('name', _id)))
schema_names[_id] = items[name]
schema_names['_PortiaItem'] = items['PortiaItem']
spider_data = create_spiders(spiders, schemas, extractors, schema_names,
selector)
write_to_archive(archive, dir_name, spider_data)
archive.finalize()
archive.close()
zbuff.seek(0)
return zbuff
示例6: is_zipstream
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def is_zipstream(data):
"""
just like zipfile.is_zipfile, but works upon buffers and streams
rather than filenames.
If data supports the read method, it will be treated as a stream
and read from to test whether it is a valid ZipFile.
If data also supports the tell and seek methods, it will be
rewound after being tested.
"""
if isinstance(data, (str, buffer)):
data = BytesIO(data)
if hasattr(data, "read"):
tell = 0
if hasattr(data, "tell"):
tell = data.tell()
try:
result = bool(_EndRecData(data))
except IOError:
result = False
if hasattr(data, "seek"):
data.seek(tell)
else:
raise TypeError("requies str, buffer, or stream-like object")
return result
示例7: test_load_write_file
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def test_load_write_file(self):
for fname in [DATA['empty_tck_fname'],
DATA['simple_tck_fname']]:
for lazy_load in [False, True]:
tck = TckFile.load(fname, lazy_load=lazy_load)
tck_file = BytesIO()
tck.save(tck_file)
loaded_tck = TckFile.load(fname, lazy_load=False)
assert_tractogram_equal(loaded_tck.tractogram, tck.tractogram)
# Check that the written file is the same as the one read.
tck_file.seek(0, os.SEEK_SET)
assert_equal(tck_file.read(), open(fname, 'rb').read())
# Save tractogram that has an affine_to_rasmm.
for lazy_load in [False, True]:
tck = TckFile.load(DATA['simple_tck_fname'], lazy_load=lazy_load)
affine = np.eye(4)
affine[0, 0] *= -1 # Flip in X
tractogram = Tractogram(tck.streamlines, affine_to_rasmm=affine)
new_tck = TckFile(tractogram, tck.header)
tck_file = BytesIO()
new_tck.save(tck_file)
tck_file.seek(0, os.SEEK_SET)
loaded_tck = TckFile.load(tck_file, lazy_load=False)
assert_tractogram_equal(loaded_tck.tractogram,
tractogram.to_world(lazy=True))
示例8: generate_glassbrain_image
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def generate_glassbrain_image(image_pk):
from neurovault.apps.statmaps.models import Image
import neurovault
import matplotlib as mpl
mpl.rcParams['savefig.format'] = 'jpg'
my_dpi = 50
fig = plt.figure(figsize=(330.0/my_dpi, 130.0/my_dpi), dpi=my_dpi)
img = Image.objects.get(pk=image_pk)
f = BytesIO()
try:
glass_brain = plot_glass_brain(img.file.path, figure=fig)
glass_brain.savefig(f, dpi=my_dpi)
except:
# Glass brains that do not produce will be given dummy image
this_path = os.path.abspath(os.path.dirname(__file__))
f = open(os.path.abspath(os.path.join(this_path,
"static","images","glass_brain_empty.jpg")))
raise
finally:
plt.close('all')
f.seek(0)
content_file = ContentFile(f.read())
img.thumbnail.save("glass_brain_%s.jpg" % img.pk, content_file)
img.save()
示例9: test_write_simple_file
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def test_write_simple_file(self):
tractogram = Tractogram(DATA['streamlines'],
affine_to_rasmm=np.eye(4))
tck_file = BytesIO()
tck = TckFile(tractogram)
tck.save(tck_file)
tck_file.seek(0, os.SEEK_SET)
new_tck = TckFile.load(tck_file)
assert_tractogram_equal(new_tck.tractogram, tractogram)
new_tck_orig = TckFile.load(DATA['simple_tck_fname'])
assert_tractogram_equal(new_tck.tractogram, new_tck_orig.tractogram)
tck_file.seek(0, os.SEEK_SET)
assert_equal(tck_file.read(),
open(DATA['simple_tck_fname'], 'rb').read())
# TCK file containing not well formatted entries in its header.
tck_file = BytesIO()
tck = TckFile(tractogram)
tck.header['new_entry'] = 'value\n' # \n not allowed
assert_raises(HeaderError, tck.save, tck_file)
tck.header['new_entry'] = 'val:ue' # : not allowed
assert_raises(HeaderError, tck.save, tck_file)
示例10: stream
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def stream(fname):
with open(fname, 'rb') as fp:
stream_ = BytesIO(
fp.read().replace(b'\x90', b'').replace(b'\x8b', b' ')
)
stream_.seek(0)
return stream_
示例11: kit_generator
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def kit_generator(maxn):
with zipfile.ZipFile('Archive.zip') as zf:
fl = zf.filelist
yielded = 0
for member in fl:
if 'MACOSX' in member.filename:
continue
i = member.filename.split('_')[0] #Was int($)
if maxn is not None and yielded > maxn:
return
with zf.open(member) as fp:
zf_b = BytesIO(fp.read())
zf_b.seek(0)
sub_zf = zipfile.ZipFile(zf_b)
try:
variant_fp = sub_zf.open('variants.vcf')
except KeyError:
print("No variants.vcf in kit {0}".format(i))
regions_fp = sub_zf.open('regions.bed')
yield variant_fp, regions_fp, i
yielded += 1
#raise StopIteration
variant_fp.close()
regions_fp.close()
示例12: test_dump_and_load_
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def test_dump_and_load_(self):
in_resource = Book(
title='Consider Phlebas',
num_pages=471,
rrp=19.50,
fiction=True,
genre="sci-fi",
authors=[Author(name="Iain M. Banks")],
publisher=Publisher(name="Macmillan"),
published=[datetime.datetime(1987, 1, 1, tzinfo=utc)]
)
fp = BytesIO()
msgpack_codec.dump(in_resource, fp)
fp.seek(0)
out_resource = msgpack_codec.load(fp)
self.assertEqual(out_resource.title, in_resource.title)
self.assertEqual(out_resource.num_pages, in_resource.num_pages)
self.assertEqual(out_resource.rrp, in_resource.rrp)
self.assertEqual(out_resource.fiction, in_resource.fiction)
self.assertEqual(out_resource.genre, in_resource.genre)
self.assertEqual(out_resource.authors[0].name, in_resource.authors[0].name)
self.assertEqual(out_resource.publisher.name, in_resource.publisher.name)
self.assertEqual(out_resource.published[0], in_resource.published[0])
示例13: filter
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def filter(self, im):
if self.sharpness:
im = sharpen(im, self.sharpness)
buf = BytesIO()
if self.palette:
if im.mode in ('RGBA', 'LA'):
alpha = im.split()[3]
alpha = Image.eval(alpha, lambda a: 255 if a > 0 else 0)
mask = Image.eval(alpha, lambda a: 255 if a == 0 else 0)
matte = Image.new("RGBA", im.size, self.background)
matte.paste(im, (0, 0), im)
matte = matte.convert("RGB").convert(
'P', palette=Image.ADAPTIVE, colors=self.colors - 1)
matte.paste(self.colors, mask)
matte.save(buf, "PNG", transparency=self.colors)
elif im.mode not in ('P'):
im = im.convert('P', palette=Image.ADAPTIVE,
colors=self.colors)
im.save(buf, 'PNG')
else:
im.save(buf, 'PNG')
else:
if not im.mode.startswith("RGB"):
im = im.convert('RGB')
im.save(buf, 'PNG')
buf.seek(0)
return buf
示例14: deepCopy
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def deepCopy(obj):
stream = BytesIO()
p = Pickler(stream, 1)
p.dump(obj)
stream.seek(0)
u = Unpickler(stream)
return u.load()
示例15: default
# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import seek [as 别名]
def default(self, obj):
try:
return super(ObjectJSONEncoder, self).default(obj)
except TypeError as e:
if "not JSON serializable" not in str(e):
raise
if isinstance(obj, datetime.datetime):
return {'ISO8601_datetime': obj.strftime('%Y-%m-%dT%H:%M:%S.%f%z')}
if isinstance(obj, datetime.date):
return {'ISO8601_date': obj.isoformat()}
if numpy is not None and isinstance(obj, numpy.ndarray) and obj.ndim == 1:
memfile = BytesIO()
numpy.save(memfile, obj)
memfile.seek(0)
serialized = json.dumps(memfile.read().decode('latin-1'))
d = {
'__ndarray__': serialized,
}
return d
else:
d = {
'__class__': obj.__class__.__qualname__,
'__module__': obj.__module__,
}
return d