如何在没有本地Python安装的情况下创建嵌入和运行Python代码的应用程序?

Rob*_*ert 10 c python dll distribution

你好软件开发人员.

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

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

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

我怎么能做到这一点?那是一个循序渐进的食谱吗?

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

提前致谢.

Lau*_*eau 6

你看过Python的官方文档:将Python嵌入到另一个应用程序中吗?

IBM还有这个非常好的PDF:在C应用程序中嵌入Python脚本.

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


Rob*_*ert 6

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

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

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

...
Run Code Online (Sandbox Code Playgroud)