简体   繁体   English

如何在Linux unsing QProcess下执行shell命令?

[英]How to execute a shell command under Linux unsing QProcess?

I am trying to read the screen resolution from within a Qt application, but without using the GUI module. 我试图从Qt应用程序中读取屏幕分辨率,但不使用GUI模块。

So I have tried using: 所以我尝试过使用:

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

command through QProcess , but it shows a warning and does not give any output: 通过QProcess命令,但它显示警告并且不提供任何输出:

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? 我怎么解决这个问题?

You have to use bash and pass the argument in quotes: 你必须使用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();
}

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

You can't use QProcess to execute piped system commands like that, it is designed to run a single program with arguments Try: 您不能使用QProcess来执行这样的管道系统命令,它旨在运行带参数的单个程序尝试:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM