QT 调用python环境配置

一、安装好python环境(python或anaconda都可)

  打包将python环境相关文件到一个文件夹中,如下图所示:

  打包的文件路径:

  

 

 生成的依赖包目录结构:

二、在QT工程中配置python环境

2.1工程文件(.pro)中加入库路径

INCLUDEPATH += $$PWD/Bin/Python3/include
LIBS += -L$$PWD/Bin/Python3/libs -lpython3 -lpython39

  包结构如步骤一所示 

 2.2 解决编译报错

  在项目中添加头文件(#include "Python.h")之后编译会报错,无法解析的外部符号 __imp___Py_RefTotal
无法解析的外部符号 __imp___Py_NegativeRefcount,该符号在函数 __import_array 中被引用。

  解决编译报错,需要对拷贝过来的文件夹python39/include里面的object.h和pyconfig.h 两个文件进行修改:

  1)object.h

修改:

#if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)
#define Py_REF_DEBUG
#endif

#if defined(Py_DEBUG) && !defined(Py_REF_DEBUG)
//#define Py_REF_DEBUG
#endif

修改

typedef struct{
const char* name;
int basicsize;
int itemsize;
unsigned int flags;
PyType_Slot *slots; /* terminated by slot==0. */
} PyType_Spec;

为:

#undef slots
typedef struct{
const char* name;
int basicsize;
int itemsize;
unsigned int flags;
PyType_Slot *slots; /* terminated by slot==0. */
} PyType_Spec;
#define slots Q_SLOTS

  2)pyconfig.h

#ifdef _DEBUG
# define Py_DEBUG
#endif

改为

#ifdef _DEBUG
//# define Py_DEBUG
#endif

2.3 调用python代码测试

    QString path = QApplication::applicationDirPath() + "/Python3";
    auto homePath = (wchar_t*)reinterpret_cast<const wchar_t*>(path.utf16());
    Py_SetPythonHome(homePath);        //将python路径加入python环境变量
    Py_Initialize();                //初始化
    if(!Py_IsInitialized())            //判断初始化是否成功
    {
//        qDebug() << "init python failed:" << path;
    }
//    qDebug() << "init python success:" << path;
    PyRun_SimpleString("import sys"); //引入sys模块
    PyRun_SimpleString("sys.path.append('./')"); //将存放python文件的路径加入搜寻路径

 

posted @ 2023-03-21 09:12  xianyongchao  阅读(839)  评论(0编辑  收藏  举报