• 请不要在回答技术问题时复制粘贴 AI 生成的内容
YUCOAT
V2EX  ›  程序员

cpp 如何嵌入 Python 解释器

  •  
  •   YUCOAT · Apr 16, 2015 · 4739 views
    This topic created in 4134 days ago, the information mentioned may be changed or developed.
    我想在我的cpp程序里调用Python脚本函数,然后照着网上的资料,写了一个demo,运行成功了。然后我把我的demo、py的dll、py脚本,MSVCxxx之类的文件挪到另外一台没有安装Python解释器的电脑上,我的demo跑不起来了。

    很显然,我的demo是通过python的dll调用了我本机的Python解释器来运行Python脚本的。现在我需要让我的cpp程序在客户的电脑上也运行Python脚本,而客户的电脑是没有安装Python解释器的,那我应该怎么做呢?

    我没有找到类似的文档,谢谢大家的回答。
    8 replies    2015-04-17 21:59:17 +08:00
    timonwong
        1
    timonwong  
       Apr 16, 2015
    先看官方文档:
    https://docs.python.org/2/extending/embedding.html

    一些库:
    超级重量级的 boost::python

    如果你已经在本机能运行了,你需要打包:
    1. Python??.dll 以及依赖 (比如 msvc 运行库)
    2. python stdlib, (可以打包为 zip, 比如 python27.zip, 然后加入 PYTHONPATH 环境变量)
    YUCOAT
        2
    YUCOAT  
    OP
       Apr 16, 2015
    @timonwong

    我已经尝试过了,把我机器上的Python34文件复制到没有安装的电脑上,然后把我的exe和py都放到对面机器上的Python34里,把msvc之类的必要dll页复制过去就能直接运行我的程序。可以不用设置环境变量。
    timonwong
        3
    timonwong  
       Apr 16, 2015   ❤️ 2
    @YUCOAT
    我的意思是这样的

    - 你的程序.exe
    - python34.dll
    - python34.zip
    - msvcrt 相关 dll

    python34.zip 是 Python34\Lib 打包
    Py_SetPath(L"xxx\\python34.zip");
    YUCOAT
        4
    YUCOAT  
    OP
       Apr 17, 2015
    @timonwong 了解啦~
    Septembers
        5
    Septembers  
       Apr 17, 2015
    @timonwong
    /t/180051#r_1933214
    在Python-2.7.3/Modules/python.c的main函数的首行加入
    Py_SetPath(L"./python-stdlib.zip");
    会编译失败 请问需要改写才能编译通过并运行 谢谢
    timonwong
        6
    timonwong  
       Apr 17, 2015
    Septembers
        7
    Septembers  
       Apr 17, 2015
    @timonwong
    ➜ Python-2.7.3 ./python
    [1] 19515 segmentation fault (core dumped) ./python
    timonwong
        8
    timonwong  
       Apr 17, 2015
    @Septembers
    1. 为什么运行 python,这里的上下文是 embedding 不是 extending...
    2. PySys_SetPath 接收的是 char * 不是 wchart_t *
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3855 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 00:50 · PVG 08:50 · LAX 17:50 · JFK 20:50
    ♥ Do have faith in what you're doing.