Qprocess打乱我的linux命令(我想)。怎么修? [英] Qprocess messes my linux command up (i think). how to fix?

查看:535
本文介绍了Qprocess打乱我的linux命令(我想)。怎么修?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要强制我的c ++ QT4应用程序从linux命令读取结果。我试图使用Qprocess,但一旦我的命令变得复杂,它会以某种方式(只是猜测),不工作。



在这里,我试图为yu小示例:

  QProcess过程; 
command =ls -l | grep a | sort;
qDebug()<< Execute command - >+ command;
process.start(command);
process.waitForFinished(-1);
QString processStdout = process.readAllStandardOutput();
QString processStderr = process.readAllStandardError();
qDebug()<< Std out - >+ processStdout;
qDebug()<< std err - >+ processStderr;

这将打印:

 执行命令 - > ls -l | grep a | sort 
Std out - >
Std err - > ls:|:没有这样的文件或目录

$



如果我用一个更简单的例子替换这个<$ c
$ b

$ c> command =ls -l; 它工作无流
操作系统在标准错误上返回错误。



解决方案

QProcess 不支持shell命令。因此,管道符号不是由shell解释,而是直接传递给 ls ls 将其解释为文件名,并抱怨因为没有名为 | 的文件。



您需要通过重定向QProcess对象的输入和输出流来手动设置管道。阅读文档以了解如何执行此操作。



一般应该避免shell命令,而是依赖于Qt类和函数。当然没有必要调用 grep ls ,因为使用 QRegExp QDir 。如果你需要执行子进程,那么使用 :: start(const QString& const QStringList& OpenMode)重载并传递所有参数为列表,以避免引用问题。 / p>

I need to force my c++ QT4 application to read results from a linux command. I am trying to use Qprocess but as soon as my command gets complicated it get messed somehow (just guessing) and does not work.

Here i try to make for yu a small example:

QProcess process;
command = "ls -l | grep a | sort";
qDebug() << "Execute command -> "+command;
process.start( command );
process.waitForFinished(-1);
QString processStdout = process.readAllStandardOutput();
QString processStderr = process.readAllStandardError();
qDebug() << "Std out -> "+processStdout;
qDebug() << "Std err -> "+processStderr;

this will print:

Execute command -> ls -l | grep a | sort
"Std out -> " 
"Std err -> ls: |: No such file or directory

while would correctly print the file names if runed from the consol.

If i replace the comman with somethink simpler such command = "ls -l"; it work smoothless The error is returned on standar error by the OS.

I guess thereforethat the Qstring used for the command gets manipolated somehow. Any idea about wht's happening?

解决方案

QProcess does not support shell commands. The pipe symbols is thus not interpreted by a shell, but instead directly passed to ls. ls interprets it as file name, and complains because apparantly there is no file named |.

You need to setup pipes manually by redirecting input and output streams of QProcess objects. Read the documentation to learn how to do this.

Generally how should avoid shell commands, and instead rely on Qt classes and functions. There is certainly no need to call grep or ls, because the same can be done easier with QRegExp, and QDir. If you need to execute subprocesses, then use the ::start(const QString&, const QStringList&, OpenMode) overload and pass all arguments as list to avoid quoting issues.

这篇关于Qprocess打乱我的linux命令(我想)。怎么修?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆