【发布时间】:2021-09-22 14:31:49
【问题描述】:
我正在对url 进行简单的API 调用,将数据保存为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>
我假设 Python 在打印之前尝试使用 cp1252 编码对 d 进行解码。但是为什么它必须首先对 d 进行解码,为什么它可以与 cmd.exe 一起使用,但不能与 Git Bash 一起使用?
【问题讨论】:
-
你能在这两种情况下打印
sys.stdout.encoding吗? -
它不会尝试解码任何东西,但它必须编码才能打印出来。违规字符是一个 unicode U+2153 VULGAR FRACTION ONE THIRD (
⅓)。它不能显示在仅接受 cp1252 字符的 Git Bash 终端窗口中。你可以使用print(d.encode('cp1252', errors='replace')) -
@AbdulNiyasPM utf-8 用于 cmd 和 cp1252 用于 bash。
-
@SergeBallesta 在文件开头添加
sys.stdout.reconfigure(encoding='utf-8')也对我有用。
标签: python bash cmd encoding cp1252