本文整理汇总了Python中six.moves.StringIO.close方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.close方法的具体用法?Python StringIO.close怎么用?Python StringIO.close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.moves.StringIO
的用法示例。
在下文中一共展示了StringIO.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generateParserSummary
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def generateParserSummary(files):
valid = files['valid']
other = files['other']
failed = files['failed']
processed = files['processed']
output = StringIO()
output.write('Successful Files with transactions:\n')
# Successful Files
for n,t in valid:
output.write(' File Name: {}\n'.format(n))
output.write(' Transactions:\n')
for trans in t.transactions.all():
output.write(' CRN: {}\n'.format(trans.crn))
# Successful Files without transactions
output.write('\nSuccessful Files without transactions:\n')
for n,t in other:
output.write(' File Name: {}\n'.format(n))
# Failed files
output.write('\nFailed Files:\n')
for n,r in failed:
output.write(' File Name: {}\n'.format(n))
output.write(' Reason: {}\n'.format(r))
# Already processed Files
output.write('\nFiles previously processed:\n')
for n,t in processed:
output.write(' File Name: {}\n'.format(n))
contents = output.getvalue()
output.close()
return contents
示例2: render_and_save_variation
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def render_and_save_variation(self, name, content, variation):
"""
Renders the image variations and saves them to the storage
"""
content.seek(0)
img = Image.open(content)
if self.is_smaller(img, variation):
factor = 1
while (img.size[0] / factor > 2 * variation['width'] and
img.size[1] * 2 / factor > 2 * variation['height']):
factor *= 2
if factor > 1:
img.thumbnail((int(img.size[0] / factor),
int(img.size[1] / factor)), resample=resample)
if variation['crop']:
img = ImageOps.fit(img, (variation['width'], variation['height']), method=resample)
else:
img.thumbnail((variation['width'], variation['height']), resample=resample)
variation_name = self.get_variation_name(self.instance, self.field, variation)
file_buffer = StringIO()
format = self.get_file_extension(name).lower().replace('jpg', 'jpeg')
img.save(file_buffer, format)
self.storage.save(variation_name, ContentFile(file_buffer.getvalue()))
file_buffer.close()
示例3: render
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def render(self):
"""This is the tricky part, whith the rendered_content create a PDF"""
# The following is required for PDF generation
import xhtml2pdf.pisa as pisa # The import is changed to xhtml2pdf
if not self._is_rendered:
# File pointer needed to create the PDF in memory
buffer = StringIO()
# Create the PDF object, using the StringIO object as its "file."
pisa.CreatePDF(self.rendered_content, buffer,
link_callback=fetch_resources)
# Get the value of the StringIO buffer and write it to the response.
pdf = buffer.getvalue()
buffer.close()
self.write(pdf)
# Sets the appropriate PDF headers.
self['Content-Disposition'] = 'attachment; filename=%s' % (
self.filename, )
# The PDF has been rendered
self._is_rendered = True
for post_callback in self._post_render_callbacks:
post_callback(self)
return self
示例4: test_deqatn_10
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def test_deqatn_10(self):
"""
per nast/tpl/ptdmi1.dat
"""
model = BDF(debug=None)
model.cards_to_read.add('DEQATN')
model.test_deqatn = True
card = [
'deqatn 2 f(x,y,z)= 1.;',
' L=x+y',
]
model.add_card(card, 'DEQATN', is_list=False)
model.cross_reference()
s = StringIO()
model.write_bdf(s, close=False)
s.getvalue()
s.close()
eq = model.dequations[2]
x = zeros(10., dtype='float32')
y = zeros(11., dtype='float32')
z = zeros(12., dtype='float32')
#out = eq.func(x, y, z)
out = eq.func(1.0, 2.0)
print(out)
示例5: test_deqatn_9
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def test_deqatn_9(self):
"""
per nast/tpl/ptdmi1.dat
"""
model = BDF(debug=None)
model.cards_to_read.add('DEQATN')
model.test_deqatn = True
card = [
'deqatn 2 f(x,y,z)= 1.;',
' L=1+2+3+',
' + 4/min(1,2);',
' b= 4.;',
' h= 2.;',
' t1= 200.;',
' t2= 300.;',
' t=t1*(L-x)/L+t2*x/L',
' +4'
]
model.add_card(card, 'DEQATN', is_list=False)
model.cross_reference()
s = StringIO()
model.write_bdf(s, close=False)
s.getvalue()
s.close()
示例6: test_deqatn_6
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def test_deqatn_6(self):
func_str = 'def f(x, y, z):\n'
func_str += ' c = 3\n'
func_str += ' return x + y + z + c\n'
#func = exec(fnc_str)
s = StringIO()
s.write(s)
s.close()
exec (func_str)
f(1, 2, 3)
#func = exec func_str
assert f(1, 2, 3) == 9, func(1, 2, 3)
示例7: generateTransactionsSummary
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def generateTransactionsSummary(files,unmatched_only=False):
try:
# Split transactions into biller codes
biller_codes = {}
biller_code_emails = {}
if unmatched_only:
for f in files:
for t in f.transactions.all():
if t.biller_code in biller_codes:
txns = list(biller_codes[t.biller_code])
txns.append(t)
biller_codes[t.biller_code] = txns
else:
biller_codes[t.biller_code] = [t]
else:
for n, f in files:
for t in f.transactions.all():
if t.biller_code in biller_codes:
txns = list(biller_codes[t.biller_code])
txns.append(t)
biller_codes[t.biller_code] = txns
else:
biller_codes[t.biller_code] = [t]
# Generate summaries per biller code
for k,v in biller_codes.items():
matched = []
unmatched = []
for t in v:
if t.matched:
matched.append(t)
else:
unmatched.append(t)
output = StringIO()
if not unmatched_only:
# Matched txns
output.write('Matched transactions:\n')
for m in matched:
output.write(' CRN: {} Amount: ${}\n'.format(m.crn,m.amount))
# Unmatched txns
output.write('\nUnmatched transactions:\n')
for u in unmatched:
output.write(' CRN: {} Amount: ${}\n'.format(u.crn,u.amount))
contents = output.getvalue()
output.close()
# Add the biller code email
biller_code_emails[k] = contents
return biller_code_emails
except Exception as e:
traceback.print_exc(e)
raise
示例8: test_deqatn_3
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def test_deqatn_3(self):
model = BDF(debug=None)
model.cards_to_read.add('DEQATN')
model.test_deqatn = True
card = ['DEQATN 1000',
' MAXDIFF(t1,t2)=abs(t2-t1)/t1']
model.add_card(card, 'DEQATN', is_list=False)
model.cross_reference()
s = StringIO()
model.write_bdf(s, close=False)
s.getvalue()
#print(s.getvalue())
s.close()
示例9: File
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
class File(object):
def __init__(self, path, mode=None):
if path in files:
self.fp = StringIO(files[path])
else:
self.fp = StringIO(files[os.path.split(path)[-1]])
def __enter__(self):
return self.fp
def __exit__(self, *args):
return
def close(self, *args, **kwargs):
self.fp.close()
示例10: test_run_multiple_times_with_different_stdout_and_stderr
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def test_run_multiple_times_with_different_stdout_and_stderr(self):
stdout, stderr = StringIO(), StringIO()
self._run(stdout, stderr)
self._assert_normal_stdout_stderr_are_empty()
self._assert_output(stdout, [('My Suite', 2), ('My Test', 1)])
self._assert_output(stderr, [('Hello, world!', 1)])
stdout.close(); stderr.close()
output = StringIO()
self._run(output, output, variable='MESSAGE:Hi, again!')
self._assert_normal_stdout_stderr_are_empty()
self._assert_output(output, [('My Suite', 2), ('My Test', 1),
('Hi, again!', 1), ('Hello, world!', 0)])
output.close()
self._run(variable='MESSAGE:Last hi!')
self._assert_output(sys.__stdout__, [('My Suite', 2), ('My Test', 1)])
self._assert_output(sys.__stderr__, [('Last hi!', 1), ('Hello, world!', 0)])
示例11: StdoutCapture
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
class StdoutCapture(object):
def __init__(self):
self.captured = StringIO()
def start(self):
sys.stdout = self.captured
return self
def stop(self):
sys.stdout = sys.__stdout__
return self
def value(self):
self.captured.flush()
return self.captured.getvalue()
def close(self):
self.captured.close()
示例12: test_deqatn_4
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
def test_deqatn_4(self):
"""
per nast/tpl/ptdmi1.dat
"""
model = BDF(debug=None)
#model.cards_to_read.add('DEQATN')
model.test_deqatn = True
card = [
'deqatn 2 f(x,y,z)= 1.;',
' l=10.;',
' b= 4.;',
' h= 2.;',
' t1= 200.;',
' t2= 300.;',
' t=t1*(l-x)/l+t2*(x)/l',
]
model.add_card(card, 'DEQATN', is_list=False)
model.cross_reference()
s = StringIO()
model.write_bdf(s, close=False)
s.getvalue()
s.close()
示例13: ClosableOutput
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
class ClosableOutput(object):
encoding = None
def __init__(self, path):
self._output = StringIO()
self._path = path
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def write(self, data):
self._output.write(data)
def close(self):
self.value = self._output.getvalue()
self._output.close()
def __str__(self):
return self._path
示例14: CaptureStdOut
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
class CaptureStdOut(object):
"""
An logger that both prints to stdout and writes to file.
"""
def __init__(self, log_file_path = None, print_to_console = True, prefix = None):
"""
:param log_file_path: The path to save the records, or None if you just want to keep it in memory
:param print_to_console:
"""
self._print_to_console = print_to_console
if log_file_path is not None:
# self._log_file_path = os.path.join(base_dir, log_file_path.replace('%T', now))
make_file_dir(log_file_path)
self.log = open(log_file_path, 'w')
else:
self.log = StringIO()
self._log_file_path = log_file_path
self.old_stdout = _ORIGINAL_STDOUT
self.prefix = None if prefix is None else prefix
def __enter__(self):
self.old_stdout = sys.stdout
self.old_stderr = sys.stderr
sys.stdout = self
sys.stderr = self
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.flush()
sys.stderr.flush()
sys.stdout = self.old_stdout
sys.stderr = self.old_stderr
self.close()
def get_log_file_path(self):
assert self._log_file_path is not None, "You never specified a path when you created this logger, so don't come back and ask for one now"
return self._log_file_path
def write(self, message):
if self._print_to_console:
self.old_stdout.write(message if self.prefix is None or message=='\n' else self.prefix+message)
self.log.write(message)
self.log.flush()
def close(self):
if self._log_file_path is not None:
self.log.close()
def read(self):
if self._log_file_path is None:
return self.log.getvalue()
else:
with open(self._log_file_path) as f:
txt = f.read()
return txt
def __getattr__(self, item):
return getattr(self.old_stdout, item)
示例15: DataTable
# 需要导入模块: from six.moves import StringIO [as 别名]
# 或者: from six.moves.StringIO import close [as 别名]
#.........这里部分代码省略.........
assert signed==bool(sign), 'signature expected'
assert result.valid and result.fingerprint==fingerprint, 'invalid signature'
assert 'format' in data and data['format']==self.dataformat, "file format not supported"
assert 'version' in data and data['version'][0]<=self.version[0], "file version not supported"
assert 'fields' in data , "fields missing"
fields = data['fields']
self.rows = data['data']
columns, unknown = [], []
for field in fields:
if field in self.columns: columns.append(field)
elif self.ignore: unknown.append(field)
else: assert False, "unknown field '%s'" % field
if self.required:
for field in self.required:
assert field in columns, "missing required field '%s'" % field
self.fields = fields
self.read_columns = (columns,unknown)
elif mode=='w':
assert self.fileformat in ('json','jsondict') or self.file, 'file missing'
if self.fileformat=='csv':
if encrypt or sign: self.file = StringIO()
else: self.file = f
if not PY3:
import unicodecsv
writer = unicodecsv.writer
else:
writer = csv.writer
self.csv = writer(self.file,lineterminator='\n',dialect=self.dialect)
self.csv.writerow((self.dataformat,'%i.%i' % tuple(self.version)))
self.csv.writerow(self.columns)
else: # self.fileformat in ('json','jsondict'):
self.rows = []
def close(self):
"close input/output. StringIO output is left open"
if not self.mode: return
if self.mode=='r':
if self.fileformat=='csv' and self.encrypt: self.file.close() # close tmp buffer
elif self.fileformat in ('json','jsondict'): return
elif self.fileformat in ('json','jsondict','json-file','jsondict-file'):
import json
data = {'format':self.dataformat,'version':self.version,
'fields':list(self.columns),'data':self.rows}
if self.fileformat in ('json','jsondict'): output = self.file
else: output = None
if self.encrypt or self.sign:
data, result = json_encrypt(data, self.gpg, output=output,
encrypt=self.encrypt,sign=self.sign)
assert data and result,'encryption failed'
elif not output is None:
output.update(data)
data = output
if self.fileformat in ('json','jsondict'): return data
if self.pretty:
json.dump(data,self.file, sort_keys=True, indent=2, separators=(',', ': '))
else:
json.dump(data,self.file)
elif self.encrypt or self.sign:
from six import PY3, BytesIO, StringIO
if PY3 and isinstance(self.file,StringIO):
data = self.file.getvalue()
if self.encrypt:
result = self.gpg.encrypt_str(data,self.encrypt,default_key=self.sign)
else: #sign
result = self.gpg.sign_str(data)
else: