How to execute a shell command under Linux unsing QProcess?

…衆ロ難τιáo~ 提交于 2020-02-24 11:32:07

问题


I am trying to read the screen resolution from within a Qt application, but without using the GUI module.

So I have tried using:

xrandr |grep \* |awk '{print $1}'

command through QProcess, but it shows a warning and does not give any output:

unknown escape sequence:'\\*'

Rewriting it with \\\* does not help, as it leads to the following error:

/usr/bin/xrandr: unrecognized option '|grep'\nTry '/usr/bin/xrandr --help' for more information.\n

How can I solve that?


回答1:


You have to use bash and pass the argument in quotes:

#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();
}

Output:

"1366x768\n"

Or:

QProcess process;
process.start("/bin/bash", {"-c" , "xrandr |grep \\* |awk '{print $1}'"});

Or:

QProcess process;
QString command = R"(xrandr |grep \* |awk '{print $1}')";
process.start("/bin/sh", {"-c" , command});



回答2:


You can't use QProcess to execute piped system commands like that, it is designed to run a single program with arguments Try:

QProcess process;
process.start("bash -c xrandr |grep * |awk '{print $1}'");

OR

QProcess process;
QStringList args = QString("-c,xrandr,|,grep *,|,awk '{print $1}'").split(",");
process.start("bash", args);


来源:https://stackoverflow.com/questions/52264843/how-to-execute-a-shell-command-under-linux-unsing-qprocess

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