我正在尝试使用Cython
和PyInstaller
库将我的项目代码打包成可执行的二进制文件。我的代码目录如下所示:
main.py
是从program_a.py
和program_b.py
输入逻辑的主要代码。
我成功地将我的program_a
和program_b
文件转换为.so文件,可以通过任何python代码导入.so文件。我是通过执行以下脚本完成的。
from distutils.core import setup
from Cython.Build import cythonize
sourcefiles = ['program_a.py', 'program_b.py']
setup(
name = "Hello World",
ext_modules = cythonize(sourcefiles),
)
通过执行> python setup.py build_ext --inplace
我得到.so
文件,如下所示
当我运行python main.py
时,它与.so
文件完美匹配。这表明我可以将它们作为模块导入。
现在,我想将二进制文件(.so)文件和main.py
打包成单个二进制文件。为此,我使用了pyInstaller
提供的以下命令
pyinstaller "main.py" --onefile
它实际上在dist/
文件夹中提供了二进制文件,但我无法导入某些模块并收到以下错误:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import program_a as lisence_checker
File "program_a.py", line 1, in init program_a
ModuleNotFoundError: No module named 'licensing'
[18032] Failed to execute script main
如何将库与pyinstaller链接或将库信息嵌入到我的二进制文件中?
我发现了什么:
但是所有这些上面的链接都没有在python代码示例中使用任何外部包。我能够在没有外部模块的情况下编译代码
熟悉PyInstaller软件包后,我能够找出问题所在。我按照以下步骤使其最终适合我。
现在,发布我的答案,以帮助其他人:)
## Build *.so files from python modules
1. Execute "setup.py" file
> python setup.py build
2. It will generate "*.so" modules inside "build/lib.linux-x86_64-3.6" dir.
## Created binary from cython modules
1. Copy the binaries (i.e. *.so) files into binary folder
2. Get inside the binary folder 'cd binary'
3. Run Pyinstaller command inside binary directory: `python -O -m PyInstaller --clean --onefile idps.spec`
4. Your binary will be inside dist folder 'binary/dist/'
5. Execute the binary in linux using './dist/sample_app'
6. Your app is ready :)
这是spec文件,使它适合我:
# -*- mode: python -*-
block_cipher = None
a = Analysis(['main.py'],
pathex=['cython_pyinstaller_sample/binary'],
binaries=[('program_a.cpython-36m-x86_64-linux-gnu.so', '.'),('program_b.cpython-36m-x86_64-linux-gnu.so', '.')],
datas=[('config_file.txt', '.')],
hiddenimports=['licensing', 'licensing.methods', 'pandas'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False) pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher) exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='sample_app',
debug=True,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )