How do I read from QProcess?

非 Y 不嫁゛ 提交于 2019-12-05 17:59:29

Use QIODevice::waitForReadyRead() in a loop, and only after that returns, then call readAllStandardOutput(). As it says in the docs, QProcess::readAllStandardOutput() will read all available data, but will not wait. And before you start reading, you need to wait that process is started with QProcess::waitForStarted().

Quick untested partial code, replace line ba = ps.readAllStandardOutput(); with this:

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

That should exit the loop when there is error or child process terminates, but keep reading until then, with no timeout.

Note: in a "regular" Qt program, you would have event loop running, and then you would not call waitForReadyRead() or other similar convenience functions. They would block the event loop and stop everything else too. In such a program, you would preferably use signals and slots, or alternatively start mucking about with threads (but that's generally not preferred, it just adds unnecessary complexity).

Ville Lukka

QProcess documentation says, that QProcess object emits signals when there is data available to read: readyRead() and readyReadStandardOutput() and readyReadStandardError().

Easiest way is to connect those signals to your slots, and make your reading with eg. readAllStandardOutput() there.

Of course hydes loop works also.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!