【问题标题】:UnicodeEncodeError with Git Bash but not with cmd.exeUnicodeEncodeError 与 Git Bash 但不是与 cmd.exe
【发布时间】: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


【解决方案1】:

我认为两者(Windows 和 Git Bash)uses different encoding for standard output。可以通过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()
'?'

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 2011-09-02
    • 2015-04-13
    • 2019-03-25
    • 1970-01-01
    • 2018-05-18
    • 2016-04-19
    • 1970-01-01
    相关资源
    最近更新 更多