Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 呼叫 Python 實戰:封裝 util 工具類的三個關鍵函式

本文用實例程式碼說明 C++ 如何反過來呼叫 Python。

util.h 中共實作三個函式:

1. init_log:以 glog 初始化日誌;
2. exe_command:由 C++ 執行 shell 指令;
3. exe_py:由 C++ 呼叫 Python 檔案中的函式。

Python 端:

def pr(args):
    for arg in args:
        print arg

C++ 端,include/util.h:

/**
 * @file util.h
 * @brief 日誌初始化、shell 執行與 Python 呼叫工具
 **/
#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"

// 初始化日誌
void init_log(const char* argv);

// 執行 shell 指令
char* exe_command(const char* cmd);

// 執行 python 命令
void exe_py(const std::string module_name,
            const std::string func_name,
            const std::vector<std::string>& args);

#endif

src/util.cpp:

#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';
        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());
}

main.cpp:

#include <stdio.h>
#include <vector>
#include <string>
#include <util.h>
#include <iostream>

int main(int argc, char* argv[]) {
    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);
}

設計思路其實很樸素:把 Python 直譯器當成一個外部命令來跑,用 popen 抓取 stdout,就能把 C++ 的資料送進 Python 函式並取回結果。

Makefile 有三個必踩的重點:

  1. 要 include python.h 所在目錄,也就是 Python 的 include 路徑;
  2. C++ 編譯參數需加入 -std=c++11,例如 CXXFLAGS('-g -pipe -W -Wall -fPIC -std=c++11'),因為程式碼用到了 auto 與 range-based for;
  3. 別忘了 include glog 的目錄。

延伸閱讀:CentOS 源碼安裝 Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》 https://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》 https://www.linuxidc.com/Linux/2013-11/92693.htm

Python 腳本獲取 Linux 系統資訊 https://www.linuxidc.com/Linux/2013-08/88531.htm

Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved