Python内部缓冲输出

时间:2015-02-18 18:34:51

标签: python python-3.x

我希望某种方式print()到字符串或内部缓冲区而不是Python中的stdout。

理想情况下,我可以打印到此处,然后将字符串转储到控制台,就好像它已经打印到stdout开始一样。类似的东西:

>>> print("output 1", a)
>>> print("output 2", a)
>>> print(a)
output 1
output 2

如果您想知道,我这样做是为了快速重构之前直接打印到控制台的代码。

3 个答案:

答案 0 :(得分:1)

您正在寻找的是StringIO模块。

你只需这样使用它:

import StringIO

a= StringIO.StringIO()
a.write('output 1\n')
print >>a, 'output 2'

# Retrieve file contents -- this will be
# 'output 1\noutput 2\n'
contents = a.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
a.close()

# will output 'output 1\noutput 2\n'
print contents
编辑:在发帖之前,我没有看到乔什的回答。他的语法是python 3我的是旧的python 2.x

答案 1 :(得分:0)

StringIO就像一个虚拟文件,可以用于此目的,但你必须小心得到你描述的行为:

>>> import io
>>> a = io.StringIO('')
>>> print("output 1", file=a)
>>> print("output 2", file=a)
>>> print(a.getvalue())  # notice the extra new line at the end...
output 1
output 2

>>> print(a.getvalue(), end='')  # use end='' to suppress extra new line
output 1
output 2
>>> print(a)  # print(a) will not yield the same results
<_io.StringIO object at 0x7fe3a23568b8>
>>> print("output 3", a)  # make sure to use "file=", or it will print str(a)!
output 3 <_io.StringIO object at 0x7fe3a23568b8>
>>> 

答案 2 :(得分:0)

一般情况下,print()方法采用一个很少使用的参数file,它只需要像文件一样&#39; (默认为stdout)。来自doc:

  

file参数必须是具有write(string)方法的对象;如果它不存在或None,将使用sys.stdout。输出缓冲由文件确定。例如,使用file.flush()确保在屏幕上立即显示。

如果您想维护print语法,可以提供自己的缓冲实现或使用StringIO作为文件。