【问题标题】:How to create an application which embeds and runs Python code without local Python installation?如何在不安装本地 Python 的情况下创建嵌入和运行 Python 代码的应用程序?
【发布时间】:2011-01-30 11:16:35
【问题描述】:

各位软件开发人员您好。

我想分发一个可通过嵌入 Python 解释器编写脚本的 C 程序。
C程序使用Py_Initialize、PyImport_Import等来完成Python嵌入。

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

  • 我的程序可执行文件及其库
  • Python 库 (dll/so)
  • 一个包含所有必要 Python 模块和库的 ZIP 文件。

我怎样才能做到这一点?有没有一步一步的方法?

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

提前致谢。

【问题讨论】:

  • 我删除了我的答案,因为它不适用。您可能想要编辑问题,以便清楚地表明您正在将 Python 嵌入到 C 应用程序中。

标签: python c dll distribution


【解决方案1】:

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

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

【讨论】:

  • 便携式 Python 在我进行研究时也是一个发现。但这不是我要找的。不应该有任何其他依赖。
【解决方案2】:

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

一旦你有了它,你就可以使用一个导入钩子(参见PEP 302)让你的嵌入式 Python 代码从你选择的任何地方加载模块。但是,如果您将所有内容都放在一个 zip 文件中,您可能只需将其设为 sys.path 上的唯一条目。

【讨论】:

  • 啊,我应该在发帖之前刷新一下cmets...!
【解决方案3】:

你看过 Python 的官方文档吗:Embedding Python into another application

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

你应该能够使用这两种资源做你想做的事。

【讨论】:

  • 我按照嵌入指南做了,效果很好。
【解决方案4】:

我只是在一台没有安装 Python 的计算机上测试了我的可执行文件并且它工作正常。

当您将 Python 链接到您的可执行文件(无论是动态还是静态)时,您的可执行文件已经获得了基本的 Python 语言功能(运算符、方法、字符串、列表、元组、字典等基本结构),而没有任何其他依赖关系。

然后我让 Python 的 setup.py 通过 python setup.py sdist --format=zip 编译 Python 源代码分发,它给了我一个名为 pylib-2.6.4.zip 的 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

...

【讨论】:

    【解决方案5】:

    有一个名为 py2exe 的程序。我不知道它是否仅适用于Windows。此外,我使用的最新版本并没有将所有内容打包到一个 .exe 文件中。它创建了一堆必须分发的东西 - 一个 zip 文件等。

    【讨论】:

    • 标题似乎具有误导性——嵌入了 Python。我不想将 Python 代码嵌入到可执行文件中 - 可执行文件应通过链接到 Python 变得可编写脚本。因此 py2exe 不是解决方案。
    【解决方案6】:

    我想这里就是你想要的答案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 变量中所述。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2023-01-25
      • 1970-01-01
      • 2016-02-02
      • 2011-06-26
      • 2017-11-26
      • 2014-05-03
      • 1970-01-01
      相关资源
      最近更新 更多