使用PyInstaller构建Cython编译的python代码。

问题描述 投票:22回答:1

我正试图用Python构建一个多文件的代码,其中包括 PyInstaller. 为此,我已经编译了以下代码 Cython,并且正在使用 .so 的文件。.py 文件。

假设第1个文件是 main.py 和进口的是 file_a.pyfile_b.py,我得到 file_a.sofile_b.so Cython编译后。

当我把 main.py, file_a.sofile_b.so 在一个文件夹中,并通过以下方式运行它 "python main.py",它的工作。

但当我用 PyInstaller 并尝试运行生成的可执行文件,它对在 file_afile_b.

如何解决这个问题呢?一种解决方案是将所有标准模块导入到 main.py 这样就可以了。但是如果我不想改变我的代码,有什么办法呢?

python cython pyinstaller
1个回答
22
投票

所以,我得到了这个为你工作。

请看一下 将Cython扩展与Pyinstaller捆绑在一起。

快速启动。

git clone https://github.com/prologic/pyinstaller-cython-bundling.git
cd pyinstaller-cython-bundling
./dist/build.sh

这将产生一个静态二进制。

$ du -h dist/hello
4.2M    dist/hello
$ ldd dist/hello
    not a dynamic executable

并产生输出。

$ ./dist/hello 
Hello World!
FooBar

基本上,这归结为产生一个简单的 setup.py 构建分机的 file_a.sofile_b.so 然后用 pyinstaller 将应用和扩展捆绑到一个单一的执行文件中。

例子 setup.py:

from glob import glob
from setuptools import setup
from Cython.Build import cythonize


setup(
    name="test",
    scripts=glob("bin/*"),
    ext_modules=cythonize("lib/*.pyx")
)

建设扩展部分。

$ python setup.py develop

捆绑应用程序。

$ pyinstaller -r file_a.so,dll,file_a.so -r file_b.so,dll,file_b.so -F ./bin/hello

0
投票

以防有人想快速解决这个问题。

我遇到了同样的情况,找到了一个快速解决的方法。问题是pyinstaller没有在.exe文件中添加运行程序所需的库。

你需要做的就是将所有需要的库(和.so文件)导入到你的main.py文件中(调用file_a.py和file_b.py的文件)。例如,假设file_a.py使用opencv库(cv2),file_b.py使用matplotlib库。现在在你的main.py文件中,你也需要导入cv2和matplotlib。基本上,无论你在 file_a.py 和 file_b.py 中导入了什么,你都必须在 main.py 中也导入。这将告诉 pyinstaller 程序需要这些库,并将这些库包含在 exe 文件中。

© www.soinside.com 2019 - 2024. All rights reserved.