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!