gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:09:36 25 4
gpt4 key购买 nike

我想在 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");

但是我没有捕捉到任何输出,我在哪里弄错了,或者有更好的方法吗?

最佳答案

我写了一个非常简约的程序,可以达到您的预期。下面是代码:

主窗口.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();
}

实现说明:

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

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

关于python - 尝试使用 QProcess 运行 python 控制台时无法获得输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11830284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com