我正在尝试读取 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/