讲述C++中调用Python脚本


也许大家对与Python脚本还不是很了解,看完本文后对您一定会大有帮助,下文除了学习Python脚本的基本性质外还对调用Python脚本时出现的问题进行全面研究。

需要的时候还可以改一改,只要不改变接口, C++的程序一旦编译好了,再改就没那么方便了 先看Python脚本代码

  1. #test function  
  2.  
  3. def add(a,b):  
  4.  
  5.     print "in python function add"  
  6.  
  7.     print "a = " + str(a)  
  8.  
  9.     print "b = " + str(b)  
  10.  
  11.     print "ret = " + str(a+b)  
  12.  
  13.     return  
  14.  
  15.  
  16.  
  17. def foo(a):  
  18.  
  19.     print "in python function foo"  
  20.  
  21.     print "a = " + str(a)  
  22.  
  23.     print "ret = " + str(a * a)  
  24.  
  25.     return 

把上面的PPython脚本代码存为pytest.py接下来是c++ 的代码:

  1. #include "Python.h"  
  2.  
  3. int main(int argc, char** argv)  
  4. {  
  5.     // 初始化Python  
  6.     //在使用Python系统前,必须使用Py_Initialize对其  
  7.     //进行初始化。它会载入Python的内建模块并添加系统路  
  8.     //径到模块搜索路径中。这个函数没有返回值,检查系统  
  9.     //是否初始化成功需要使用Py_IsInitialized。  
  10.  
  11.     Py_Initialize();  
  12.  
  13.     // 检查初始化是否成功  
  14.     if ( !Py_IsInitialized() )   
  15.     {  
  16.         return -1;  
  17.     }  
  18.  
  19.     // 添加当前路径  
  20.     //把输入的字符串作为Python代码直接运行,返回0  
  21.     //表示成功,-1表示有错。大多时候错误都是因为字符串  
  22.     //中有语法错误。  
  23.     PyRun_SimpleString("import sys");  
  24.     PyRun_SimpleString("sys.path.append('./')");  
  25.     PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;  
  26.  
  27.     // 载入名为pytest的脚本  
  28.     pName = PyString_FromString("pytest");  
  29.     pModule = PyImport_Import(pName);  
  30.     if ( !pModule )  
  31.     {  
  32.         printf("can't find pytest.py");  
  33.         getchar();  
  34.         return -1;  
  35.     }  
  36.     pDict = PyModule_GetDict(pModule);  
  37.     if ( !pDict )   
  38.     {  
  39.         return -1;  
  40.     }  
  41.  
  42.     // 找出函数名为add的函数  
  43.     pFunc = PyDict_GetItemString(pDict, "add");  
  44.     if ( !pFunc || !PyCallable_Check(pFunc) )  
  45.     {  
  46.         printf("can't find function [add]");  
  47.         getchar();  
  48.         return -1;  
  49.     } 

编译选项, 需要手动指定Python脚本的include 路径, 和链接接路径。

  1. 如何使Python嵌入C++应用程序?
  2. 深入探讨Ruby与Python语法比较
  3. Python学习资料介绍分享
  4. Python学习经验谈:版本、IDE选择及编码解 决方案
  5. 浅析Python的GIL和线程安全

评论关闭