C + + calls Python

Source: Internet
Author: User

This article explains C + + 's method of invoking Python with instance code.


This article implements three functions in Util.h:

1. Init_log: Initialize log with Google log (Glog)
2. Exe_command: Shell code executed by C + +
3. exe_py:c++ calling Python file

Code:

Include/util.h:

/***************************************************************************  *- * Copyright (c) Baidu.com, Inc. All Rights Reserved * * * * * * * *********************************************************************/-                                                                            - -/** * @file util.h * @author ZHANGRUIQING01 ([email protected]) * @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 logvoidInit_log (Const Char* argv);//EXE shell commandChar* Exe_command (Const Char* cmd);//EXE python commandvoidExe_py (Const STD::stringModule_name,Const STD::stringFunc_name,Const STD:: Vector<std::string>& args);



Src/util.cpp:

/***************************************************************************      *- * Copyright (c) Baidu.com, Inc.                                                                               All Rights Reserved * * **************************************************************************/-                                                                                - -/** * @file src/util.cpp * @author ZHANGRUIQING01 ([email protected]) * @                                                           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 2048voidInit_log (Const Char* argv) {if(!getenv ("Glog_logtostderr")) {Google::logtostderr (); } Google::installfailuresignalha                                           Ndler ();                                                 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] =' + ';//buf_res        fprintf(stderr,"------------\nexe RESULT:%s\n------------\ n", buf_res); Pclose (FRES);returnBuf_res; }Else{LOG (FATAL) <<"Failed to execute "<< cmd <<"'"; }                                                                            }voidExe_py (Const STD::stringModule_name,Const STD::stringFunc_name,Const STD:: Vector<std::string>& args) {STD::stringArgs_str =""; for(Auto& Arg:args) {args_str + = arg +","; }STD::stringcmd ="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 ()); }



Main.cpp:

/***************************************************************************          *- * Copyright (c) Baidu.com, Inc.                                                                                   All Rights Reserved * * **************************************************************************/-                                                                                    - -/** * @file src/util.cpp                                   * @author ZHANGRUIQING01 ([email protected])                                                               * @date 2015/10/23 10:41:23 * @version $Revision $-                                                                            * @brief- *--                                                                                  **/                                                                                 #include <stdio.h>#include <vector>#include <string>#include <util.h>#include <iostream>intMainintargcChar* argv[]) {//initial LogInit_log (argv[0]);Charcmd[ -]="Echo ' abc '";Char* res = Exe_command (cmd);STD::stringArg_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);

Note the makefile file:

    1. The directory where include Python.h is required, the Include directory for Python
    2. C + + compilation parameters added-std=c++11:
      Cxxflags ('-g-pipe-w-wall-fpic-std=c++11 ')
    3. directory where include Glog

Finally look at the structure of the program in this article:



Execution Result:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C + + calls Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.