問題描述
我正在使用 Qt 并對其進行 bash,需要執(zhí)行如下操作:
I'm using Qt and bash over it, need to execute something like:
bash: cat file | grep string
在 Qt 中:
QString cmd = "cat file | grep string";
QProcess *process = new QProcess;
process->start(cmd);
process->waitForBytesWritten();
process->waitForFinished();
qDebug() << process->readAll();
問題出在管道(|")中,進程沒有返回任何內(nèi)容.如果沒有(|"),比如
The problem is in pipe ("|"), and process returs nothing. If there is no ("|"), like
"cat file"
一切正常.我試過了.喜歡
everything is ok. I tried smth. like
"cat file \| grep string",
"cat file | grep string"
但結果是一樣的.如果我復制命令并在 bash 中運行它,一切正常.
but result is the same. If I copy the command and run it in bash everything is ok.
QString::toAscii().data()
和其他轉(zhuǎn)換也有不好的結果.
and other transforms also have bad result.
推薦答案
問題是您不能使用 QProcess 運行系統(tǒng)命令,而只能運行單個進程.因此,解決方法是將您的命令作為參數(shù)傳遞給 bash:
The problem is you cannot run a system command with QProcess, but only a single process. So the workaround will be to pass your command as an argument to bash:
process.start("bash", QStringList() << "-c" << "cat file | grep string");
這篇關于使用 QProcess 管道(或命令鏈)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!