阻止sys.stdout写入文本文件

gal*_*ero 0 python sys spyder

我正在使用python sys将我的stdout保存到文本文件中.

sys.stdout=open('OLSYield.txt','w')
Run Code Online (Sandbox Code Playgroud)

但是我只想要一部分stdout转到文本.如何停止写入txt文件并重定向回终端或控制台?

所以看起来应该是这样的

sys.stdout=open('OLSYield.txt','w')
print "helloWorld appears in text file"

sys.stdout=close('OLSYield.txt','w')
print "helloWorld appears in console"
Run Code Online (Sandbox Code Playgroud)

我不确定我应该用什么命令关闭 stdout=open

Jam*_*ent 5

要将输出更改回控制台,您需要保留对原始标准输出的引用:

orig_stdout = sys.stdout
sys.stdout=open('OLSYield.txt','w')
print "helloWorld appears in text file"

sys.stdout.close()
sys.stdout=orig_stdout 
print "helloWorld appears in console"
Run Code Online (Sandbox Code Playgroud)