本文以实例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:

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

C++: 
include/util.h:

/***************************************************************************
*-
* Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
*-
**************************************************************************/
-
-
-
/**
* @file util.h
* @author zhangruiqing01(zhangruiqing01@baidu.com)
* @date 2015/10/24 02:17:56
* @version $Revision$-
* @brief-
* i
**/ #ifndef __UTIL_H_
#define __UTIL_H_ #include "glog/logging.h"
#include <string>
#include <vector> #define PYTHON_LIB_PATH "~/.jumbo/lib/python2.7"
#define PYTHON_BIN_PATH "~/.jumbo/bin/python2.7" // initial log
void init_log(const char* argv); // exe shell command
char* exe_command(const char* cmd); // exe python command
void exe_py(
const std::string module_name,
const std::string func_name,
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:

/***************************************************************************
*-
* Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
*-
**************************************************************************/
-
-
-
/**
* @file src/util.cpp
* @author zhangruiqing01(zhangruiqing01@baidu.com)
* @date 2015/10/24 02:12:34
* @version $Revision$-
* @brief-
*--
**/ #include "util.h"
#include <stdio.h>
#include <errno.h>
#include <Python.h>
#define MAX_LENGTH 2048 void init_log(const char* argv){
if (!getenv("GLOG_logtostderr")) {
google::LogToStderr();
}
google::InstallFailureSignalHandler();
google::InitGoogleLogging(argv);
LOG(INFO) << "Create Log successfully";
} char* exe_command(const char* cmd){
FILE* fres;
if ((fres = popen(cmd, "r")) != NULL){
char* buf_res = (char*) malloc(MAX_LENGTH);
fread(buf_res, MAX_LENGTH, 1, fres);
buf_res[strlen(buf_res) - 3] = '\0';
//buf_res
fprintf(stderr, "------------\nEXE RESULT: %s\n------------\n", buf_res);
pclose(fres);
return buf_res;
}
else{
LOG(FATAL) << "Failed to execute '" << cmd << "'";
}
} void exe_py(
const std::string module_name,
const std::string func_name,
const std::vector<std::string>& args){
std::string args_str = "";
for(auto& arg : args){
args_str += arg + ",";
} std::string cmd = "LD_LIBRARY_PATH=" +
std::string(PYTHON_LIB_PATH) + ":" + "$LD_LIBRARY_PATH " +
std::string(PYTHON_BIN_PATH) +
" -c 'import sys\n" +
"sys.path.append(\"pyfiles\")\n" +
"import " + module_name + "\n" +
"ret = " + module_name + "." + func_name + "([" +
args_str + "])'";
LOG(INFO) << "exec command: "<< cmd;
char* res = exe_command(cmd.c_str());
}
  • 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:

/***************************************************************************
*-
* Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
*-
**************************************************************************/
-
-
-
/**
* @file src/util.cpp
* @author zhangruiqing01(zhangruiqing01@baidu.com)
* @date 2015/10/23 10:41:23
* @version $Revision$-
* @brief-
*--
**/ #include <stdio.h>
#include <vector>
#include <string>
#include <util.h>
#include <iostream> int main(int argc, char* argv[]){
//initial log
init_log(argv[0]); char cmd[100]="echo 'abc'";
char* res = exe_command(cmd); std::string arg_v[] = {"1"};
std::vector<std::string>py_args(arg_v, arg_v + sizeof(arg_v)/sizeof(arg_v[0]));
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. /lib64/libc.so.6: version `GLIBC_2.14' not found问题

    <备忘> 参考文章: https://my.oschina.net/zhangxu0512/blog/262275 问题答疑: http://blog.sina.com.cn/s/blog ...

  2. 关于django批量上传图片

    本来想一张一张上传的,但是明显会对客户造成不必要的麻烦,所以如果前台一次性上传五张十张的话,那就简单的多. 但是后台我数据库对于图片存储的字段只有一个,不可能有多少张照片就要多少个字段来存储.也就是说 ...

  3. Java 查询URL对应IP地址

    /** * @ClassName TestSocket1 * @Version 1.0 * @Date 2014-9-26 上午10:19:36 */ public class TestSocket1 ...

  4. 求字符串的最长回文字串 O(n)

    昨天参加了某公司的校园招聘的笔试题,做得惨不忍睹,其中就有这么一道算法设计题:求一个字符串的最长回文字串.我在ACM校队选拔赛上遇到过这道题,当时用的后缀数组AC的,但是模板忘了没写出代码来. 回头我 ...

  5. 【BZOJ】【2038】小Z的袜子

    填个坑吧,学习了莫队算法.我也忘记是看的哪位大牛的博客&代码学习的了T_T,如果您发现了的话请私信我,我会注明学自您的代码. 另外感谢@PoPoQQQ大神 好,进入正文,莫队算法,也算是一种暴 ...

  6. delete错误

    今天找了半天delete错误,后来才知道是MTd和MDd模式的问题,MTd的内存申请和释放必须在同一个模块里面,接口上面不能使用stl等,MDd可以使用.改成MDd就可以了

  7. 项目分析(map复习)

    有段时间没看map里面的东西了,刚才看发现功能上增加了一些,在来复习了一次流程初始化每个map建立线程,这个线程有两个功能,1.处理GS发过来的包 2.驱动map里面的定时器GS发过来的包是存在m_g ...

  8. 导入ApiDemo报错,找不到R文件

    1.先检查当前ApiDemo对应的SDK版本是否一致(项目右键-Properties-Android) 2.查看是什么错误.我的就是layout中的progressbar_2.xml中所有组件的id前 ...

  9. 禁止触屏滑动touchmove方法介绍

    在移动端页面开发中,有时需要禁止用户滑动屏幕,搜索了好久才找到移动终端的touch事件,touchstar,touchmove,touchend. 阻止滚动 一些移动设备有缺省的touchmove行为 ...

  10. SQLserver分页查询实例

    Sqlserver数据库分页查询一直是Sqlserver的短板,闲来无事,想出几种方法,假设有表ARTICLE,字段ID.YEAR...(其他省略),数据53210条(客户真实数据,量不大),分页查询 ...