[英]How to execute a shell command under Linux unsing QProcess?
我試圖從Qt應用程序中讀取屏幕分辨率,但不使用GUI模塊。
所以我嘗試過使用:
xrandr |grep \* |awk '{print $1}'
通過QProcess命令,但它顯示警告並且不提供任何輸出:
unknown escape sequence:'\\\\*'
用\\\\\\*
重寫它沒有用,因為它會導致以下錯誤:
/usr/bin/xrandr: unrecognized option '|grep'\\nTry '/usr/bin/xrandr --help' for more information.\\n
我怎么解決這個問題?
你必須使用bash並在引號中傳遞參數:
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QProcess process;
QObject::connect(&process, &QProcess::readyReadStandardOutput, [&process](){
qDebug()<<process.readAllStandardOutput();
});
QObject::connect(&process, &QProcess::readyReadStandardError, [&process](){
qDebug()<<process.readAllStandardError();
});
process.start("/bin/bash -c \"xrandr |grep \\* |awk '{print $1}' \"");
return a.exec();
}
輸出:
"1366x768\n"
要么:
QProcess process;
process.start("/bin/bash", {"-c" , "xrandr |grep \\* |awk '{print $1}'"});
要么:
QProcess process;
QString command = R"(xrandr |grep \* |awk '{print $1}')";
process.start("/bin/sh", {"-c" , command});
您不能使用QProcess來執行這樣的管道系統命令,它旨在運行帶參數的單個程序嘗試:
QProcess process;
process.start("bash -c xrandr |grep * |awk '{print $1}'");
要么
QProcess process;
QStringList args = QString("-c,xrandr,|,grep *,|,awk '{print $1}'").split(",");
process.start("bash", args);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.