【问题标题】:Execute script in another thread and write output in real-time on gui (pyqt5)在另一个线程中执行脚本并在 gui (pyqt5) 上实时写入输出
【发布时间】:2023-03-15 04:17:01
【问题描述】:

我有一个文件 script.py,它执行一些操作并使用一些“打印”语句与用户进行通信。

使用 PyQt5,我创建了一个单独的文件 gui.py,在其中创建了一个带有一些小部件的 GUI,包括“运行”按钮和 QTextEdit。当我按下该按钮时,我希望执行“script.py”,并将其输出的每一行重定向到我的 QTextEdit 实时

我设法执行了脚本并查看了它的输出......但是,虽然它在控制台上完美运行,但 QTextEdit 仅在 script.py 结束执行时更新。

这是我的代码:

class gui(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        def run():
            try:  
                p = subprocess.Popen("python script.py", stdout=subprocess.PIPE)
                for line in iter(p.stdout.readline, b''):
                    if line != "b''":
                        line = str(line)[2:-5] # eliminates b' and \r\n'
                        print(line) # This works real-time
                        output.append(line) # this does not
                p.stdout.close()
                p.wait()

            except Exception as e:
                print(str(e))


        button_run = QPushButton("&Run", self)
        button_run.clicked.connect(run)

        output = QTextEdit()
        output.setPlaceholderText("Text will appear here")
        output.setReadOnly(True)

        """ 
            rest of initUI....
        """


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = gui()
    sys.exit(app.exec_())

我尝试使用 QProcess,但我无法理解它。

【问题讨论】:

标签: python multithreading qt pyqt


【解决方案1】:

您应该使用工作线程并通过 Qt 插槽和信号与您的工作线程通信您的主应用程序。请参阅this example,它是用 C++ 编码的,但对于理解这个想法很有用。

【讨论】:

  • 那是 c++,不是 QML
【解决方案2】:

使用 Qt 的 QProcess 而不是在线程中使用 subprocess 会容易得多 - 它具有 readyRead 信号和 readLine 方法之类的东西。

【讨论】:

  • QProcess 似乎非常麻烦且复杂(至少对我而言),我什至无法用它执行脚本。对我来说,我在网络上找不到 PyQt 的 QProcess 的单个工作示例,这似乎很荒谬
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多