问题
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