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">)