Qt Calling an External Python Script

I am trying to write a GUI shell for one of the command line tools written in Python.
I was asked to use Qt.

The following is the .cpp project file:

#include "v_1.h" #include "ui_v_1.h" #include<QtCore/QFile> #include<QtCore/QTextStream> #include <QProcess> #include <QPushButton> v_1::v_1(QWidget *parent) : QMainWindow(parent),ui(new Ui::v_1) { ui->setupUi(this); } v_1::~v_1() { delete ui; } void v_1::on_pushButton_clicked() { QProcess p; p.start("python script -arg1 arg1"); p.waitForFinished(-1); QString p_stdout = p.readAllStandardOutput(); ui->lineEdit->setText(p_stdout); } 

Below is my project header file:

 #ifndef V_1_H #define V_1_H #include <QMainWindow> namespace Ui { class v_1; } class v_1 : public QMainWindow { Q_OBJECT public: explicit v_1(QWidget *parent = 0); ~v_1(); private slots: void on_pushButton_clicked(); private: Ui::v_1 *ui; }; #endif // V_1_H 

A UI file is just a LineEdit button and widget.

I highlighted the button when it clicks. The on_pushButton_clicked() method works fine when I call some utilities, such as ls or ps , and it outputs the output of these commands to the LineEdit widget, but when I try to call a Python script, it does not show me anything in the LineEdit widgets.

Any help would be greatly appreciated.

+4
source share
3 answers

Have you tried the following:

  • Make sure python is in your system path.
  • Transmission parameters specified in the documentation as QStringList
  • Change readAllStandardOutput to readAll during testing

 void v_1::on_pushButton_clicked() { QProcess p; QStringList params; params << "script.py -arg1 arg1"; p.start("python", params); p.waitForFinished(-1); QString p_stdout = p.readAll(); ui->lineEdit->setText(p_stdout); } 
+2
source

The code below works for me:

 void MainWindow::on_pushButton_clicked() { QString path = QCoreApplication::applicationDirPath(); QString command("python"); QStringList params = QStringList() << "script.py"; QProcess *process = new QProcess(); process->startDetached(command, params, path, &processID); process->waitForFinished(); process->close(); } 

path : you can set your own path
command : in which program do you want to run (in this case python)
parameters : the script you want to execute
& processID is intended to kill the process if the main window is closed

0
source

Hunor's answer also worked for me. But I did not use the process identifier. I did:

 void MainWindow::on_pushButton_clicked() { QString path = '/Somepath/mypath'; QString command("python"); QStringList params = QStringList() << "script.py"; QProcess *process = new QProcess(); process->startDetached(command, params, path); process->waitForFinished(); process->close(); } 
0
source

All Articles