1. 程式人生 > >python Pyinstaller 打包 statsmodels.api失敗

python Pyinstaller 打包 statsmodels.api失敗

最近用pyinstaller打包的時候,程式中包含statsmodels.api這個第三方庫,然後打包完後執行EXE時遇到找不到包的:“no module named statsmodels.tsa.XXXXX”錯誤,搞得我焦頭爛額,鑽研了一下終於總算是解決了。不過我找遍國內外網站,都沒有相關解決辦法, 也是靠自己摸索出來的,所以就做個好人好事,分享出來。

當匯入statsmodels.api的時候,python安裝目錄下的Anaconda3\Lib\site-packages\statsmodels\tsa\statespaceAnaconda3\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打包就是個大坑!

還有另外一個總結:

所有PYD檔案,打包的時候都用 --hidden-import=檔名,最保險