尝试使用QProcess运行python控制台时无法获得输出

Twi*_*Sun 5 python qt

我想在QT C++程序中使用python解释器,我试图使用QProcess打开一个python控制台:

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

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

但我没有抓到任何输出,我在哪里弄错了,还是有更好的方法呢?

Meh*_*olf 4

我编写了一个非常简约的程序,可以满足您的期望。下面是代码:

主窗口.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
Run Code Online (Sandbox Code Playgroud)

主程序

#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();
}
Run Code Online (Sandbox Code Playgroud)

实施注意事项:

  • 我通过添加使用同步 APIQProces::waitFor...().
  • 我关闭了与QProcess::closeWriteChannel()
  • 我添加了一些调试输出,尤其是错误代码QProcess非常有帮助。

hello!当按下按钮时,这些东西一起显示出一种激励。