简体   繁体   English

阻止sys.stdout写入文本文件

[英]Stop sys.stdout from writing to a text file

I am using python sys to save my stdout to a text file. 我正在使用python sys将我的标准输出保存到文本文件。

sys.stdout=open('OLSYield.txt','w')

However I only want a portion of the stdout to go to the text. 但是,我只希望标准输出的一部分转到文本。 How do I stop writing to txt file and redirect back to the terminal or console? 如何停止写入txt文件并重定向回终端或控制台?

So it should look something like 所以它看起来应该像

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

sys.stdout=close('OLSYield.txt','w')
print "helloWorld appears in console"

Im not sure what command I should use to close stdout=open 我不确定我应该使用什么命令来关闭stdout=open

to change the output back to the console you need to keep a reference to the original stdout: 要将输出更改回控制台,您需要保留对原始标准输出的引用:

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"

You can stop writing to your file and revert to the console like this: 您可以停止写入文件,并返回到控制台,如下所示:

sys.stdout = open("file.txt", "w")
print "in file"

sys.stdout.close()
sys.stdout = open("/dev/stdout", "w")

print "in console"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM