python - 将打印重定向到字符串列表?

标签 python

我知道如何将打印重定向到文件。

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/

相关文章:

python - 如何在动态创建的 QMdiAreaSubWindow 中处理 matplotlib pick Artist 事件? (给出的示例 - 部分工作!)

python - 如何通过Python合并不同文件夹中同名文件的内容?

python - Enigma 副本未产生预期结果

python - Django 和 SSL 问题

c++ - 使用 boost.python 时 c++ 流有什么问题?

python - 为什么此代码不能为 Project Euler Question #56 提供正确的结果?

python - 在 Python 中替换 SVG 的内部内容

php - phpcurl 的 Soap Python 响应中的 NameError

python - 如何使用 Selenium 和 Chrome 在 Python 中单击下拉菜单

python - Beautiful Soup 无法识别 Python 3、IPython 6 控制台上的 UTF-8 编码