命令在终端工作,但不通过QProcess [英] Command working in terminal, but not via QProcess

查看:613
本文介绍了命令在终端工作,但不通过QProcess的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ifconfig | grep 'inet'

但不通过QProcess

is working when executed via terminal. But not via QProcess

我的示例代码是

QProcess p1;
p1.start("ifconfig | grep 'inet'");
p1.waitForFinished();
QString output(p1.readAllStandardOutput());
textEdit->setText(output);

textedit上没有显示任何内容。

Nothing is getting displayed on textedit.

但是当我在qprocess的开始使用 ifconfig 时,输出显示在textedit上。我没有任何技巧构造命令 ifconfig | grep'inet',例如对'和<$ c $使用 \' c> \ | for | ?特殊字符?但我也试过:(

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:(

推荐答案

QProcess执行一个进程,你要做的是执行一个

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.

有三种可能的解决方案:

There are three possible solutions:

-c sh >(command):

Put the command you want to be executed as an argument to sh after -c ("command"):

QProcess sh;
sh.start("sh", QStringList() << "-c" << "ifconfig | grep inet");

sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();

或者你可以将命令作为 sh

Or you could write the commands as the standard input to sh:

QProcess sh;
sh.start("sh");

sh.write("ifconfig | grep inet");
sh.closeWriteChannel();

sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();

避免 sh ,是启动两个QProcesses并在你的代码中做管道:

Another approach which avoids sh, is to launch two QProcesses and do the piping in your code:

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

这篇关于命令在终端工作,但不通过QProcess的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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