温馨提示×

ubuntu c++如何调用 Python

小樊
34
2026-09-08 09:54:23
栏目: 编程语言

在 Ubuntu 上用 C++ 调用 Python,常见有几种方式,从“简单可靠”到“高级灵活”依次是:


一、最常用方式:使用 Python C API(推荐)

1️⃣ 安装 Python 开发头文件

sudo apt update
sudo apt install python3-dev

确认 Python 版本:

python3 --version

2️⃣ 示例:C++ 调用 Python 函数

假设有一个 Python 文件 test.py

# test.py
def add(a, b):
    return a + b

C++ 代码 main.cpp

#include <Python.h>
#include <iostream>

int main() {
    Py_Initialize();

    // 添加当前路径
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

    PyObject* pModule = PyImport_ImportModule("test");
    if (!pModule) {
        std::cerr << "Failed to load Python module\n";
        return 1;
    }

    PyObject* pFunc = PyObject_GetAttrString(pModule, "add");
    if (!pFunc || !PyCallable_Check(pFunc)) {
        std::cerr << "Function not found\n";
        return 1;
    }

    PyObject* pArgs = PyTuple_Pack(2,
        PyLong_FromLong(3),
        PyLong_FromLong(5));

    PyObject* pResult = PyObject_CallObject(pFunc, pArgs);

    long result = PyLong_AsLong(pResult);
    std::cout << "Result: " << result << std::endl;

    Py_DECREF(pArgs);
    Py_DECREF(pResult);
    Py_DECREF(pFunc);
    Py_DECREF(pModule);

    Py_Finalize();
    return 0;
}

3️⃣ 编译

g++ main.cpp -o main $(python3-config --cflags --ldflags)

运行:

./main

✅ 优点:

  • 官方支持
  • 稳定、可控
  • 适合长期项目

二、调用 Python 脚本(简单粗暴)

#include <cstdlib>

int main() {
    system("python3 test.py");
}

✅ 适合:

  • 只跑脚本
  • 不关心返回值

❌ 不适合:

  • 高性能
  • 复杂交互

三、使用 pybind11(C++ ↔ Python 双向)

如果你希望 Python 调用 C++,或 C++ 调用 Python 都很自然

pip install pybind11

适合写扩展模块,但不太适合“C++ 直接调 Python 脚本”。


四、使用 Boost.Python(老牌方案)

sudo apt install libboost-python-dev

功能强,但配置复杂,维护成本高,现在不如 pybind11 流行。


五、常见问题

❓ 找不到 Python.h

sudo apt install python3-dev

❓ Py_Initialize 失败

确保:

  • 系统装了 Python
  • 没有混用不同 Python 版本

❓ 多线程调用

  • 必须在主线程 Py_Initialize
  • 子线程用 PyGILState_Ensure / Release

六、推荐方案总结

场景 推荐
C++ 调 Python 脚本 Python C API
只跑脚本 system()
双向调用 pybind11
老项目 Boost.Python

如果你愿意,我可以:

  • 给你一个 CMake 示例
  • 教你 C++ 传 NumPy 数组
  • 在 C++ 中调用 PyTorch / OpenCV Python

你现在是想做什么类型的调用?

0