本文整理汇总了Python中six.StringIO.truncate方法的典型用法代码示例。如果您正苦于以下问题:Python StringIO.truncate方法的具体用法?Python StringIO.truncate怎么用?Python StringIO.truncate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six.StringIO
的用法示例。
在下文中一共展示了StringIO.truncate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_to_db
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [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()
示例2: test_import_ignore
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_import_ignore(self):
output = StringIO()
call_command(
'import_json',
'--main-component', 'test',
'--project', 'test',
TEST_COMPONENTS,
stdout=output
)
self.assertIn(
'Imported Test/Gettext PO with 3 translations',
output.getvalue()
)
output.truncate()
call_command(
'import_json',
'--main-component', 'test',
'--project', 'test',
'--ignore',
TEST_COMPONENTS,
stderr=output
)
self.assertIn(
'Component Test/Gettext PO already exists',
output.getvalue()
)
示例3: csv_iter
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def csv_iter():
rows = iter(table)
fo = IO()
csv_writer = csv.writer(fo)
csv_writer.writerow(converter.header2())
while True:
try:
for _ in range(1000):
row = next(rows)
#print row
csv_writer.writerow(row)
except StopIteration:
fo.seek(0)
yield fo.read().encode('utf-8')
del fo
break
fo.seek(0)
data = fo.read().encode('utf-8')
fo.seek(0)
fo.truncate()
yield data
if converter.errors:
yield 'The following errors were found at unspecified points in processing:\n'
for error in converter.errors:
yield str(error)+'\n'
示例4: GbpLogTester
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
class GbpLogTester(object):
"""
Helper class for tests that need to capture logging output
"""
def __init__(self):
"""Object initialization"""
self._log = None
self._loghandler = None
def _capture_log(self, capture=True):
""" Capture log"""
if capture:
assert self._log is None, "Log capture already started"
self._log = StringIO()
self._loghandler = gbp.log.GbpStreamHandler(self._log, False)
self._loghandler.addFilter(gbp.log.GbpFilter([gbp.log.WARNING,
gbp.log.ERROR]))
handlers = list(gbp.log.LOGGER.handlers)
for hdl in handlers:
gbp.log.LOGGER.removeHandler(hdl)
gbp.log.LOGGER.addHandler(self._loghandler)
else:
assert self._log is not None, "Log capture not started"
gbp.log.LOGGER.removeHandler(self._loghandler)
self._loghandler.close()
self._loghandler = None
self._log.close()
self._log = None
def _get_log(self):
"""Get the captured log output"""
self._log.seek(0)
return self._log.readlines()
def _check_log_empty(self):
"""Check that nothig was logged"""
output = self._get_log()
ok_(output == [], "Log is not empty: %s" % output)
def _check_log(self, linenum, regex):
"""Check that the specified line on log matches expectations"""
if self._log is None:
raise Exception("BUG in unittests: no log captured!")
log = self._get_log()
assert_less(linenum, len(log),
"Not enough log lines: %d" % len(log))
output = self._get_log()[linenum].strip()
ok_(re.match(regex, output),
"Log entry '%s' doesn't match '%s'" % (output, regex))
def _clear_log(self):
"""Clear the mock strerr"""
if self._log is not None:
self._log.seek(0)
self._log.truncate()
示例5: test_output_bold_green_on_bold_white
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_output_bold_green_on_bold_white():
"file-like filter output: bold green on white"
io = StringIO()
couleur.proxy(io).enable()
io.write("#{bold}#{green}#{on:white}Hello\n")
assert_equals('\033[1;32;47mHello\n', io.getvalue())
couleur.proxy(io).disable()
io.seek(0)
io.truncate()
io.write("#{black}should not be translated\n")
assert_equals('#{black}should not be translated\n', io.getvalue())
示例6: test_output_green_and_red_on_white_foreground
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_output_green_and_red_on_white_foreground():
"file-like filter output: green foreground and white on red background"
io = StringIO()
couleur.proxy(io).enable()
io.write("#{green}Hello #{white}#{on:red}Italy!\n")
assert_equals('\033[32mHello \033[37;41mItaly!\n', io.getvalue())
couleur.proxy(io).disable()
io.seek(0)
io.truncate()
io.write("#{black}should not be translated\n")
assert_equals('#{black}should not be translated\n', io.getvalue())
示例7: test_output_green_foreground
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_output_green_foreground():
"file-like filter output: green foreground"
io = StringIO()
couleur.proxy(io).enable()
io.write("#{green}Hello Green!\n")
assert_equals('\033[32mHello Green!\n', io.getvalue())
couleur.proxy(io).disable()
io.seek(0)
io.truncate()
io.write("#{black}should not be translated\n")
assert_equals('#{black}should not be translated\n', io.getvalue())
示例8: test_output_black_on_white_foreground
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_output_black_on_white_foreground():
"file-like filter output: black foreground on white background"
io = StringIO()
couleur.proxy(io).enable()
io.write("#{black}#{on:white}Hello Black!\n")
assert_equals('\033[30;47mHello Black!\n', io.getvalue())
couleur.proxy(io).disable()
io.seek(0)
io.truncate()
io.write("#{black}should not be translated\n")
assert_equals('#{black}should not be translated\n', io.getvalue())
示例9: test_logging
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_logging():
rep = Report(ValueError, 20, 'msg', 'fix')
str_io = StringIO()
logger = logging.getLogger('test.logger')
logger.setLevel(30) # defaultish level
logger.addHandler(logging.StreamHandler(str_io))
rep.log_raise(logger)
assert_equal(str_io.getvalue(), '')
rep.problem_level = 30
rep.log_raise(logger)
assert_equal(str_io.getvalue(), 'msg; fix\n')
str_io.truncate(0)
str_io.seek(0)
示例10: test_ignoring_colors
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_ignoring_colors():
"file-like filter output: ignoring output"
io = StringIO()
couleur.proxy(io).enable()
couleur.proxy(io).ignore()
io.write("#{bold}#{green}#{on:white}Hello\n")
assert_equals('Hello\n', io.getvalue())
couleur.proxy(io).disable()
io.seek(0)
io.truncate()
io.write("#{black}should not be translated\n")
assert_equals('#{black}should not be translated\n', io.getvalue())
示例11: generate_csv
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def generate_csv(results):
output_file = StringIO()
yield output_file.getvalue()
output_file.truncate(0)
output = None
for marker in results.all():
serialized = marker.serialize()
if not output:
output = csv.DictWriter(output_file, serialized.keys())
output.writeheader()
row = {k: v.encode('utf8')
if type(v) is six.text_type else v
for k, v in iteritems(serialized)}
output.writerow(row)
yield output_file.getvalue()
output_file.truncate(0)
示例12: test_output
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
def test_output():
status, warnings = StringIO(), StringIO()
app = TestApp(status=status, warning=warnings)
try:
status.truncate(0) # __init__ writes to status
status.seek(0)
app.info("Nothing here...")
assert status.getvalue() == "Nothing here...\n"
status.truncate(0)
status.seek(0)
app.info("Nothing here...", True)
assert status.getvalue() == "Nothing here..."
old_count = app._warncount
app.warn("Bad news!")
assert warnings.getvalue() == "WARNING: Bad news!\n"
assert app._warncount == old_count + 1
finally:
app.cleanup()
示例13: CSVWriter
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
class CSVWriter(object):
""" ref: http://docs.python.jp/2/library/csv.html
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwargs):
self.queue = StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwargs)
self.stream = f
self.encoding = encoding
def write(self, row):
# 一度 utf-8 としてキューに書いてから、それを読み出して指定のエンコーディングで書き直す
self.writer.writerow([s.encode("utf-8") for s in row])
data = self.queue.getvalue()
data = data.decode("utf-8")
self.stream.write(data)
# キューをクリア
self.queue.truncate(0)
def writerows(self, rows):
[self.write(row) for row in rows]
示例14: OutputStream
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
class OutputStream(_WritelnDecorator):
def __init__(self, on_stream, off_stream):
self.capture_stream = IO()
self.on_stream = on_stream
self.off_stream = off_stream
self.stream = on_stream
def on(self):
self.stream = self.on_stream
def off(self):
self.stream = self.off_stream
def capture(self):
self.capture_stream.truncate()
self.stream = self.capture_stream
def get_captured(self):
self.capture_stream.seek(0)
return self.capture_stream.read()
示例15: __init__
# 需要导入模块: from six import StringIO [as 别名]
# 或者: from six.StringIO import truncate [as 别名]
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=excel, encoding="utf-8", **kwargs):
self.queue = StringIO()
self.writer = writer(self.queue, dialect=dialect, **kwargs)
self.stream = f
self.encoding = encoding
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([unicode(s).encode(self.encoding) for s in row])
data = self.queue.getvalue()
data = data.decode(self.encoding)
data = self.encoder.encode(data)
self.stream.write(data)
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)