2017-09-26 233 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