Python3.7用PyInstaller打包exe报hook-pydoc导入错误怎么解决
问题场景
- 运行环境:Python 3.7.4
- 执行打包命令:
pyinstaller test.py --noconsole --onefile - 报错信息:
PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_pydoc required by hook for module C:\Users\user\Anaconda3\lib\site-packages\PyInstaller\hooks\hook-pydoc.py. Please check whether module __PyInstaller_hooks_0_pydoc actually exists and whether the hook is compatible with your version of C:\Users\hiro\Anaconda3\lib\site-packages\PyInstaller\hooks\hook-pydoc.py: You might want to read more about hooks in the manual and provide a pull-request to improve PyInstaller.
- 已排查情况:
- 查看hook-pydoc.py文件,未找到版本相关说明
- 无法定位到__PyInstaller_hooks_0_pydoc模块
解决方法
方法1:更换适配Python3.7的PyInstaller版本
PyInstaller 5.x及以上版本已停止对Python3.7的官方支持,内置hook和老版本Python存在兼容冲突,先卸载现有版本安装兼容稳定版:
pip uninstall pyinstaller pip install pyinstaller==4.10
安装完成后重新执行原始打包命令即可。
方法2:打包时排除pydoc模块
如果你的业务代码没有直接调用pydoc相关功能,打包时添加排除参数跳过有问题的hook即可:
pyinstaller test.py --noconsole --onefile --exclude-module pydoc
方法3:清理缓存后重新打包
如果之前有过打包失败的记录,先删除项目目录下的build文件夹、dist文件夹以及后缀为.spec的缓存文件,再重新执行打包命令。
兼容问题说明
该报错确实属于PyInstaller版本兼容问题,是高版本PyInstaller停止维护Python3.7后,内置的hook-pydoc.py和老版本Python的模块依赖不匹配导致的,不需要修改业务代码。
内容的提问来源于stack exchange,提问作者Hiro Koba

