C/C++/Qt与 Python 混合编程(2):Qt 调用嵌入python文件

在 Qt 的 Project 中添加一个 py 文件。

C/C++/Qt与 Python 混合编程(2):Qt 调用嵌入python文件_第1张图片

 

然后在 test_py.py 中的内容如下:

# This Python file uses the following encoding: utf-8
# if__name__ == "__main__":
# pass
def hello():
 print("hello world!")

只有一个 hello()函数,Qt 就是调用这个 hello 函数,然后执行,显示 hello,world!

在上一节的主文件中添加如下代码:

 PyRun_SimpleString("import sys\n");
 PyRun_SimpleString("print(sys.path.append('/Users/wangxinnian/Downloads/qtApp/testQP1'))\n");
 PyObject* pModule = PyImport_ImportModule("test_py");
 if (!pModule){
 printf("不能打开 python file\n");
 Py_Finalize();
 return -1;
 }
 else printf("python文件已经打开了!");
 PyObject* pFunHello = PyObject_GetAttrString(pModule, "hello"); // 这里的 hellow 就是 python 文件定义的。
 if (!pFunHello){
 cout << "Get function hello failed !" < 
  

代码分析 :

1。 引入了 python 的语句:

import sys

sys.path.append("/Users/wangxinnian/Downloads/qtApp/testQP1")

设置 test_py 寻找的资源路径,这个就是项目的目录。

2.使用PyImport_ImportModule

使用该函数打开 py 文件,取得该文件中的模块函数

3. 找到 hello 函数

使用 PyObject_GeAttrString 查找到模块中指定的函数

4. 然后执行这个函数

 PyObject_CallFunction(pFunHello,nullptr);

运行结果如下:

今日是: Thu Jul 25 10:04:03 2019

大家好!

None

hello world!

python文件已经打开了!hello 模块已经打开了,开始执行

完整的 main.cpp 内容如下:

#define PY_SSIZE_T_CLEAN
#include 
#include 
#include
using namespace std;
int main(int argc, char *argv[])
{
 QCoreApplication a(argc, argv);
 wchar_t *program = Py_DecodeLocale(argv[0], nullptr);
 if (program == nullptr) {
 fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
 exit(1);
 }
 Py_SetProgramName(program); /* optional but recommended */
 Py_Initialize();
 PyRun_SimpleString ("from time import time,ctime\n"
 "print('今日是:', ctime(time()))\n"
 "print('大家好!')\n"
 );
 PyRun_SimpleString("import sys\n");
 PyRun_SimpleString("print(sys.path.append('/Users/wangxinnian/Downloads/qtApp/testQP1'))\n");
 PyObject* pModule = PyImport_ImportModule("test_py");
 if (!pModule){
 printf("不能打开 python file\n");
 Py_Finalize();
 return -1;
 }
 else printf("python文件已经打开了!");
 PyObject* pFunHello = PyObject_GetAttrString(pModule, "hello"); // 这里的 hellow 就是 python 文件定义的。
 if (!pFunHello){
 cout << "Get function hello failed !" < 
 

你可能感兴趣的:(python,Qt,Python,与人工智能)