2015-05-21 140 views

回答

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

存儲在一個變量

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