QProcess传递(shell)参数

时间:2017-06-10 09:45:02

标签: linux qt shell qprocess

我正在尝试在Qt中读取shell脚本的输出。但是,将参数传递给shell脚本不起作用,因为它完全被忽略。我在下面的摘录中做错了什么?

QProcess *process = new QProcess;
process->start("sh", QStringList() << "-c" << "\"xdotool getactivewindow\"");
process->waitForFinished();
QString output = process->readAllStandardOutput();
target = output.toUInt();

我已经看了几个其他线程并尝试过诸如

之类的解决方案
process->start("sh", QStringList() << "-c" << "xdotool getactivewindow");

process->start("sh", QStringList() << "-c" << "xdotool" << "getactivewindow");

但没有效果。

1 个答案:

答案 0 :(得分:1)

我希望你的第二种方法能够奏效。

我使用以下脚本(test.sh)测试了它:

#!/bin/bash
echo "First arg: $1"
echo "Second arg: $2"

我用以下方式使用QProcess调用脚本:

QProcess *process = new QProcess;
process->start("./test.sh", QStringList() << "abc" << "xyz");
process->waitForFinished();
qDebug () << process->readAllStandardOutput();
// returns: "First arg: abc\nSecond arg: xyz\n" => OK

process->start("sh", QStringList() << "-c" << "./test.sh abc xyz");
process->waitForFinished();
qDebug () << process->readAllStandardOutput();
// returns: "First arg: abc\nSecond arg: xyz\n" => OK

process->start("sh", QStringList() << "-c" << "./test.sh" <<  "abc xyz");
process->waitForFinished();
qDebug () << process->readAllStandardOutput();
// returns: "First arg: \nSecond arg: \n" => WRONG

<强>解释

  • process->start("sh", QStringList() << "-c" << "\"xdotool getactivewindow\"");:不需要(也不允许)引用自己的论点。 documentation并不是那么清楚,但它指出:
  

注意:不会进一步拆分参数。

  • process->start("sh", QStringList() << "-c" << "xdotool getactivewindow");:这应该有用

  • process->start("sh", QStringList() << "-c" << "xdotool" << "getactivewindow");getactivewindow作为参数传递给sh而不是xdotool