照着【Qtcreator中C++调用python方法_:-1: error: lnk1146: 没有用选项“/libpath:”指定的参数_alxe_made的博客-CSDN博客】走,遇到的第一个意外:
Could not find platform independent libraries <prefix>
根据网上的经验,搞环境变量搞了一会儿bug就消失了(中午睡起来迷迷糊糊的,也记不清具体是咋没的了😂)。
接着:
ModuleNotFoundError: No module named 'test1'
test1是我的python代码,QT中的关键c++代码如下:
Py_Initialize();
if ( !Py_IsInitialized() )
{
PyErr_Print();
return -1;
}
PyObject* pModule = PyImport_ImportModule("test1");
if (!pModule) {
PyErr_Print();
cout<< "Cant open python file!\n" << endl;
return -1;
}
PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello"); // 这里的hellow就是python文件定义的函数
if(!pFunhello){
cout<<"Get function hello failed"<<endl;
return -1;
}
PyObject_CallFunction(pFunhello,NULL);
Py_Finalize();
可见,
Py_Initialize();
正常运行,问题出在:
PyObject* pModule = PyImport_ImportModule("test1");
百思不得其解,然后看同行们的成功案例,从【C++(Qt)与Python混合编程(一) - 知乎】中得到经验,在该语句前加三段代码,变为:
Py_Initialize();
if ( !Py_IsInitialized() )
{
PyErr_Print();
return -1;
}
//在这里加
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.argv = ['python.py']");
PyRun_SimpleString("sys.path.append('./')");
//加以上三句
PyObject* pModule = PyImport_ImportModule("test1");
if (!pModule) {
PyErr_Print();
cout<< "Cant open python file!\n" << endl;
return -1;
}
PyObject* pFunhello= PyObject_GetAttrString(pModule,"hello"); // 这里的hellow就是python文件定义的函数
if(!pFunhello){
cout<<"Get function hello failed"<<endl;
return -1;
}
PyObject_CallFunction(pFunhello,NULL);
Py_Finalize();
然后......就好了!神奇!据ChatGPT说:
“
这段代码的作用是将当前目录
'./'
添加到 Python 模块的搜索路径中,这样在导入模块时,Python 就会先在当前目录中搜索对应的模块文件。同时,这段代码还将
sys.argv
设置为只包含一个元素'python.py'
。在 Python 中,sys.argv
是一个包含命令行参数的列表,第一个元素通常是脚本文件名,后面跟着的才是命令行参数。在这里,我们将其修改为只包含一个元素'python.py'
,是因为我们并不需要通过命令行参数来传递信息。综上,这段代码的作用是为了确保我们可以在当前目录中成功导入所需的模块。
”
此外,我的test.py文件不像大多数教程一样要拷贝到
C:\...\build-use_python_in_cxx-Clone_of_Desktop_Qt_5_15_2_MSVC2019_64bit-Debug\debug
而是放在其父文件中:
否则还会报【ModuleNotFoundError: No module named 'test1'】的错。