Python通过'Git Bash'打印Unicode字符串得到'UnicodeEncodeError' [英] Python print Unicode string via 'Git Bash' gets 'UnicodeEncodeError'

查看:75
本文介绍了Python通过'Git Bash'打印Unicode字符串得到'UnicodeEncodeError'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 test.py 中的

print('Привет мир')

使用 cmd 正常工作

> python test.py
?????? ???

使用 Git Bash 出现错误

$ python test.py
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    print('\u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440')
  File "C:\Users\raksa\AppData\Local\Programs\Python\Python36\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-5: character maps to <undefined>

有人知道通过 Git Bash 执行python代码时出错的原因吗?

Does anyone know the reason behind of getting error when execute python code via Git Bash?

推荐答案

Python 3.6直接使用Windows API将Unicode写入控制台,因此打印非ASCII字符要好得多.但是Git Bash不是标准的Windows控制台,因此它可以退回到以前的行为,以终端编码(在您的情况下为cp1252)编码Unicode字符串.cp1252不支持西里尔字母,因此失败.这是正常的".您将在Python 3.5及更高版本中看到相同的行为.

Python 3.6 directly uses the Windows API to write Unicode to the console, so is much better about printing non-ASCII characters. But Git Bash isn't the standard Windows console so it falls back to previous behavior, encoding Unicode string in the terminal encoding (in your case, cp1252). cp1252 doesn't support Cyrillic, so it fails. This is "normal". You'll see the same behavior in Python 3.5 and older.

在Windows控制台中,Python 3.6应该打印实际的西里尔字母,因此令人惊讶的是您的"????????????".那不是正常的",但是也许您没有选择支持西里尔字母的字体.我安装了两个Python版本:

In the Windows console Python 3.6 should print the actual Cyrillic characters, so what is surprising is your "?????? ???". That is not "normal", but perhaps you don't have a font selected that supports Cyrillic. I have a couple of Python versions installed:

C:\>py -3.6 --version
Python 3.6.2

C:\>py -3.6 test.py
Привет мир

C:\>py -3.3 --version
Python 3.3.5

C:\>py -3.3 test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    print('\u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440 \u4f60\u597d')
  File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-5: character maps to <undefined>

这篇关于Python通过'Git Bash'打印Unicode字符串得到'UnicodeEncodeError'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆