使用PyInstaller构建Cython编译的python代码 [英] Building Cython-compiled python code with PyInstaller
问题描述
我正在尝试使用 PyInstaller
构建Python多文件代码。为此,我使用 Cython
编译了代码,并使用 .so
文件代替了 .py
文件。
I am trying to build a Python multi-file code with PyInstaller
. For that I have compiled the code with Cython
, and am using .so
files generated in place of .py
files.
假设第一个文件是 main.py
,导入的是 file_a.py
和 file_b.py
,我得到的是 file_a.so
和 file_b.so
进行Cython编译后。
Assuming the 1st file is main.py
and the imported ones are file_a.py
and file_b.py
, I get file_a.so
and file_b.so
after Cython compilation.
当我放入 main.py
时, file_a.so
和 file_b.so
放在一个文件夹中,然后通过 python main.py
运行它,就可以了。
When I put main.py
, file_a.so
and file_b.so
in a folder and run it by "python main.py"
, it works.
但是,当我使用 PyInstaller
生成它并尝试运行生成的可执行文件时,它会为 file_a
和 file_b
。
But when I build it with PyInstaller
and try to run the executable generated, it throws errors for imports done in file_a
and file_b
.
如何解决?一种解决方案是将所有标准模块导入 main.py
中,此方法有效。但是,如果我不想更改我的代码,那有什么解决方案?
How can this be fixed? One solution is to import all standard modules in main.py
and this works. But if I do not wish to change my code, what can be the solution?
推荐答案
所以我为您工作了。
快速入门:
git clone https://github.com/prologic/pyinstaller-cython-bundling.git
cd pyinstaller-cython-bundling
./dist/build.sh
这会生成一个静态二进制:
This produces a static binary:
$ du -h dist/hello
4.2M dist/hello
$ ldd dist/hello
not a dynamic executable
并产生输出:
$ ./dist/hello
Hello World!
FooBar
基本上,这可以归结为生成一个简单的 setup.py
来构建扩展名 file_a.so
和 file_b.so
,然后使用 pyinstaller 将应用程序扩展捆绑到一个executeble中。
Basically this came down to producing a simple setup.py
that builds the extensions file_a.so
and file_b.so
and then uses pyinstaller to bundle the application the extensions into a single executeble.
示例 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
这篇关于使用PyInstaller构建Cython编译的python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!