首页 > 解决方案 > UnicodeDecodeError:“charmap”编解码器无法解码位置 73776 中的字节 0x81

问题描述

这是一个 Django 项目。pip install -r requirements.txt在本地 virtualenv 中运行时遇到错误。

Collecting https://github.com/jedestep/Zappa/archive/layer-support.zip (from -r requirements\base.txt (line 9))
Using cached https://github.com/jedestep/Zappa/archive/layer-support.zip
ERROR: Command errored out with exit status 1:
     command: 'c:\users\user~1\desktop\project\project\venv\scripts\python.exe' -c 'import sys, setuptools, tokenize
    ; sys.argv[0] = '"'"'C:\\Users\\USER~1\\AppData\\Local\\Temp\\pip-req-build-6htw2gh2\\setup.py'"'"'; __file__='"'"'C:\
    \Users\\USER~1\\AppData\\Local\\Temp\\pip-req-build-6htw2gh2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(
    __file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' e
    gg_info --egg-base 'C:\Users\USER~1\AppData\Local\Temp\pip-req-build-6htw2gh2\pip-egg-info'
         cwd: C:\Users\USER~1\AppData\Local\Temp\pip-req-build-6htw2gh2\
    Complete output (7 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\USER~1\AppData\Local\Temp\pip-req-build-6htw2gh2\setup.py", line 8, in <module>
        long_description = readme_file.read()
      File "c:\users\user~1\desktop\project\project\venv\lib\encodings\cp1252.py", line 23, in decode
        return codecs.charmap_decode(input,self.errors,decoding_table)[0]
    UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 73776: character maps to <undefined>
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

要求确实在 vagrant 环境中按预期安装,但是我记得它也可以在我的机器上本地工作。不幸的是,我不确定导致此错误的更改是什么,这可能是拉动的结果。

版本: Python: 3.6.5 Django: 2.2 pip: 20.0.2

我已经运行pip install --upgrade setuptools了,但它并没有改变错误。当我尝试运行时,自动测试数据库下载会发生类似的错误tox

任何想法,将不胜感激。谢谢。

标签: pythonwindowsencoding

解决方案


要求确实在 vagrant 环境中按预期安装,但是我记得它也可以在我的机器上本地工作。不幸的是,我不确定导致此错误的更改是什么,这可能是拉动的结果。

问题在于您尝试安装的软件包以及您的环境配置。我猜这个包在某个时候更新了并且坏了,因为他们在他们的自述文件中添加了表情符号或其他东西:如果你看一下错误消息,你会发现在读入东西时有问题long_description,检查包的 setup.py你可以找到开始附近的问题:

with open('README.md') as readme_file:
    long_description = readme_file.read()

这里的问题是,当您open的文件未指定模式时,它将是“文本”,因此 python 会自动将字节解码为 str,这很酷,除了它用于此类解码的编码是系统的“默认”编码(通过调用找到locale.getpreferredencoding(False)),这通常不是可取的。

您的 Vagrant 环境和开发人员的机器可能具有 UTF8 默认编码(就像现在大多数 unix 系统一样),同时您的本地 windows 框没有并且默认使用 CP1252,这会爆炸。可悲的是,我不是 Windows 用户(对于开发人员),所以我不知道如何更改“默认编码”,考虑到粗略搜索 SO 所产生的结果,这甚至可能是不可能的。

我会建议:

  • 要求包作者修复他们的 setup.py 以明确指定encoding打开文件时
  • 试图了解更多关于getpreferredencoding's 的内部决策,以及是否可以通过 Windows 中的环境覆盖首选编码(显然可以/很容易覆盖标准流的编码,但chcp/set PYTHONIOENCODING显然不为正常做任何事情open
  • 在适用于 Linux 的 Windows 子系统上运行你的东西,这可能开箱即用

PS:我冒昧地更新了您帖子的标签,因为 django、pip 和 egg 真的与实际问题无关


推荐阅读