我在Windows上有一個程序,調用一堆子進程,並在GUI中顯示結果。我使用PyQt作爲GUI,並使用subprocess
模塊來運行程序。當子進程在Python中運行時,如何從子進程PIPE獲取數據?
我有以下WorkerThread
,即產生一個子線程用於專門讀取過程標準輸出和打印結果中的每個shell命令(以後我會給你電匯它的GUI)。
這一切正常。 除了proc.stdout.read(1)
從不返回,直到子流程完成後。這是一個很大的問題,因爲其中一些子進程可能需要15-20分鐘才能運行,並且我需要在運行時顯示結果。
在子流程運行時,我需要做些什麼來使管道工作?
class WorkerThread(QtCore.QThread):
def run(self):
def sh(cmd, cwd = None):
proc = subprocess.Popen(cmd,
shell = True,
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
stdin = subprocess.PIPE,
cwd = cwd,
env = os.environ)
proc.stdin.close()
class ReadStdOutThread(QtCore.QThread):
def run(_self):
s = ''
while True:
if self.request_exit: return
b = proc.stdout.read(1)
if b == '\n':
print s
s = ''
continue
if b:
s += b
continue
if s: print s
return
thread = ReadStdOutThread()
thread.start()
retcode = proc.wait()
if retcode:
raise subprocess.CalledProcessError(retcode, cmd)
return 0
FWIW:我重寫使用QProcess
整個事情,我看到完全相同的問題。 stdout
收到沒有數據,直到基礎過程已返回。然後,我立即得到一切。
我不知道輸出會有多長時間。 –
@ChrisB。我剛剛添加了一個可能是你正在尋找的例子的鏈接。 –