[英]how to print subprocess' stdout directly to file
如何強制subprocess.Popen / os.Popen將大型輸出直接寫入文件,而不在緩沖區中保留任何內容? 我嘗試了這個:
os.popen(cmd, bufsize=0)
它沒有幫助。 讀取所有輸出(再次是大輸出)並將其保存到文件/列表的任何解決方案都將有所幫助。
這是將stdout
重定向到文件的方法:
import sys
sys.stdout = open('your_file', 'w')
然后,將在shell中輸出的所有內容都轉儲到該文件中。
您可以使用stdout
參數將輸出從子進程重定向到文件:
import shlex
from subprocess import check_call
with open('outputfilename', 'wb', 0) as outputfile:
check_call(shlex.split(cmd), stdout=outputfile)
您知道我應該在命令中添加哪些內容以防止子進程向外殼打印警告/錯誤嗎?
只需將stderr=subprocess.STDOUT
設置為合並stdout / stderr。 或將stderr
重定向到os.devnull
以放棄輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.