Skip to content Skip to sidebar Skip to footer

Run Script From GUI

I wrote a script (test.py) for Data Analysis. Now I'm doing a GUI in PyQt. What I want is when I press a button 'Run', the script test.py will run and show the results (plots). I t

Solution 1:

What you need to do is create a text label, then pipe stdout / stderr to subprocess.PIPE:

p = subprocess.Popen(
    "python test1.py",
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)

Then call subprocess.Popen.communicate():

stdout, stderr = p.communicate()
# Display stdout (and possibly stderr) in a text label

Solution 2:

You can import test1.py and call functions from within it whenever you wish

Use this How can I make one python file run another?


Solution 3:

QProcess class is used to start external programs and to communicate with them.

Try it:

import sys
import subprocess

from PyQt5 import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton
from PyQt5.QtCore import QProcess

class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("TEMP FILE")
        self.home()

    def home (self):
        btn_run = QPushButton("Run", self)
        #btn_run.clicked.connect(self.execute)                                   # ---
        filepath = "python test1.py"                                             # +++
        btn_run.clicked.connect(lambda checked, arg=filepath: self.execute(arg)) # +++

        self.show()

    def execute(self, filepath):                                         # +++
        #subprocess.Popen('test1.py', shell=True)
        #subprocess.call(["python", "test1.py"])

        # It works
        #subprocess.run("python test1.py")

        QProcess.startDetached(filepath)                                 # +++



if not QApplication.instance():
    app = QApplication(sys.argv)
else:
    app = QApplication.instance()

GUI = Window()
app.exec_()

enter image description here


Post a Comment for "Run Script From GUI"