Qt C++ - 用双引号构造一个 QStringlist



我需要一些帮助来做一些非常简单的事情,但这些事情一直不起作用:

我正在尝试构建此QStringList

-c "import imp; foo = imp.load_source('myTest', '/home/John/fw/demos/myTest.py'); foo.myTestFunction();"

注意引号!但是我已经尝试了无数种事情,例如:

QStringList params;
params << "-c "import imp; foo = imp.load_source('myTest', '/home/John/fw/demos/myTest.py'); foo.myTestFunction() " ";

但这似乎行不通!

发生什么:

我正在尝试从我的Qt gui运行python脚本。我可以在使用终端时运行脚本,如下所示:

$ python2 -c "import imp; foo = imp.load_source('myTest', '/home/John/fw/demos/myTest.py'); foo.myTestFunction();"
output: this is the python script

我现在正在尝试在我的Qt C++代码中复制它,如下所示:

{
QProcess p;
QStringList params;
params << "-c "import imp; foo = imp.load_source('myTest', '/home/John/fw/demos/myTest.py');     foo.myTestFunction() " ";
qDebug()<<params;
p.start("python2 ", params);
p.waitForFinished(-1);
QString p_stdout = p.readAll();
qDebug()<<p_stdout;
qDebug()<<"ran py script";
}

但它只输出:

"-c "import imp; foo = imp.load_source('myTest', '/home/John/fw/demos/myTest.py'); foo.myTestFunction() " "
""
ran py scrip

这是脚本:

#!/usr/bin/env python2
import os
import numpy as np
def myTestFunction():
print('output: this is the python script')
return 55
if __name__=='__main__':
a = myTestFunction()
print('returned value: '+ str(a))

我希望至少看到"55"而不是像"这样的空字符串。小子能帮帮我吗?

当程序使用单独的参数运行时,它会返回一个空字符串,我仍然不明白原因。但是,如果我们将所有内容连接在一个命令中,它就能够正确执行应用程序:

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QProcess p;
QString cmd("/usr/bin/python2 -c "import imp; foo = imp.load_source('myTest', '/home/qhipa/myTest.py'); foo.myTestFunction()"");
p.start(cmd);
qDebug()<< p.arguments();
if (!p.waitForFinished(-1))
qDebug() << "Make failed:" << p.errorString();
else
qDebug() << "Make output:" << p.readAll();
qDebug()<<"ran py script";
return a.exec();
}

输出:

("-c", "import imp; foo = imp.load_source('myTest', '/home/qhipa/myTest.py'); foo.myTestFunction()")
Make output: "output: this is the python scriptn"
ran py script

如果我们删除引号也可以工作,似乎在参数的开头即使命令需要也没有必要放置引号。

QProcess p;
QStringList params = QStringList()<<"-c"<<
"import imp; foo = imp.load_source('myTest', '/home/qhipa/myTest.py'); foo.myTestFunction()";
p.start("/usr/bin/python2", params);
qDebug()<< p.arguments();
if (!p.waitForFinished(-1))
qDebug() << "Make failed:" << p.errorString();
else
qDebug() << "Make output:" << p.readAll();
qDebug()<<"ran py script";

相关内容

  • 没有找到相关文章

最新更新