Linux如何在不使用QProcess的情况下执行shell命令? [英] How to execute a shell command under Linux unsing QProcess?
本文介绍了Linux如何在不使用QProcess的情况下执行shell命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从Qt应用程序中读取屏幕分辨率,但不使用GUI模块.
I am trying to read the screen resolution from within a Qt application, but without using the GUI module.
所以我尝试使用:
xrandr |grep \* |awk '{print $1}'
通过 QProcess 的
命令,但它显示警告并且不提供任何输出:
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
我该如何解决?
推荐答案
您必须使用bash并在引号中传递参数:
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();
}
输出:
"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});
这篇关于Linux如何在不使用QProcess的情况下执行shell命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文