从 GUI 运行脚本 [英] Run script from GUI

查看:54
本文介绍了从 GUI 运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为数据分析编写了一个脚本 (test.py).现在我正在 PyQt 中做一个 GUI.我想要的是当我按下运行"按钮时,脚本 test.py 将运行并显示结果(绘图).

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).

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

I tried subprocess.call('test1.py') and subprocess.Popen('test1.py') but it only opens the script and don't run it. I also tried os.system, doesn't work either.

下面的脚本不完整(有更多相关的按钮和功能,但不相关且与所描述的问题无关).

The script below is not complete (there are more buttons and functions associated but is not relevant and aren't connect to the problem described).

我在 Spyder 和 PyQt5 上使用 Python 3.6.

I'm using Python 3.6 on Spyder and PyQt5.

有没有其他函数或模块可以做我想做的事?

Is there any other function or module that can do what I want?

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

推荐答案

你需要做的是创建一个文本标签,然后通过管道 stdout/stderr 到 subprocess.PIPE:

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
)

然后调用subprocess.Popen.communicate():

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

这篇关于从 GUI 运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆