0
我有一个代码中使用的print()在文件中写:如何打印到屏幕后重定向打印到文件,在Python中?
with open('test.xml', "w+") as outfile:
sys.stdout = outfile
现在我要编写此代码后安慰,我该怎么办呢?
我有一个代码中使用的print()在文件中写:如何打印到屏幕后重定向打印到文件,在Python中?
with open('test.xml', "w+") as outfile:
sys.stdout = outfile
现在我要编写此代码后安慰,我该怎么办呢?
您可以从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
存储在一个变量
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">)