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

系统 1566 0

在 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 !" <
                  
                  
                
              
            
          

更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论