2017-06-10 78 views
1

我试图读取Qt中的shell脚本的输出。但是,将参数传递给shell脚本不起作用,因为它完全被忽略。以下摘录中我做错了什么?QProcess传递(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"); 

,但没有奏效。

+0

是否'流程 - >启动( “xdotool”,QStringList中()<<“getactivewindow”);'工作?如果你自己在shell中执行它,命令是什么? – m7913d

+1

在shell中,我执行xdotool getactivewindow。和thx,'process-> start(“xdotool”,QStringList()<<“getactivewindow”);'工作!我怀疑是因为只有一个命令没有任何空间可以逃脱。所以原来的问题仍然没有解决。 – Alex

回答

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