1

I'm trying to create a Python GUI using PyQt5 that displays real-time output of another Python code that is executed by a button. I've tried using subprocess and Popen, but the my output is only appearing after the program execution ends. Here's the code I've tried:

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Set the window title
        self.setWindowTitle("Example")

        # Set the minimum size of the main window
        self.setMinimumSize(500, 400)

        self.text_edit = QPlainTextEdit(self)

        buttons_layout = QHBoxLayout()
        button = QPushButton("Speak")
        button.setStyleSheet(
            "QPushButton {"
            "    border-radius: 10px;"
            "    padding: 10px 10px;"
            "    background-color: #add8e6;"
            "}"
            "QPushButton:hover {"
            "    background-color: #a4dded;"
            "}"
        )
        button.clicked.connect(self.run_script_in_thread)        
        

        buttons_layout.addWidget(button)
        def run_script_in_thread(self):
            thread = threading.Thread(target=self.run_script)
            thread.start()

        def run_script(self):
            process = subprocess.Popen([sys.executable, 'main.py'], stdout=subprocess.PIPE)
            output = process.communicate()[0].decode('utf-8')
            self.text_edit.setPlainText(output)
  

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Is there a way to display the output in real-time, as the button clicked? Thank you for any help you can provide!

  • Do you have access to 'the other python code'? In other words, can you modify it? If not, what kind of output does it have? Is it prints or does it use logging? – mahkitah Apr 22 '23 at 12:33
  • If you can't get around using subprocess, the answer to your question is a combination of these two questions: https://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess https://stackoverflow.com/questions/54643280/how-can-i-use-a-qtextbrowser-instead-of-the-console-in-python – mahkitah Apr 22 '23 at 13:09

0 Answers0