[英]Read stdoutput of continuous QProcess in Qt
我對使用Qt的QProcess有一些問題。 我已將以下功能與按鈕的onClick事件連接。 基本上,我想在單擊此按鈕時執行另一個文件,並在我的Qt程序中獲取其輸出。 該文件calculator
執行,顯示一些輸出,然后等待用戶的輸入。
void runPushButtonClicked() {
QProcess myprocess;
myprocess.start("./calculator")
myprocess.waitForFinished();
QString outputData= myprocess.readStandardOutput();
qDebug() << outputData;
}
在一種情況下,當calculator
是僅輸出一些結果並最終終止的文件時,這是完美的。 但是,如果計算器在輸出一些結果后等待用戶的進一步輸入,則在outputData
什么也沒有。 實際上, waitForFinished()
會超時,但是即使刪除了waitForFinished()
, outputData
仍然為空。
我已經嘗試過SO上可用的一些解決方案,但是無法處理這種情況。 任何指導將不勝感激。
我建議您設置一個信號處理程序,該處理程序在子進程產生輸出時被調用。 例如,您必須連接到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
程序完成后,主電源也會退出。
oo
#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
類的readSubprocess
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.