最近用pyinstaller打包的时候,程序中包含statsmodels.api这个第三方库,然后打包完后运行EXE时遇到找不到包的:“no module named statsmodels.tsa.XXXXX”错误,搞得我焦头烂额,钻研了一下终于总算是解决了。不过我找遍国内外网站,都没有相关解决办法, 也是靠自己摸索出来的,所以就做个好人好事,分享出来。
当导入statsmodels.api的时候,python安装目录下的Anaconda3\Lib\site-packages\statsmodels\tsa\statespace,Anaconda3\Lib\site-packages\statsmodels\tsa\statespace\_filters和Anaconda3\Lib\site-packages\statsmodels\tsa\statespace\_smoothers目录下有很多pyd文件:
这些pyd文件,用pyinstaller打包时,是无法打包的,打包时必须用--hidden-import=PYD的文件名,隐藏才可以,否则就算打包完了,运行EXE的时候,会报各种各样的无法找到某某模块的错误,比如“no module named statsmodels.tsa.statespace._kalman_filter”等等。
所以解决方法:
1. 首先在Anaconda3\Lib\site-packages\PyInstaller\hooks目录下,建立hook-statsmodels.py文件:
文件内容为:
hiddenimports=[
#all your previous hidden imports
'statsmodels.tsa.statespace._kalman_filter',
'statsmodels.tsa.statespace._kalman_smoother',
'statsmodels.tsa.statespace._representation',
'statsmodels.tsa.statespace._simulation_smoother',
'statsmodels.tsa.statespace._statespace',
'statsmodels.tsa.statespace._tools',
'statsmodels.tsa.statespace._filters._conventional',
'statsmodels.tsa.statespace._filters._inversions',
'statsmodels.tsa.statespace._filters._univariate',
'statsmodels.tsa.statespace._smoothers._alternative',
'statsmodels.tsa.statespace._smoothers._classical',
'statsmodels.tsa.statespace._smoothers._conventional',
'statsmodels.tsa.statespace._smoothers._univariate'
]
2. pyinstaller 打包时命令行输入 --hidden-import= XXX, XXX为以上的文件名
比如:
pyinstaller -F -c 主文件.py -p 额外路径1 -p 额外路径2 --hidden-import=statsmodels.tsa.statespace._kalman_filter --hidden-import=statsmodels.tsa.statespace._kalman_smoother --hidden-import=statsmodels.tsa.statespace._representation --hidden-import=statsmodels.tsa.statespace._simulation_smoother --hidden-import=statsmodels.tsa.statespace._statespace --hidden-import=statsmodels.tsa.statespace._tools --hidden-import=statsmodels.tsa.statespace._filters._conventional --hidden-import=statsmodels.tsa.statespace._filters._inversions --hidden-import=statsmodels.tsa.statespace._filters._univariate --hidden-import=statsmodels.tsa.statespace._smoothers._alternative --hidden-import=statsmodels.tsa.statespace._smoothers._classical --hidden-import=statsmodels.tsa.statespace._smoothers._conventional --hidden-import=statsmodels.tsa.statespace._smoothers._univariate
这样打包完,EXE就可以顺利运行了!
总之python打包就是个大坑!