当我试图在Qt C++程序中嵌入Python脚本时,当我尝试包含Python.h时,会遇到多个问题。以下是我想提供的内容:
python.h
上没有安装Python时,
因此,我在网上搜索,试图找到一个解决办法。并发现了很多问题和博客,但没有他们涵盖了我的所有问题,它仍然花了我好几个小时和很多挫折。这就是为什么我必须用我的完整解决方案写下一个StackOverflow条目,这样它可能会有所帮助,并可能加速您的所有工作:)
发布于 2020-12-07 15:01:41
(这个答案及其所有代码示例也在非Qt环境中工作。只有2和4.是Qt特定的)
下载并安装Python https://www.python.org/downloads/release
INCLUDEPATH = "C:\Users\Public\AppData\Local\Programs\Python\Python39\include"
LIBS += -L"C:\Users\Public\AppData\Local\Programs\Python\Python39\libs" -l"python39"#include <QCoreApplication>
#pragma push_macro("slots")
#undef slots
#include <Python.h>
#pragma pop_macro("slots")
/*!
* \brief runPy can execut a Python string
* \param string (Python code)
*/
static void runPy(const char* string){
Py_Initialize();
PyRun_SimpleString(string);
Py_Finalize();
}
/*!
* \brief runPyScript executs a Python script
* \param file (the path of the script)
*/
static void runPyScript(const char* file){
FILE* fp;
Py_Initialize();
fp = _Py_fopen(file, "r");
PyRun_SimpleFile(fp, file);
Py_Finalize();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
runPy("from time import time,ctime\n"
"print('Today is', ctime(time()))\n");
//uncomment the following line to run a script
//runPyScript("test/decode.py");
return a.exec();
}每当您#包括
冲突。
#pragma push_macro("slots")
#undef slots
#include <Python.h>
#pragma pop_macro("slots")通过这些步骤,我能够使用64位MinGW和MSVC编译器在Qt中运行python。只有处于调试模式的MSVC仍然存在问题。
进一步:
如果希望将参数传递给python脚本,则需要以下函数(它可以很容易地复制粘贴到代码中):
/*!
* \brief runPyScriptArgs executs a Python script and passes arguments
* \param file (the path of the script)
* \param argc amount of arguments
* \param argv array of arguments with size of argc
*/
static void runPyScriptArgs(const char* file, int argc, char *argv[]){
FILE* fp;
wchar_t** wargv = new wchar_t*[argc];
for(int i = 0; i < argc; i++)
{
wargv[i] = Py_DecodeLocale(argv[i], nullptr);
if(wargv[i] == nullptr)
{
return;
}
}
Py_SetProgramName(wargv[0]);
Py_Initialize();
PySys_SetArgv(argc, wargv);
fp = _Py_fopen(file, "r");
PyRun_SimpleFile(fp, file);
Py_Finalize();
for(int i = 0; i < argc; i++)
{
PyMem_RawFree(wargv[i]);
wargv[i] = nullptr;
}
delete[] wargv;
wargv = nullptr;
}若要使用此函数,请按以下方式调用它(例如,在您的主目录中):
int py_argc = 2;
char* py_argv[py_argc];
py_argv[0] = "Progamm";
py_argv[1] = "Hello";
runPyScriptArgs("test/test.py", py_argc, py_argv);与测试文件夹中的test.py脚本一起使用:
import sys
if len(sys.argv) != 2:
sys.exit("Not enough args")
ca_one = str(sys.argv[0])
ca_two = str(sys.argv[1])
print ("My command line args are " + ca_one + " and " + ca_two)您将得到以下输出:
My command line args are Progamm and Hellohttps://stackoverflow.com/questions/65184133
复制相似问题