linux - QProcess 传递(shell)参数

标签 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");

但都没有用。

最佳答案

我希望您的第二种方法应该有效。

我使用以下脚本 ( 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不是那么清楚,但它指出:

Note: No further splitting of the arguments is performed.

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

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

关于linux - QProcess 传递(shell)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44471879/

相关文章:

linux - 将文件从源复制到目标的 Bash Shell 脚本

c++ - Qt:如何在每次迭代中创建等待用户输入的循环?

Qt Designer 无法提升 QMainWindow

c++ - 插入到 QTextEdit 中的 HTML 不符合样式表

bash - 通过 bash 脚本执行 curl 请求

linux - RPM Epoch header 是否有任何限制?

linux - 汇编程序在 GDB 中找不到调试符号

python - 过滤数组并仅检索以最高数字开头的字符串

shell - Bourne Shell 中是否有像 Bash 中那样的进程替换?

bash - 将命令作为输入传递给另一个命令(su、ssh、sh 等)