簡體   English   中英

我如何閱讀QProcess?

[英]How do I read from QProcess?

我有這個簡單的C ++程序:

int main(int argc, char *argv[])
{

    QCoreApplication a(argc, argv);

    QProcess ps;
    QByteArray ba;

    ps.start("ls J:");
    ba = ps.readAllStandardOutput();
    char *someData = ba.data();

    cout << "Testing QProcess ..." << endl;
    cout << someData << endl;
    cout << "done!" << endl;

    return a.exec();
}

輸出是:

Testing QProcess ...


done!

如果我從Windows cmd運行“ls J:”它可以工作。 我錯過了什么?

在循環中使用QIODevice :: waitForReadyRead() ,只有在返回之后,才調用readAllStandardOutput() 正如文檔中所述, QProcess::readAllStandardOutput()將讀取所有可用數據,但不會等待。 在開始閱讀之前,您需要等待QProcess::waitForStarted()啟動該過程。

快速未經測試的部分代碼,替換行ba = ps.readAllStandardOutput(); 有了這個:

if (ps.waitForStarted(-1)) {
    while(ps.waitForReadyRead(-1)) {
        ba += ps.readAllStandardOutput();
    }
}
// else report error or whatever

當出現錯誤或子進程終止時,應該退出循環,但在此之前保持讀取,沒有超時。

注意:在“常規”Qt程序中,您將運行事件循環,然后您不會調用waitForReadyRead()或其他類似的便捷函數。 他們會阻止事件循環並停止其他一切。 在這樣的程序中,你最好使用信號和插槽,或者用線程開始亂碼(但這通常不是優選的,它只會增加不必要的復雜性)。

QProcess文檔說,當有可讀數據時, QProcess對象會發出信號: readyRead()readyReadStandardOutput()以及readyReadStandardError()

最簡單的方法是將這些信號連接到您的插槽,並使用例如。 readAllStandardOutput()那里。

當然hydes循環也有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM