python - 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 一起使用?
解决方案
我认为(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()
'?'
推荐阅读
- javascript - 检查任何类型的 typeof 的最短方法是什么?
- java - Apache Camel 排除选项不能与 GenericFileFilter 一起使用
- javascript - vuejs在选择后获取日期选择器的值
- php - 如何将随机数量的表单元素中的数据保存到 SQL 表中?
- java - 如何根据线程数调度并发Runnables,而线程在完成任务后必须等待延迟
- html - 在 iframe 中使用背景图像和响应式设计强制桌面视图
- python - 如何使用基本页面中的单独页面访问功能视图的上下文?
- css - html css3 滑块 - 如何计算代码中新创建的关键帧滑块的百分比或运行时间?
- c# - MVC如何重用具有父类模型的视图
- c# - 如何在 WPF 中“从多个切换按钮中选择一个”?