如何在python中重定向打印到文件后打印到屏幕?

时间:2015-05-21 07:16:46

标签: python

我有一个代码使用print()写入文件:

with open('test.xml', "w+") as outfile:
    sys.stdout = outfile

现在我希望在此代码后写入控制台,我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以从sys.__stdout__恢复sys.stdout

with open('test.xml', "w+") as outfile:
    sys.stdout = outfile

sys.stdout = sys.__stdout__

或者您可以存储原始版本:

orig_stdout = sys.stdout
with open('test.xml', "w+") as outfile:
    sys.stdout = outfile

sys.stdout = orig_stdout

您可以在此处使用上下文管理器:

from contextlib import contextmanager

@contextmanager
def redirect_stdout(filename):
    orig_stdout = sys.stdout
    try:
        with open(filename, "w+") as outfile:
            sys.stdout = outfile
            yield
    finally:
        sys.stdout = orig_stdout

然后在您的代码中使用它:

with redirect_stdout('test.xml'):
    # stdout is redirected in this block

# stdout is restored afterwards

答案 1 :(得分:1)

将stdout存储在变量

stdout = sys.stdout
with open('test.xml', 'w+') as outfile:
    sys.stdout = outfile
    print("<text>Hello World</text>") # print to outfile instead of stdout

sys.stdout = stdout # now its back to normal

虽然这很有效,但您应该直接写入文件

with open('test.xml', 'w+') as outfile
    outfile.write("<text>Hello World</text">)