在python中,如何在将打印重定向到文件后打印到屏幕?
我有一个使用print()在文件中写入的代码:在python中,如何在将打印重定向到文件后打印到屏幕?,python,Python,我有一个使用print()在文件中写入的代码: with open('test.xml', "w+") as outfile: sys.stdout = outfile 现在,我想在这段代码之后写入控制台,如何才能做到这一点?将标准输出存储在变量中 stdout = sys.stdout with open('test.xml', 'w+') as outfile: sys.stdout = outfile print("<text>Hello World&
with open('test.xml', "w+") as outfile:
sys.stdout = outfile
现在,我想在这段代码之后写入控制台,如何才能做到这一点?将标准输出存储在变量中
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
stdout=sys.stdout
以open('test.xml','w+')作为输出文件:
sys.stdout=outfile
打印(“Hello World”)#打印到输出文件而不是标准输出
sys.stdout=stdout#现在恢复正常
虽然这确实有效,但您应该直接写入文件
with open('test.xml', 'w+') as outfile
outfile.write("<text>Hello World</text">)
以open('test.xml','w+')作为输出文件的
write(“Hello World将标准输出存储在变量中
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
stdout=sys.stdout
以open('test.xml','w+')作为输出文件:
sys.stdout=outfile
打印(“Hello World”)#打印到输出文件而不是标准输出
sys.stdout=stdout#现在恢复正常
虽然这确实有效,但您应该直接写入文件
with open('test.xml', 'w+') as outfile
outfile.write("<text>Hello World</text">)
以open('test.xml','w+')作为输出文件的
outfile.write(“Hello World您可以从以下位置还原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
您可以从以下位置还原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