如何从C++调用带参数的Python脚本并实现参数传递?
在C++中调用Python脚本并传递参数
问题背景
你有一个接收两个字符串参数的Python脚本(原脚本缺少import sys且未输出返回值,需补充修正),代码如下:
import sys def main(a, b): c = a + b return c if __name__ == '__main__': print(main(sys.argv[1], sys.argv[2])) # 新增print让C++能捕获返回结果
同时需要在C++函数中调用该脚本并传递参数,目标函数框架如下:
extern "C" std::string call_py(std::string a, std::string b) { // 实现调用逻辑 }
以下提供两种可行的实现方案:
方案1:系统调用执行Shell命令
模拟控制台python3 script.py "Hi" "Bye"的调用方式,通过C++执行系统命令并捕获输出。
实现代码
#include <iostream> #include <string> #include <array> #include <cstdio> extern "C" std::string call_py(std::string a, std::string b) { // 拼接命令,给参数加引号避免空格等特殊字符解析错误 std::string cmd = "python3 script.py \"" + a + "\" \"" + b + "\""; // 捕获命令输出 std::array<char, 128> buffer; std::string result; FILE* pipe = popen(cmd.c_str(), "r"); if (!pipe) { return "Error: 执行命令失败"; } while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) { result += buffer.data(); } pclose(pipe); // 移除末尾换行符 if (!result.empty() && result.back() == '\n') { result.pop_back(); } return result; }
注意事项
- 确保
script.py在C++程序运行目录下,否则需指定绝对路径 - 若参数包含引号等特殊字符,需额外做转义处理,避免命令解析出错
- 该方式会启动独立Python进程,性能开销相对较高
方案2:嵌入Python解释器(直接调用API)
在C++进程中直接嵌入Python解释器,调用脚本函数,无需额外启动进程,性能更优。
实现代码
#include <Python.h> #include <string> #include <stdexcept> extern "C" std::string call_py(std::string a, std::string b) { // 初始化Python解释器 Py_Initialize(); if (!Py_IsInitialized()) { return "Error: Python解释器初始化失败"; } std::string result_str; try { // 将脚本所在目录添加到Python搜索路径 PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); // 替换为脚本实际目录 // 导入脚本模块 PyObject* pModule = PyImport_ImportModule("script"); if (!pModule) { PyErr_Print(); throw std::runtime_error("导入脚本模块失败"); } // 获取main函数 PyObject* pFunc = PyObject_GetAttrString(pModule, "main"); if (!pFunc || !PyCallable_Check(pFunc)) { PyErr_Print(); throw std::runtime_error("获取main函数失败"); } // 构造函数参数 PyObject* pArgs = PyTuple_New(2); PyTuple_SetItem(pArgs, 0, PyUnicode_FromString(a.c_str())); PyTuple_SetItem(pArgs, 1, PyUnicode_FromString(b.c_str())); // 调用函数并获取结果 PyObject* pResult = PyObject_CallObject(pFunc, pArgs); if (!pResult) { PyErr_Print(); throw std::runtime_error("调用main函数失败"); } // 转换Python字符串为C++字符串 char* result_cstr = PyUnicode_AsUTF8(pResult); if (result_cstr) { result_str = result_cstr; } // 释放Python资源 Py_XDECREF(pResult); Py_XDECREF(pArgs); Py_XDECREF(pFunc); Py_XDECREF(pModule); } catch (const std::exception& e) { result_str = std::string("Error: ") + e.what(); } // 关闭Python解释器 Py_Finalize(); return result_str; }
编译链接说明
编译时需链接Python开发库,示例命令(替换为你的Python版本,如python3.10):
g++ your_code.cpp -o your_program -I/usr/include/python3.x -lpython3.x
注意事项
- 需提前安装Python开发包(如
python3-dev) - 脚本文件名需与导入的模块名一致(
script.py对应导入script) - 需处理Python异常,避免C++进程崩溃
内容的提问来源于stack exchange,提问作者sama
相关产品推荐
相关产品推荐

