簡體   English   中英

在for循環中使用subprocess.Popen將stdout輸出更新到UI時,python UI應用程序掛起

[英]python UI app hangs while updating stdout output to UI using subprocess.Popen in a for loop

我正在運行subprocess.Popen()來調用命令行工具,該命令會將其輸出打印到控制台,如下所示:

[app] : Initializing...
[app] : Starting process
[app] : .............
[app] : .............
[app] : Extracting information
[app] : Downloading information
[app] : 100% completed              
[app] : Saving file to disk
[app] : Completed

現在,我試圖捕獲輸出,以便可以將該輸出實時顯示給我的python UI應用程序。 我正在捕獲這樣的輸出:

cmd = "..."
p = subprocess.Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
for line in p.stdout:
    self.status.showmsg(str(line.rstrip()))
    p.stdout.flush()

問題:輸出正確顯示在我的UI上,直到到達該輸出行,在該行中顯示已完成進程的百分比(在示例中為100%)。 這是UI掛起的地方,並且不會顯示%的逐漸增加或之后的任何輸出。 盡管該程序在后台正確運行(執行其操作),但當它100%完成時,UI會解凍。

我在這里做錯了什么? 在我看來(%)輸出也是另一個循環,並且在那里失敗,但是我不知道為什么或如何在python中處理這個問題。

感謝您的寶貴建議!

在單獨的線程中運行工作進程,然后使用自定義信號將數據發送回gui。 這是一個非常基本的演示腳本:

import sys
from PyQt4 import QtCore, QtGui

class Thread(QtCore.QThread):
    dataReceived = QtCore.pyqtSignal(str)

    def run(self):
        # subprocess stuff goes here
        for step in range(6):
            self.sleep(1)
            self.dataReceived.emit('data received: %d' % step)

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtGui.QPushButton('Start')
        self.button.clicked.connect(self.handleButton)
        self.setCentralWidget(self.button)
        self.thread = Thread(self)
        self.thread.dataReceived.connect(self.statusBar().showMessage)

    def handleButton(self):
        if not self.thread.isRunning():
            self.statusBar().showMessage('starting...')
            self.thread.start()

    def closeEvent(self, event):
        self.thread.wait()

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(200, 60)
    window.show()
    sys.exit(app.exec_())

暫無
暫無

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

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