我正在不同的ubuntu机器上用PyInstaller打包一个项目。在其中一些项目上,当执行生成的项目时,会抛出以下错误:
文件"~/PyInstaller-2.1/proj/build/proj/out00 PYZ.PYZ/CryptoRandom",第28行,在ImportError中:无法导入名称OSRNG
然而,导入在python控制台中运行得很好,我可以在不打包的情况下执行该项目
我尝试过卸载和重新安装pycrypto,但没有成功,我还尝试过添加特定的
来自Crypto.随机导入OSRNG
到主文件,这样PyInstaller就可以拾取它。
我用hithwen的配方解决了这个问题,但用了一个稍微不同的.spec
文件。我把它留在这里供大家参考。
# -*- mode: python -*-
#Tweaks to properly import pyCrypto
#Get the path
def get_crypto_path():
'''Auto import sometimes fails on linux'''
import Crypto
crypto_path = Crypto.__path__[0]
return crypto_path
#Analysis remains untouched
a = Analysis(['myapp.py'],
pathex=[],
hiddenimports=[],
hookspath=None,
runtime_hooks=None)
#Add to the tree the pyCrypto folder
dict_tree = Tree(get_crypto_path(), prefix='Crypto', excludes=["*.pyc"])
a.datas += dict_tree
#As we have the so/pyd in the pyCrypto folder, we don't need them anymore, so we take them out from the executable path
a.binaries = filter(lambda x: 'Crypto' not in x[0], a.binaries)
#PYZ remains untouched
pyz = PYZ(a.pure)
#EXE remains untouched
exe = EXE(pyz,
a.scripts,
exclude_binaries=True,
name='myapp',
debug=False,
strip=None,
upx=True,
console=True )
#COLLECT remains untouched
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name='myapp')
我通过将Crypto目录树添加到规范文件中解决了这个问题
我用这个函数得到路径:
def get_crypto_path():
'''Auto import sometimes fails on linux'''
import Crypto
crypto_path = Crypto.__path__[0]
return crypto_path
然后在规范文件中替换:
dict_tree = Tree('CRYPTO_PATH', prefix='Crypto', excludes=["*.pyc"])
a.datas += dict_tree
我通过用pycryptodomex
替换pycrypto/pycryptodome使其正常工作。共享已发布答案的链接:https://stackoverflow.com/a/50009769/4355695