我知道如何将打印重定向到文件。
import sys
orig_stdout = sys.stdout
f = file('out.txt', 'w')
sys.stdout = f
for i in range(2):
print ('i = ', i)
sys.stdout = orig_stdout
f.close()
我需要做同样的事情但没有文件:将打印输出保存在字符串列表中。在 Py3k 中如何实现?
编辑:我可以在中间部分使用第 3 方打印,而不是我自己的打印,因此代码对于通常的“print()”必须是通用的。
最佳答案
import sys
class ListStream:
def __init__(self):
self.data = []
def write(self, s):
self.data.append(s)
sys.stdout = x = ListStream()
for i in range(2):
print ('i = ', i)
sys.stdout = sys.__stdout__
print(x.data)
产量
['i = ', ' ', '0', '\n', 'i = ', ' ', '1', '\n']
提示:您不需要保存原始的sys.stdout
orig_stdout = sys.stdout
因为 sys.stdout
可以用
sys.stdout = sys.__stdout__
您还可以通过使 ListStream
成为上下文管理器来添加一些语法糖:
import sys
class ListStream:
def __init__(self):
self.data = []
def write(self, s):
self.data.append(s)
def __enter__(self):
sys.stdout = self
return self
def __exit__(self, ext_type, exc_value, traceback):
sys.stdout = sys.__stdout__
通过添加 __enter__
和 __exit__
方法,您现在可以在 with-statement
中使用 ListStream
当 Python 退出 with-suite
时,将自动重置sys.stdout
:
with ListStream() as x:
for i in range(2):
print ('i = ', i)
print(x.data)
关于python - 将打印重定向到字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21341096/