ifconfig | grep 'inet'
通过终端执行时正在工作。但不是通过QProcess
我的示例代码是
QProcess p1;
p1.start("ifconfig | grep 'inet'");
p1.waitForFinished();
QString output(p1.readAllStandardOutput());
textEdit->setText(output);
在textedit上什么都没有显示。
但是当我在qprocess的开头仅使用
ifconfig
时,输出将显示在textedit上。我是否错过了构造ifconfig | grep 'inet'
命令的任何技巧,例如将\'
用于'
和\|
用于|
?特殊字符?但我也尝试过 最佳答案
QProcess执行一个进程。您要执行的操作是执行Shell命令,而不是进程。命令管道是Shell的功能。
有三种可能的解决方案:
将要执行的命令作为参数作为sh
的后面-c
(“命令”):
QProcess sh;
sh.start("sh", QStringList() << "-c" << "ifconfig | grep inet");
sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();
或者,您可以将命令编写为
sh
的标准输入:QProcess sh;
sh.start("sh");
sh.write("ifconfig | grep inet");
sh.closeWriteChannel();
sh.waitForFinished();
QByteArray output = sh.readAll();
sh.close();
避免
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();
关于c++ - 命令在终端中运行,但不能通过QProcess运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10701504/