[英]Output from subprocess is not available on unbuffered stdout pipe before the subprocess terminates?
[英]Output of subprocess both to PIPE and directly to stdout
我發現了一些看起來像我的問題但是沒有產生我可以使用的解決方案(最接近的是: 子程序輸出到stdout和PIPE )
問題:我想使用子進程啟動一個進程需要很長時間。 運行命令后,我需要解析stdout-output和stderr-output。
目前我這樣做如下:
p = subprocess.Popen( command_list, stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
out, error_msg = p.communicate()
print out + "\n\n" + error_msg
#next comes code in which I check out and error_msg
但是這種方法的缺點是用戶在運行時看不到進程的輸出。 僅在結尾處打印輸出。
有沒有辦法在命令運行時打印輸出(好像我給出了沒有stdout / stderr = subprocess.PIPE的命令)並且最后還是通過p.communicate輸出?
注意:我目前正在開發python 2.5(使用此python版本的舊軟件版本)。
在類似的情況下,這段代碼曾幫助過我:
process = subprocess.Popen(cmd, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
print line,
sys.stdout.flush() # please see comments regarding the necessity of this line
process.wait()
errcode = process.returncode
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.