Linux 命令在终端中工作,但不通过 QProcess
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10701504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Command working in terminal, but not via QProcess
提问by ScarCode
ifconfig | grep 'inet'
is working when executed via terminal. But not via QProcess
通过终端执行时正在工作。但不是通过 QProcess
My sample code is
我的示例代码是
QProcess p1;
p1.start("ifconfig | grep 'inet'");
p1.waitForFinished();
QString output(p1.readAllStandardOutput());
textEdit->setText(output);
Nothing is getting displayed on textedit.
textedit 上没有显示任何内容。
but when I use just ifconfig
in start of qprocess, output is getting displayed on textedit. Did I miss any trick to construct the command ifconfig | grep 'inet'
, like use \'
for '
and \|
for |
? for special characters? but I tried that as well:(
但是当我刚ifconfig
开始使用qprocess 时,输出会显示在 textedit 上。我是否错过了构建命令的任何技巧ifconfig | grep 'inet'
,例如 use \'
for'
和\|
for |
?对于特殊字符?但我也试过了:(
采纳答案by leemes
QProcess executes one single process. What you are trying to do is executing a shell command, not a process. The piping of commands is a feature of your shell.
QProcess 执行单个进程。您要做的是执行shell 命令,而不是进程。命令管道是 shell 的一个特性。
There are three possible solutions:
有三种可能的解决方案:
Put the command you want to be executed as an argument to sh
after -c
("command"):
将要执行的命令作为参数放在sh
after -c
("command") 中:
QProcess sh;
sh.start("sh", QStringList() << "-c" << "ifconfig | grep inet");
sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();
Or you could write the commands as the standard input to sh
:
或者您可以将命令作为标准输入写入sh
:
QProcess sh;
sh.start("sh");
sh.write("ifconfig | grep inet");
sh.closeWriteChannel();
sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();
Another approach which avoids sh
, is to launch two QProcesses and do the piping in your code:
避免 的另一种方法sh
是启动两个 QProcesses 并在您的代码中执行管道:
QProcess ifconfig;
QProcess grep;
ifconfig.setStandardOutputProcess(&grep); // "simulates" ifconfig | grep
ifconfig.start("ifconfig");
grep.start("grep", QStringList() << "inet"); // pass arguments using QStringList
grep.waitForFinished(); // grep finishes after ifconfig does
QByteArray output = grep.readAll(); // now the output is found in the 2nd process
ifconfig.close();
grep.close();
回答by kmkaplan
The QProcess
object does not automatically give you full blown shell syntax: you can not use pipes. Use a shell for this:
该QProcess
对象不会自动为您提供完整的 shell 语法:您不能使用管道。为此使用外壳:
p1.start("/bin/sh -c \"ifconfig | grep inet\"");
回答by BergmannF
You can not use the pipe symbol in QProcess it seems.
您似乎不能在 QProcess 中使用管道符号。
However there is the setStandardOutputProcessMethod that will pipe the output to the next process.
但是,有setStandardOutputProcess方法会将输出通过管道传输到下一个进程。
An example is provided in the API.
API 中提供了一个示例。