本文以实例code讲解 C++ 调用 python 的方法。

本文在util.h中实现三个函数:

1. init_log: 用google log(glog)初始化log 
2. exe_command: 由 C++ 执行 shell code 
3. exe_py: C++调用python文件


Code:

Python:

  1. def pr(args):
  2. for arg in args:
  3. print arg
  • 1
  • 2
  • 3

C++: 
include/util.h:

  1. /***************************************************************************
  2. *-
  3. * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
  4. *-
  5. **************************************************************************/
  6. -
  7. -
  8. -
  9. /**
  10. * @file util.h
  11. * @author zhangruiqing01(zhangruiqing01@baidu.com)
  12. * @date 2015/10/24 02:17:56
  13. * @version $Revision$-
  14. * @brief-
  15. * i
  16. **/
  17. #ifndef __UTIL_H_
  18. #define __UTIL_H_
  19. #include "glog/logging.h"
  20. #include <string>
  21. #include <vector>
  22. #define PYTHON_LIB_PATH "~/.jumbo/lib/python2.7"
  23. #define PYTHON_BIN_PATH "~/.jumbo/bin/python2.7"
  24. // initial log
  25. void init_log(const char* argv);
  26. // exe shell command
  27. char* exe_command(const char* cmd);
  28. // exe python command
  29. void exe_py(
  30. const std::string module_name,
  31. const std::string func_name,
  32. const std::vector<std::string>& args);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

src/util.cpp:

  1. /***************************************************************************
  2. *-
  3. * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
  4. *-
  5. **************************************************************************/
  6. -
  7. -
  8. -
  9. /**
  10. * @file src/util.cpp
  11. * @author zhangruiqing01(zhangruiqing01@baidu.com)
  12. * @date 2015/10/24 02:12:34
  13. * @version $Revision$-
  14. * @brief-
  15. *--
  16. **/
  17. #include "util.h"
  18. #include <stdio.h>
  19. #include <errno.h>
  20. #include <Python.h>
  21. #define MAX_LENGTH 2048
  22. void init_log(const char* argv){
  23. if (!getenv("GLOG_logtostderr")) {
  24. google::LogToStderr();
  25. }
  26. google::InstallFailureSignalHandler();
  27. google::InitGoogleLogging(argv);
  28. LOG(INFO) << "Create Log successfully";
  29. }
  30. char* exe_command(const char* cmd){
  31. FILE* fres;
  32. if ((fres = popen(cmd, "r")) != NULL){
  33. char* buf_res = (char*) malloc(MAX_LENGTH);
  34. fread(buf_res, MAX_LENGTH, 1, fres);
  35. buf_res[strlen(buf_res) - 3] = '\0';
  36. //buf_res
  37. fprintf(stderr, "------------\nEXE RESULT: %s\n------------\n", buf_res);
  38. pclose(fres);
  39. return buf_res;
  40. }
  41. else{
  42. LOG(FATAL) << "Failed to execute '" << cmd << "'";
  43. }
  44. }
  45. void exe_py(
  46. const std::string module_name,
  47. const std::string func_name,
  48. const std::vector<std::string>& args){
  49. std::string args_str = "";
  50. for(auto& arg : args){
  51. args_str += arg + ",";
  52. }
  53. std::string cmd = "LD_LIBRARY_PATH=" +
  54. std::string(PYTHON_LIB_PATH) + ":" + "$LD_LIBRARY_PATH " +
  55. std::string(PYTHON_BIN_PATH) +
  56. " -c 'import sys\n" +
  57. "sys.path.append(\"pyfiles\")\n" +
  58. "import " + module_name + "\n" +
  59. "ret = " + module_name + "." + func_name + "([" +
  60. args_str + "])'";
  61. LOG(INFO) << "exec command: "<< cmd;
  62. char* res = exe_command(cmd.c_str());
  63. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

main.cpp:

  1. /***************************************************************************
  2. *-
  3. * Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
  4. *-
  5. **************************************************************************/
  6. -
  7. -
  8. -
  9. /**
  10. * @file src/util.cpp
  11. * @author zhangruiqing01(zhangruiqing01@baidu.com)
  12. * @date 2015/10/23 10:41:23
  13. * @version $Revision$-
  14. * @brief-
  15. *--
  16. **/
  17. #include <stdio.h>
  18. #include <vector>
  19. #include <string>
  20. #include <util.h>
  21. #include <iostream>
  22. int main(int argc, char* argv[]){
  23. //initial log
  24. init_log(argv[0]);
  25. char cmd[100]="echo 'abc'";
  26. char* res = exe_command(cmd);
  27. std::string arg_v[] = {"1"};
  28. std::vector<std::string>py_args(arg_v, arg_v + sizeof(arg_v)/sizeof(arg_v[0]));
  29. exe_py("printargs", "pr", py_args);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

注意其中的Makefile文件:

  1. 需要include python.h 所在目录,即python的include目录
  2. C++编译参数加入-std=c++11: 
    CXXFLAGS(‘-g -pipe -W -Wall -fPIC -std=c++11’)
  3. include glog所在目录

最后看一下本文中程序的结构:

执行结果: 

 
 
from: http://blog.csdn.net/abcjennifer/article/details/49377123

C++调用python的更多相关文章

  1. cpp 调用python

    在用cpp调用python时, 出现致命错误: no module named site  ,  原因解释器在搜索路径下没有找到python库.可以在调用Py_Initialize前,调用 Py_Se ...

  2. c调用python

    #include <Python.h>//python33(python2.x有几个函数不对应) /* PyImport_ImportModule 导入一个Python模块并返回它的指针 ...

  3. linux+php+apache web调用python脚本权限问题解决方案

    lamp : linux + apache + mysql + php 在上篇随笔中linux+php+apache调用python脚本时出现的问题的根本原因是:apache运行时使用的apache用 ...

  4. linux+php+apache web调用python脚本权限问题

    lamp : linux + apache + mysql + php 在近期项目中使用 linux + apache + php调用python脚本是出现以下权限问题: build/bdist.li ...

  5. C#中调用python方法

    最近因为项目设计,有部分使用Python脚本,因此代码中需要调用python方法. 1.首先,在c#中调用python必须安装IronPython,在 http://ironpython.codepl ...

  6. PHP 调用Python脚本

    上次做用户反馈自动翻译,写了个python脚本,将日文的用户反馈翻译成中文,效果虽然可以,但其它不懂python的童鞋就没法使用了,所以搭了个web服务,让其他人可以通过网页访问查询.使用的是apac ...

  7. C++中调用Python脚本

    C++中调用Python脚本的意义就不讲了,至少你可以把它当成文本形式的动态链接库, 需要的时候还可以改一改,只要不改变接口, C++的程序一旦编译好了,再改就没那么方便了 先看Python的代码 代 ...

  8. java调用python代码

    同样的我们需要安装jython,具体的步骤如下: 1. 去 http://sourceforge.net/projects/jython/ 下载最新的jython相关的jar包. 2. 下载下来的ja ...

  9. C#调用Python 脚本语言

    1. 安装IronPython http://pan.baidu.com/s/1qW4jNJ2  下载IronPython 2.7 安装下载下来的安装包 2. 创建项目 创建一个C#的Windows窗 ...

随机推荐

  1. 在Mac中如何显示和隐藏文件

    1.显示Mac隐藏文件的命令: 在终端中输入"defaults write com.apple.finder AppleShowAllFiles YES":  鼠标单击窗口左上角 ...

  2. 主元分析PCA理论分析及应用

    首先,必须说明的是,这篇文章是完完全全复制百度文库当中的一篇文章.本人之前对PCA比较好奇,在看到这篇文章之后发现其对PCA的描述非常详细,因此迫不及待要跟大家分享一下,希望同样对PCA比较困惑的朋友 ...

  3. 解释型语言和编译型语言如何交互?以lua和c为例

    转自http://my.oschina.net/mayqlzu/blog/113528 问题: 最近lua很火,因为<愤怒的小鸟>使用了lua,ios上有lua解释器?它是怎么嵌入大ios ...

  4. Introduction to Financial Management

    Recently,i am learning some useful things about financial management by reading <Essentials of Co ...

  5. [转]如何写出高效能TSQL -深入浅出SQL Server Relational Engine (含 SQL 2014 in-memory Engine)

    [转]如何写出高效能TSQL -深入浅出SQL Server Relational Engine (含 SQL 2014 in-memory Engine) http://blogs.technet. ...

  6. 简述负载均衡&CDN技术

    曾经见到知乎上有人问“为什么像facebook这类的网站需要上千个工程师维护?”,下面的回答多种多样,但总结起来就是:一个高性能的web系统需要从无数个角度去考虑他,大到服务器的布局,小到软件中某个文 ...

  7. BZOJ 2301 Problem b

    AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=2301 冬令营听了莫比乌斯,这就是宋老师上课讲的例题咯[今天来实现一下] #include& ...

  8. 剑指offer--面试题21

    题目:设计包含min函数的栈,pop(),push(),min()的时间复杂度均为O(1) 自己所写代码如下:(写‘栈’的代码还是有些不熟练!) #include <iostream> u ...

  9. vertical sync

    these days, I am compelting vertical sync https://msdn.microsoft.com/zh-cn/library/windows/desktop/b ...

  10. ie 与 Chrome 时间格式化问题.

    ie 与 Chrome 时间格式化通用: new Date(res[i].Time.replaceAll("-", "/")).format("yyy ...