Cannot get output when trying to start python console using QProcess

I wanted to use the python interpreter in a QT C ++ program, I tried to open the 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 way out where I was wrong, or is there a better way to do this?

+5
source share
2 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 using QProcess::closeWriteChannel().
  • I added some debugging output, especially the error code is QProcessvery useful.

These things together show motivation hello!at the touch of a button.

+4

, ...

python -i: python -i

.

, -i

+1

All Articles