首页 > 解决方案 > UnicodeEncodeError 与 Git Bash 但不是与 cmd.exe

问题描述

我正在对 进行简单的 API 调用url,将数据保存为 python 字典d并打印d

import requests

r = requests.get(url)
d = r.json()
print(d)

当我在 Windows 10 上通过 cmd.exe 执行脚本时,一切正常:

> python script.py
{'pagination': {'page': 1, 'pages': 2, 'per_page': 50, 'items': 58, 'urls': {'last': ...

但是为什么当我通过 Git Bash 运行它时会抛出错误?你能帮我理解错误吗?

$ git --version
git version 2.33.0.windows.2

$ python script.py
Traceback (most recent call last):
  File "C:\Users\...\Projects\discogs-data\script.py", line 6, in <module>
    print(d)
  File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2153' in position 1544: character maps to <undefined>

我假设 Pythond在打印之前尝试使用 cp1252 编码进行解码。但是为什么它必须首先对 d 进行解码,为什么它可以与 cmd.exe 一起使用,但不能与 Git Bash 一起使用?

标签: pythonbashcmdencodingcp1252

解决方案


我认为(Windows 和 Git Bash)都对标准输出使用不同的编码。您可以通过sys模块确认。

>>> import sys
>>> print(sys.stdout.encoding)

从您的回溯中,Git Bash 使用的cp1252编码不能对d指向的所有字符进行编码。如果您仍想在 GIT bash 终端中显示字符,您可以使用 'cp1252' 编码对字符串进行编码并设置错误,replace以便将任何不可编码的字符呈现为?

>>> a = '\u2153' # from your error message.
>>> a.encode('cp1252', errors='replace')
b'?'
>>> a.encode('cp1252', errors='replace').decode()
'?'

推荐阅读