我想要某种方式来 print()
到字符串或内部缓冲区,而不是 Python 中的 stdout。
理想情况下,我可以打印到此内容,然后将字符串转储到控制台,就像它一开始就打印到标准输出一样。像这样的东西:
>>> print("output 1", a)
>>> print("output 2", a)
>>> print(a)
output 1
output 2
如果您想知道,我这样做是为了快速重构之前直接打印到控制台的代码。
最佳答案
您正在寻找的是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
关于Python 内部缓冲输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28591257/