本文整理汇总了Python中six.StringIO.close方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.close方法的具体用法?Python StringIO.close怎么用?Python StringIO.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.StringIO
的用法示例。
在下文中一共展示了StringIO.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_correct_indentation_diff
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def get_correct_indentation_diff(code, filename):
"""
Generate a diff to make code correctly indented.
:param code: a string containing a file's worth of Python code
:param filename: the filename being considered (used in diff generation only)
:returns: a unified diff to make code correctly indented, or
None if code is already correctedly indented
"""
code_buffer = StringIO(code)
output_buffer = StringIO()
reindenter = reindent.Reindenter(code_buffer)
reindenter.run()
reindenter.write(output_buffer)
reindent_output = output_buffer.getvalue()
output_buffer.close()
if code != reindent_output:
diff_generator = difflib.unified_diff(code.splitlines(True), reindent_output.splitlines(True),
fromfile=filename, tofile=filename + " (reindented)")
# work around http://bugs.python.org/issue2142
diff_tuple = map(clean_diff_line_for_python_bug_2142, diff_generator)
diff = "".join(diff_tuple)
return diff
else:
return None
示例2: test_roundtrip_sequence_collections_and_alignments
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def test_roundtrip_sequence_collections_and_alignments(self):
fps = list(map(lambda e: list(map(get_data_path, e)),
[('empty', 'empty'),
('fasta_sequence_collection_different_type',
'qual_sequence_collection_different_type')]))
for reader, writer in ((_fasta_to_sequence_collection,
_sequence_collection_to_fasta),
(_fasta_to_alignment,
_alignment_to_fasta)):
for fasta_fp, qual_fp in fps:
# read
obj1 = reader(fasta_fp, qual=qual_fp)
# write
fasta_fh = StringIO()
qual_fh = StringIO()
writer(obj1, fasta_fh, qual=qual_fh)
fasta_fh.seek(0)
qual_fh.seek(0)
# read
obj2 = reader(fasta_fh, qual=qual_fh)
fasta_fh.close()
qual_fh.close()
# TODO remove this custom equality testing code when
# SequenceCollection has an equals method (part of #656).
# We need this method to include IDs and description in the
# comparison (not part of SequenceCollection.__eq__).
self.assertEqual(obj1, obj2)
for s1, s2 in zip(obj1, obj2):
self.assertTrue(s1.equals(s2))
示例3: _in_process_execute
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def _in_process_execute(self, cli_ctx, command, expect_failure=False):
from six import StringIO
from vcr.errors import CannotOverwriteExistingCassetteException
if command.startswith('az '):
command = command[3:]
stdout_buf = StringIO()
logging_buf = StringIO()
try:
# issue: stderr cannot be redirect in this form, as a result some failure information
# is lost when command fails.
self.exit_code = cli_ctx.invoke(shlex.split(command), out_file=stdout_buf) or 0
self.output = stdout_buf.getvalue()
self.applog = logging_buf.getvalue()
except CannotOverwriteExistingCassetteException as ex:
raise AssertionError(ex)
except CliExecutionError as ex:
if expect_failure:
self.exit_code = 1
self.output = stdout_buf.getvalue()
self.applog = logging_buf.getvalue()
elif ex.exception:
raise ex.exception
else:
raise ex
except Exception as ex: # pylint: disable=broad-except
self.exit_code = 1
self.output = stdout_buf.getvalue()
self.process_error = ex
finally:
stdout_buf.close()
logging_buf.close()
示例4: fetch_data
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def fetch_data(self):
# create a data frame directly from the full text of
# the response from the returned file-descriptor.
data = self.fetch_url(self.url)
fd = StringIO()
if isinstance(data, str):
fd.write(data)
else:
for chunk in data:
fd.write(chunk)
self.fetch_size = fd.tell()
fd.seek(0)
try:
# see if pandas can parse csv data
frames = read_csv(fd, **self.pandas_kwargs)
frames_hash = hashlib.md5(str(fd.getvalue()).encode('utf-8'))
self.fetch_hash = frames_hash.hexdigest()
except pd.parser.CParserError:
# could not parse the data, raise exception
raise Exception('Error parsing remote CSV data.')
finally:
fd.close()
return frames
示例5: test_roundtrip_biological_sequences
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def test_roundtrip_biological_sequences(self):
fps = list(map(lambda e: list(map(get_data_path, e)),
[('fasta_multi_seq_roundtrip',
'qual_multi_seq_roundtrip'),
('fasta_sequence_collection_different_type',
'qual_sequence_collection_different_type')]))
for reader, writer in ((_fasta_to_biological_sequence,
_biological_sequence_to_fasta),
(partial(_fasta_to_dna_sequence,
validate=False),
_dna_sequence_to_fasta),
(partial(_fasta_to_rna_sequence,
validate=False),
_rna_sequence_to_fasta),
(partial(_fasta_to_protein_sequence,
validate=False),
_protein_sequence_to_fasta)):
for fasta_fp, qual_fp in fps:
# read
obj1 = reader(fasta_fp, qual=qual_fp)
# write
fasta_fh = StringIO()
qual_fh = StringIO()
writer(obj1, fasta_fh, qual=qual_fh)
fasta_fh.seek(0)
qual_fh.seek(0)
# read
obj2 = reader(fasta_fh, qual=qual_fh)
fasta_fh.close()
qual_fh.close()
self.assertEqual(obj1, obj2)
示例6: test_roundtrip_sequence_collections_and_alignments
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def test_roundtrip_sequence_collections_and_alignments(self):
fps = list(map(lambda e: list(map(get_data_path, e)),
[('empty', 'empty'),
('fasta_sequence_collection_different_type',
'qual_sequence_collection_different_type')]))
for reader, writer in ((_fasta_to_sequence_collection,
_sequence_collection_to_fasta),
(_fasta_to_alignment,
_alignment_to_fasta)):
for fasta_fp, qual_fp in fps:
# read
obj1 = reader(fasta_fp, qual=qual_fp)
# write
fasta_fh = StringIO()
qual_fh = StringIO()
writer(obj1, fasta_fh, qual=qual_fh)
fasta_fh.seek(0)
qual_fh.seek(0)
# read
obj2 = reader(fasta_fh, qual=qual_fh)
fasta_fh.close()
qual_fh.close()
self.assertEqual(obj1, obj2)
示例7: __call__
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def __call__(self, parser, namespace, values, option_string=None):
output = StringIO()
parser.print_help(output)
text = output.getvalue()
output.close()
pydoc.pager(text)
parser.exit()
示例8: write_to_db
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def write_to_db(self, db, transaction=None, commit=True):
if transaction is None:
transaction = db
fp = StringIO()
if len(self) < Timeseries.MAX_ALL_BOTTOM:
top = ''
middle = None
self.write(fp)
bottom = fp.getvalue()
else:
dates = sorted(self.keys())
self.write(fp, end=dates[Timeseries.ROWS_IN_TOP_BOTTOM - 1])
top = fp.getvalue()
fp.truncate(0)
fp.seek(0)
self.write(fp, start=dates[Timeseries.ROWS_IN_TOP_BOTTOM],
end=dates[-(Timeseries.ROWS_IN_TOP_BOTTOM + 1)])
middle = self.blob_create(
zlib.compress(fp.getvalue().encode('ascii')))
fp.truncate(0)
fp.seek(0)
self.write(fp, start=dates[-Timeseries.ROWS_IN_TOP_BOTTOM])
bottom = fp.getvalue()
fp.close()
c = db.cursor()
c.execute("DELETE FROM ts_records WHERE id=%d" % (self.id))
c.execute("""INSERT INTO ts_records (id, top, middle, bottom)
VALUES (%s, %s, %s, %s)""", (self.id, top, middle,
bottom))
c.close()
if commit:
transaction.commit()
示例9: _save_data
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def _save_data(self, key, hmmfile, stofile, colnames, x, cur=None):
with open(hmmfile) as fh:
hmmdata = fh.read()
with open(stofile) as fh:
stodata = fh.read()
phylo = True if x.dtype == float else False
coldata = json.dumps(colnames)
xfile = StringIO()
np.save(xfile, x)
xdata = bz2.compress(xfile.getvalue(), 9)
xfile.close()
closable = False
if cur is None:
conn = sqlite3.connect(self.__filename)
cur = conn.cursor()
closable = True
IdepiProjectData.__insert(cur, IdepiProjectData.__HMM, key, hmmdata)
IdepiProjectData.__insert(cur, IdepiProjectData.__ALIGNMENT, key, stodata)
IdepiProjectData.__insert(cur, IdepiProjectData.__COLUMNS, key, coldata)
if phylo:
IdepiProjectData.__insert(cur, IdepiProjectData.__PHYLO_DATA, key, xdata)
else:
IdepiProjectData.__insert(cur, IdepiProjectData.__DISCRETE_DATA, key, xdata)
if closable:
conn.close()
示例10: open
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def open(self, filename=None):
if filename is None:
filename = self._base_uri
else:
if self._file_type == 's3':
filename = urljoin(self._base_uri.replace(
's3://', 'http://'), filename.replace('\\', '/')).replace('http://', 's3://')
elif self._file_type == 'http':
filename = urljoin(self._base_uri, filename.replace('\\', '/'))
else:
filename = os.path.abspath(os.path.join(os.path.dirname(
self._base_uri.replace('\\', '/')), filename.replace('\\', '/')))
f = None
if self._file_type == 's3':
uri_header, uri_body = filename.split('://', 1)
us = uri_body.split('/')
bucketname = us.pop(0)
key = '/'.join(us)
logger.info('Opening {}'.format(key))
f = StringIO(self._s3_bucket.Object(key).get()['Body'].read())
elif self._file_type == 'http':
f = request.urlopen(filename)
else:
f = open(filename, 'rb')
yield f
f.close()
示例11: _log_metadata
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def _log_metadata(self, project):
dependencies = self._extract_dependencies(project)
output = StringIO()
writer = csv.DictWriter(output, delimiter=',',
quoting=csv.QUOTE_MINIMAL,
lineterminator="\n",
fieldnames=ordered_fieldnames)
for dep in dependencies:
license, homepage = self._get_pypi_license_homepage(**dep)
if homepage and 'launchpad.net' in homepage:
license = self._get_launchpad_license(homepage)
if license == "UNKNOWN":
license = ""
if homepage == "UNKNOWN":
homepage = ""
info = dep
info['license_info'] = license
info['homepage'] = homepage
info['project_name'] = project.name
writer.writerow(info)
self._project_deps[project.name] = output.getvalue()
output.close()
示例12: test_config_yaml_with_env
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def test_config_yaml_with_env():
#assert False, "Not Implemented"
fileobj = StringIO(CONFIG)
result = config_from_yaml(fileobj=fileobj, silent=True, upper_only=False, parse_env=True)
fileobj.close()
print(result)
assert result['postfix']['home'] == HOME_ENV
示例13: test_roundtrip_biological_sequences
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def test_roundtrip_biological_sequences(self):
fps = map(get_data_path, ['fasta_multi_seq_roundtrip',
'fasta_sequence_collection_different_type'])
for reader, writer in ((_fasta_to_biological_sequence,
_biological_sequence_to_fasta),
(_fasta_to_nucleotide_sequence,
_nucleotide_sequence_to_fasta),
(_fasta_to_dna_sequence,
_dna_sequence_to_fasta),
(_fasta_to_rna_sequence,
_rna_sequence_to_fasta),
(_fasta_to_protein_sequence,
_protein_sequence_to_fasta)):
for fp in fps:
# read
obj1 = reader(fp)
# write
fh = StringIO()
writer(obj1, fh)
fh.seek(0)
# read
obj2 = reader(fh)
fh.close()
self.assertTrue(obj1.equals(obj2))
示例14: make_word
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def make_word(self, seed=None, min=3, max=30, tries=100):
if seed is not None or not self._seeded:
self._random.seed(seed)
out = StringIO()
tail = CircularBuffer(self.tail)
tail.append(WORD_START)
while True:
c = self.choose_transition(self.transitions(tail.tuple()), self._random.random())
if c == WORD_STOP:
break
else:
out.write(c)
tail.append(c)
result = out.getvalue()
out.close()
if min <= len(result) <= max:
return result
elif tries > 0:
return self.make_word(seed, min, max, tries - 1)
else:
raise MatrixError
示例15: _in_process_execute
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import close [as 别名]
def _in_process_execute(self, command):
# from azure.cli import as cli_main
from azure.cli.main import main as cli_main
from six import StringIO
from vcr.errors import CannotOverwriteExistingCassetteException
if command.startswith('az '):
command = command[3:]
output_buffer = StringIO()
try:
# issue: stderr cannot be redirect in this form, as a result some failure information
# is lost when command fails.
self.exit_code = cli_main(shlex.split(command), file=output_buffer) or 0
self.output = output_buffer.getvalue()
except CannotOverwriteExistingCassetteException as ex:
raise AssertionError(ex)
except CliExecutionError as ex:
if ex.exception:
raise ex.exception
else:
raise ex
except Exception as ex: # pylint: disable=broad-except
self.exit_code = 1
self.output = output_buffer.getvalue()
self.process_error = ex
finally:
output_buffer.close()