我希望某种方式print()
到字符串或内部缓冲区而不是Python中的stdout。
理想情况下,我可以打印到此处,然后将字符串转储到控制台,就好像它已经打印到stdout开始一样。类似的东西:
>>> print("output 1", a)
>>> print("output 2", a)
>>> print(a)
output 1
output 2
如果您想知道,我这样做是为了快速重构之前直接打印到控制台的代码。
答案 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)