命令在终端中工作,但不通过 QProcess 工作
- 2024-11-08 09:04:00
- admin 原创
- 276
问题描述:
ifconfig | grep 'inet'
通过终端执行时可以正常工作。但通过 QProcess 执行时不行
我的示例代码是
QProcess p1;
p1.start("ifconfig | grep 'inet'");
p1.waitForFinished();
QString output(p1.readAllStandardOutput());
textEdit->setText(output);
文本编辑上没有显示任何内容。
但是当我在 qprocess 启动时使用时ifconfig
,输出显示在 textedit 上。我是否错过了构造命令的任何技巧ifconfig | grep 'inet'
,例如使用'
for'
和|
for |
? 表示特殊字符?但我也尝试过 :(
解决方案 1:
QProcess 执行一个单一进程。您尝试执行的是执行shell 命令,而不是进程。命令管道是 shell 的一个功能。
有三种可能的解决方案:
将您想要执行的命令作为参数放入sh
after -c
("command") 中:
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();
解决方案 2:
该QProcess
对象不会自动为您提供完整的 shell 语法:您不能使用管道。使用 shell 来实现这一点:
p1.start("/bin/sh -c \"ifconfig | grep inet\"");
解决方案 3:
看来您不能在 QProcess 中使用管道符号。
但是,有setStandardOutputProcess方法可以将输出传送到下一个过程。
API 中提供了一个示例。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD