代码之家  ›  专栏  ›  技术社区  ›  Robert

如何创建一个不在本地安装python的情况下嵌入和运行python代码的应用程序?

  •  9
  • Robert  · 技术社区  · 16 年前

    你好,各位软件开发人员。

    我想发布一个C程序,它可以通过嵌入Python解释器来编写脚本。
    C程序使用py_initialize、py import_import等来完成python嵌入。

    我正在寻找一个只分发以下组件的解决方案:

    • 我的程序可执行文件及其库
    • python库(dll/so)
    • 包含所有必需的python模块和库的zip文件。

    我怎样才能做到这一点?有一个循序渐进的食谱吗?

    该解决方案应同时适用于Windows和Linux。

    事先谢谢。

    6 回复  |  直到 12 年前
        1
  •  5
  •   Laurent Parenteau    16 年前

    您看过python的官方文档吗: Embedding Python into another application ?

    IBM还提供了这个非常好的PDF: Embed Python scripting in C application .

    您应该能够使用这两种资源来做您想要做的事情。

        2
  •  3
  •   Robert    16 年前

    我只是在一台没有安装python的计算机上测试了我的可执行文件,它运行正常。

    当您将python链接到可执行文件(无论是动态的还是静态的)时,您的可执行文件已经获得了基本的python语言功能(操作符、方法、字符串、列表、元组、dict等基本结构),而不需要任何其他依赖性。

    然后我让python的setup.py通过 python setup.py sdist --format=zip 给了我一个我命名的压缩文件 pylib-2.6.4.zip .

    我接下来的步骤是:

    char pycmd[1000]; // temporary buffer for forged Python script lines
    ...
    Py_NoSiteFlag=1;
    Py_SetProgramName(argv[0]);
    Py_SetPythonHome(directoryWhereMyOwnPythonScriptsReside);
    Py_InitializeEx(0);
    
    // forge Python command to set the lookup path
    // add the zipped Python distribution library to the search path as well
    snprintf(
        pycmd,
        sizeof(pycmd),
        "import sys; sys.path = ['%s/pylib-2.6.4.zip','%s']",
        applicationDirectory,
        directoryWhereMyOwnPythonScriptsReside
    );
    
    // ... and execute
    PyRun_SimpleString(pycmd);
    
    // now all succeeding Python import calls should be able to
    // find the other modules, especially those in the zipped library
    
    ...
    
        3
  •  1
  •   Pierre-Jean Coudert    16 年前

    你看了吗 Portable Python ?不需要安装任何东西。只需复制包含的文件即可使用解释器。

    编辑:这是一个仅限Windows的解决方案。

        4
  •  0
  •   Daniel Pryden    16 年前

    你看过吗 Embedding Python in Another Application 在python文档中?

    一旦你有了这个,你就可以使用一个导入钩子(参见 PEP 302 )让嵌入的Python代码从您选择的任何位置加载模块。但是,如果您将所有内容都放在一个压缩文件中,那么您可能只需要将其作为 sys.path .

        5
  •  0
  •   Jive Dadson hmishra2250    16 年前

    有一个叫做Py2Exe的程序。我不知道它是否只适用于Windows。另外,我使用的最新版本并没有将所有内容打包成一个.exe文件。它创建了一堆必须分发的东西——一个zip文件等等。

        6
  •  0
  •   Community Mohan Dere    9 年前

    我想这就是你想要的答案 Unable to get python embedded to work with zip'd library

    基本上,你需要:

    Py_NoSiteFlag=1;
    Py_SetProgramName(argv[0]);
    Py_SetPythonHome(".");
    Py_InitializeEx(0);
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path = ['.','python27.zip','python27.zip/DLLs','python27.zip/Lib','python27.zip/site-packages']");
    

    在您的C/C++代码中加载Python标准库。

    在你的 python27.zip ,所有 .py 源代码位于 python27.zip/Lib 如中所述 sys.path 变量。

    希望这有帮助。

    推荐文章