从GUI运行脚本

2024-06-02 05:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了个剧本(测试.py)用于数据分析。现在我在PyQt中做一个GUI。 我想要的是当我按下“运行”按钮时,脚本测试.py将运行并显示结果(图)。在

我尝试了subprocess.call('test1.py')subprocess.Popen('test1.py'),但它只打开脚本而不运行它。 我也试过os.system,也没用。在

下面的脚本不完整(有更多关联的按钮和函数,但这些按钮和函数不相关,并且没有连接到所描述的问题)。在

我在Spyder和PyQt5上使用python3.6。在

有没有其他功能或模块可以做我想要的?在

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)

        self.show()

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

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

GUI = Window()
app.exec_()

Tags: 函数pyself脚本appdefguicall
3条回答

您需要做的是创建一个文本标签,然后将stdout/stderr管道发送到^{}

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

然后调用^{}

^{pr2}$

您可以导入test1.py并随时从中调用函数

使用这个How can I make one python file run another?

QProcess类用于启动外部程序并与它们通信。在

试试看:

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

相关问题 更多 >