我有一个代码使用print()写入文件:
with open('test.xml', "w+") as outfile:
sys.stdout = outfile
现在我希望在此代码后写入控制台,我该怎么做?
答案 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">)