C ++ calls python

Source: Internet
Author: User

C ++ calls python

This document describes how to call python in C ++ using the instance code.


This article implements three functions in util. h:

1. init_log: use google log (glog) to initialize log
2. exe_command: shell code executed by C ++
3. exe_py: C ++ calls the python File

Code:

Include/util. h:

/***************************************************************************  *-                                                                           * Copyright (c) 2015 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 
  
                                                               #include 
   
                                                                #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
    
     & args);                               
    
   
  



Src/util. cpp:

/***************************************************************************      *-                                                                               * Copyright (c) 2015 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 
  
                                                                  #include 
   
                                                                   #include 
    
                                                                   #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] = '';                                             //buf_res                                                                        fprintf(stderr, ------------EXE RESULT: %s------------, 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
     
      & 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 +                                               sys.path.append(pyfiles) +                                  import  + module_name +  +                                    ret =  + module_name + . + func_name + ([ +                   args_str + ])';                                               LOG(INFO) << exec command: << cmd;                                char* res = exe_command(cmd.c_str());                           }
     
    
   
  



Main. cpp:

/***************************************************************************          *-                                                                                   * Copyright (c) 2015 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 
  
                                                                      #include 
   
                                                                        #include 
    
                                                                         #include 
     
                                                                          #include 
      
        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
       
        py_args(arg_v, arg_v + sizeof(arg_v)/sizeof(arg_v[0])); exe_py(printargs, pr, py_args); 
       
      
     
    
   
  

Note the Makefile:

You need to include the directory of python. h, that is, add-std = C ++ 11 to the c ++ compilation parameter of the include directory of python:
CXXFLAGS ('-g-pipe-W-Wall-fPIC-std = c ++ 11') include glog directory

Finally, let's take a look at the program structure in this article:


  <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPta00NC94bn7o7o8YnIgLz4NCjxpbWcgYWx0PQ = "here write picture description" src = "http://www.bkjia.com/uploads/allimg/151028/042JH251-1.png" title = ""/>

 

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.