2017-09-26 113 views
1

我在使用Qt的QProcess时遇到了一些问题。我已将下列函数与按钮的onClick事件关联起来。基本上,我想在单击此按钮时执行另一个文件,并在我的Qt程序中获取它的输出。该文件calculator执行,显示一些输出,然后等待来自用户的输入。在Qt中读取连续QProcess的标准输出

void runPushButtonClicked() { 
    QProcess myprocess; 
    myprocess.start("./calculator") 
    myprocess.waitForFinished(); 
    QString outputData= myprocess.readStandardOutput(); 
    qDebug() << outputData; 
} 

在一个场景中,当calculator是只输出了一些成果,并最终终止这样的文件,这个完美的作品。但是,如果计算器在输出一些结果后等待用户进一步输入,则我的outputData中什么也没有。实际上,waitForFinished()会超时,但即使删除waitForFinished()outputData仍然是空的。

我已经尝试了一些可用于此的解决方案,但一直无法处理这种情况。任何指导将不胜感激。

+0

_I已经尝试了一些解决方案_显示你已经尝试过。 – 2017-09-26 18:47:03

+0

通过连接信号和插槽:connect(process,SIGNAL(readyRead()),this,SLOT(readStdOut())); – Daud

回答

0

我会建议你设置一个信号处理程序,它在子进程产生输出时被调用。例如。您必须连接到readyReadStandardOutput

然后,您可以识别子流程何时需要输入并发送所需的输入。这将在readSubProcess()完成。

的main.cpp

#include <QtCore> 
#include "Foo.h" 

int main(int argc, char **argv) { 
    QCoreApplication app(argc, argv); 

    Foo foo; 

    qDebug() << "Starting main loop"; 
    app.exec(); 
} 

在下文中,子进程启动和输入检查。当calculator程序结束时,主程序也退出。

foo.h中

#include <QtCore> 

class Foo : public QObject { 
    Q_OBJECT 
    QProcess myprocess; 
    QString output; 

public: 
    Foo() : QObject() { 
     myprocess.start("./calculator"); 

     // probably nothing here yet 
     qDebug() << "Output right after start:" 
       << myprocess.readAllStandardOutput(); 

     // get informed when data is ready 
     connect(&myprocess, SIGNAL(readyReadStandardOutput()), 
       this, SLOT(readSubProcess())); 
    }; 

private slots: 
    // here we check what was received (called everytime new data is readable) 
    void readSubProcess(void) { 
     output.append(myprocess.readAllStandardOutput()); 
     qDebug() << "complete output: " << output; 

     // check if input is expected 
     if (output.endsWith("type\n")) { 
     qDebug() << "ready to receive input"; 

     // write something to subprocess, if the user has provided input, 
     // you need to (read it and) forward it here. 
     myprocess.write("hallo back!\n"); 
     // reset outputbuffer 
     output = ""; 
     } 

     // subprocess indicates it finished 
     if (output.endsWith("Bye!\n")) { 
     // wait for subprocess and exit 
     myprocess.waitForFinished(); 
     QCoreApplication::exit(); 
     } 
    }; 
}; 

子进程计算器一个简单的脚本使用。你可以看到哪里输出产生和输入是预期的。

#/bin/bash 

echo "Sub: Im calculator!" 

# some processing here with occasionally feedback 
sleep 3 
echo "Sub: hallo" 

sleep 1 

echo "Sub: type" 
# here the script blocks until some input with '\n' at the end comes via stdin 
read BAR 

# just echo what we got from input 
echo "Sub: you typed: ${BAR}" 

sleep 1 
echo "Sub: Bye!" 

如果您不需要做任何事情在你的主进程(如显示GUI,管理其他线程/进程....),最简单的是只在sleep在后一个循环子流程创建,然后像readSubprocess

+0

感谢您的时间。答案不适用于我,因为“qDebug()<<”完成输出:“<<输出;”在我的情况下不会发生。我不知道。 – Daud

+0

当我使用execute而不是启动它的工作,但在终端中运行而不是在控制台输出 – Daud