0

I have a file script.py which executes some operations and uses some "print" statements to communicate with the user.

Using PyQt5, I created a separate file gui.py where I created a GUI with some widgets, including a "run" button and a QTextEdit. When I press that button, I want "script.py" to be executed and every line of its output to be redirected on my QTextEdit in real time

I managed to execute the script and view it's output... but,while it works perfectly on console, the QTextEdit is updated only when script.py has concluded its execution.

This is my code :

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_())

I tried to use QProcess, but I can't wrap my head around it.

ettanany
  • 19,038
  • 9
  • 47
  • 63

2 Answers2

0

You should use a worker thread and communicate your main app with your worker by Qt slots and signals. See this example it's coded in c++, but is usefull to get the idea.

0

This will be much easier with Qt's QProcess instead of using subprocess in a thread - it has things like a readyRead signal and a readLine method.

The Compiler
  • 11,126
  • 4
  • 40
  • 54
  • QProcess seems to be **extremely** troublesome and complicate (to me, at least), I can't even execute a script with it. It seems ridicolous to me that I can't find a SINGLE working exemple of QProcess for PyQt in the web – Kate Morrow Nov 24 '16 at 21:03