簡體   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