2015-05-21 188 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">)