pip install requirements.txt 报 UnicodeDecodeError: gbk 解码失败问题记录
问题现象
在 Windows 环境下执行项目依赖安装命令:
pip install -r requirements.txt
或:
python -m pip install -r requirements.txt
出现如下错误:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 212: illegal multibyte sequence
decoding with 'cp936' codec failed
错误发生在 pip 读取 requirements.txt 阶段,还没有真正开始安装依赖。
问题原因
Windows 中文系统下,Python / pip 在某些情况下会使用系统默认编码 GBK 或 CP936 读取文本文件。
但项目中的 requirements.txt 实际是 UTF-8 编码,文件里包含中文注释或特殊字符,例如:
# PPT Master Dependencies / PPT Master 依赖
如果 pip 按 GBK/CP936 去读取 UTF-8 文件,就可能触发:
UnicodeDecodeError: 'gbk' codec can't decode byte ...
本质原因是:
文件编码是 UTF-8,但 pip 按 GBK/CP936 解码
解决方案一:在 requirements.txt 顶部声明 UTF-8 编码
在 requirements.txt 第一行添加:
# -*- coding: utf-8 -*-
例如:
# -*- coding: utf-8 -*-
# PPT Master Dependencies / PPT Master 依赖
python-pptx>=0.6.21
requests>=2.31.0
如果项目中存在嵌套依赖文件,例如顶层 requirements.txt 引用了另一个文件:
-r skills/ppt-master/requirements.txt
那么被引用的文件也建议加上同样的编码声明:
# -*- coding: utf-8 -*-
然后重新执行:
python -m pip install -r requirements.txt
解决方案二:临时强制 Python 使用 UTF-8
在 PowerShell 中执行:
$env:PYTHONUTF8="1"
python -m pip install -r requirements.txt
这个环境变量只对当前 PowerShell 会话生效。
解决方案三:使用纯 ASCII 的 requirements.txt
如果不需要中文注释,也可以把 requirements.txt 中的中文和特殊符号删掉,只保留依赖项:
python-pptx>=0.6.21
requests>=2.31.0
beautifulsoup4>=4.12.0
这种方式最简单直接,但会损失注释说明。
推荐做法
推荐使用第一种方式:
# -*- coding: utf-8 -*-
原因是:
- 不需要删除中文注释;
- 对项目其他使用者更友好;
- 不依赖当前终端环境变量;
- 可以避免 Windows GBK 默认编码带来的读取问题。
总结
这个问题不是依赖包本身安装失败,而是 pip 读取 requirements.txt 时的编码不匹配导致的。
排查思路如下:
- 如果错误中出现
UnicodeDecodeError; - 并且包含
gbk、cp936; - 同时发生在读取
requirements.txt阶段;
那么优先检查 requirements.txt 是否是 UTF-8 编码,并在文件顶部添加:
# -*- coding: utf-8 -*-
然后重新执行:
python -m pip install -r requirements.txt

1028

被折叠的 条评论
为什么被折叠?



