Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get output when trying to run python console using QProcess

Tags:

python

qt

I wanted to use the python interpreter in a QT C++ program, I tried to open a python console using QProcess:

QProcess shell; // this is declared in the class .h file

shell.start("python");
connect(&shell,SIGNAL(readyRead()),SLOT(shellOutput()));
shell.write("print 'hello!'\n");

But I didn't catch any outputs, where did I get it wrong, or is there a better way doing this?

like image 812
TwilightSun Avatar asked Aug 06 '12 14:08

TwilightSun


1 Answers

I wrote a very minimalistic program that does what you expected. Below is the code:

mainwindow.hpp

#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP

#include <QtGui>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

private slots:
    void onReadyRead();
    void onPushButtonClicked();

private:
    QPushButton* pushButton;
    QProcess *shell;
};

#endif // MAINWINDOW_HPP

main.cpp

#include <QtCore>
#include <QtGui>
#include <QDebug>
#include "mainwindow.hpp"

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    pushButton = new QPushButton("Execute");
    connect(pushButton, SIGNAL(clicked()),
            this, SLOT(onPushButtonClicked()));
    setCentralWidget(pushButton);
}

void MainWindow::onPushButtonClicked()
{
    shell = new QProcess(this);
    connect(shell, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
    shell->start("python");
    if (!shell->waitForStarted())
        exit(1);

    shell->write("print 'hello!'\n");
    shell->closeWriteChannel();
    if (!shell->waitForFinished())
        exit(1);

    qDebug() << "Shell error code:" << shell->error();
}

void MainWindow::onReadyRead()
{
    QString text = shell->readAll();
    qDebug() << text;
}

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);
    MainWindow win;
    win.show();
    return app.exec();
}

Implementation notes:

  • I used the synchronous API by adding QProces::waitFor...().
  • I closed the communication channel with QProcess::closeWriteChannel().
  • I added some debug output especially the error code of QProcess is quite helpful.

These things together show a motivating hello! when the pushbutton is pressed.

like image 151
Mehrwolf Avatar answered Sep 19 '22 15:09

Mehrwolf