繁体   English   中英

阻止sys.stdout写入文本文件

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

我正在使用python sys将我的标准输出保存到文本文件。

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

但是,我只希望标准输出的一部分转到文本。 如何停止写入txt文件并重定向回终端或控制台?

所以它看起来应该像

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

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

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

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

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"

您可以停止写入文件,并返回到控制台,如下所示:

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