簡體   English   中英

在python中的子過程調用期間使用stdout = subprocess.PIPE時如何獲得正常的打印語句執行

[英]how to get the normal print statement execution when using stdout=subprocess.PIPE during subprocess call in python

我通過以下命令在python中啟動subprocess

result = subprocess.Popen([sys.executable, "/subscript.py"] + parameter,stdout=subprocess.PIPE )
result.wait()
out, err = result.communicate()
for line in out.splitlines():
    print line

我用這種方法面臨的問題是subscript.py中的所有print語句都被緩沖到最后,並在執行結束時打印在terminal上。 因此,如果我的subscript.py執行大約需要15分鍾,那么在15分鍾內, terminal不會顯示任何內容,而一旦subscript.py執行結束,則所有打印語句將一起打印。 我知道這是因為使用了stdout=subprocess.PIPE ,如果我刪除它,那么我將得到想要的東西,但是我無法刪除它,因為我正在使用它從subscript.py獲取變量的值(我我先在subscript.py打印該變量,然后在父腳本中進行打印,以獲取具有變量值的打印)。

因此,我想要的是應該在subscript.py中遇到時打印所有打印語句,直到執行結束subscript.py進行任何緩沖。 有沒有辦法做到這一點?

更新:我嘗試遵循JF Sebastian的方法,但仍然得到相同的輸出。 來自子流程的打印內容被緩沖,一旦子流程結束,就將它們打印到終端。 我擁有的更新代碼是:

result = subprocess.Popen([sys.executable, "/subscript.py"] + parameter,stdout=subprocess.PIPE,bufsize=1)

with result.stdout:
        for line in iter(result.stdout.readline, b''):
            print line,
result.wait()

您鏈接的答案僅在標准輸出緩沖區在子對象中刷新后才打印任何內容, 因為答案本身已明確指出。

使用-u參數 ,在Python子進程中取消緩沖stdout:

#!/usr/bin/env python2
import sys
from subprocess import Popen, PIPE

result = Popen([sys.executable, '-u', '/path/to/subscript.py'] + parameters, 
               stdout=PIPE, bufsize=1)
with result.stdout:
    for line in iter(result.stdout.readline, b''):
        print line,
result.wait()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM