关于使用pyinstaller 打包带有matplotlib 等出现UnicodeDecodeError解决方法

本文介绍了解决在Windows环境下使用PyInstaller将包含matplotlib的Python项目打包时遇到的UnicodeDecodeError问题的方法。通过调整控制台编码格式为UTF-8,成功避免了因分析zmq包时产生的错误。

转自:http://blog.youkuaiyun.com/u011529752/article/details/54892488

环境 win7 64位旗舰版 
python3.4 anaconda 
在含有 matplotlib的脚本工程中,用pyinstaller将其打包,在loading最后一个包zmq.py时出现错误:

out = out.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 121: invalid start byte
 
  • 1
  • 2
  • 1
  • 2

查了一圈终于找到原因:

  1. 在zmq包 \Lib\site-packages\zmq\backend\cffi\__pycache__\_cffi_ext.c 文件中,声明了< sys/un.h >头文件,而在windows下没有这个文件
  2. pyinstaller在分析< sys/un.h >的时候出错,并返回错误信息
  3. 错误信息的格式是基于当前控制台的编码格式,不同的操作系统编码格式不同,而一般代码都使用utf-8编码

解决思路,改变控制台的编码格式为utf-8 
解决方法,在控制台中输入 chcp 65001,然后再使用pyinstaller -F -w xxx.py 打包成功。

参考 
解决方法网址

### 使用 PyInstaller 打包后出现 `ModuleNotFoundError: No module named 'matplotlib'` 的解决方案 当使用 PyInstaller 打包包含 `matplotlib` 的 Python 应用程序时,可能会出现 `ModuleNotFoundError: No module named 'matplotlib'` 的错误。这通常是因为 PyInstaller 未能正确识别并打包 `matplotlib` 模块及其依赖项,导致生成的可执行文件在运行时找不到该模块。 #### 解决方法 1. **确保 `matplotlib` 已正确安装** 在打包前,需要确保 `matplotlib` 已在当前 Python 环境中安装。可以使用以下命令安装: ```bash pip install matplotlib ``` 如果网络连接不稳定,可以使用国内镜像源加速安装过程: ```bash pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple ``` 2. **使用 `--hidden-import` 参数手动包含 `matplotlib` 模块** 在某些情况下,PyInstaller 可能无法自动检测到 `matplotlib` 的所有依赖模块。可以通过 `--hidden-import` 参数手动指定需要包含的模块。例如: ```bash pyinstaller --onefile --hidden-import=matplotlib --hidden-import=matplotlib.backends.backend_pdf your_script.py ``` 这条命令会生成一个单文件的打包应用,并明确包含 `matplotlib` 及其 PDF 后端模块[^2]。 3. **编辑 `.spec` 文件以包含缺失的模块** 如果希望更精细地控制打包过程,可以编辑 PyInstaller 生成的 `.spec` 文件。在 `a = Analysis(...)` 行中找到 `hiddenimports=[]` 参数,并在其中添加 `matplotlib` 及其相关模块: ```python a = Analysis(['your_script.py'], pathex=['path_to_your_script'], binaries=[], datas=[], hiddenimports=['matplotlib', 'matplotlib.backends.backend_pdf'], ...) ``` 保存 `.spec` 文件后,使用以下命令重新打包应用: ```bash pyinstaller your_script.spec ``` 4. **确保 PyInstaller 为最新版本** 为了获得最佳的兼容性和功能支持,建议使用最新版本的 PyInstaller。可以通过以下命令更新 PyInstaller: ```bash pip install --upgrade pyinstaller ``` 5. **检查打包后的依赖路径** 如果仍然遇到问题,可能需要检查打包后的依赖路径是否正确。可以使用以下代码验证 `matplotlib` 是否能够正常导入: ```python import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) plt.show() ``` 如果代码运行正常,说明问题已解决。 --- ### 相关问题 1. 如何在使用 PyInstaller 打包时处理未自动检测到的模块? 2. 如何通过编辑 `.spec` 文件优化 PyInstaller打包过程? 3. 如何确保 PyInstaller 打包的应用在不同环境中正常运行? 4. 如何解决 PyInstaller 打包后出现的 `No module named 'matplotlib.backends.backend_tkagg'` 错误? 5. 如何在打包过程中包含非二进制文件(如图片、配置文件等)?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值