rak*_*eng 5 unicode python-3.x git-bash
在test.py我有
print('?????? ???')
Run Code Online (Sandbox Code Playgroud)
与cmd正常工作
> python test.py
?????? ???
Run Code Online (Sandbox Code Playgroud)
使用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>
Run Code Online (Sandbox Code Playgroud)
有谁知道通过Git Bash执行 python 代码时出错的原因?
从Python 3.7开始你可以这样做
import sys
sys.stdout.reconfigure(encoding='utf-8')
Run Code Online (Sandbox Code Playgroud)
这主要解决了我使用中文字符的 git bash 问题。它们仍然无法在控制台上正确打印到标准输出,但不会崩溃,并且当重定向到文件时,会出现正确的 unicode 字符。
归功于这个答案。
Python 3.6 直接使用 Windows API 将 Unicode 写入控制台,因此打印非 ASCII 字符要好得多。但 Git Bash 不是标准的 Windows 控制台,因此它会退回到以前的行为,在终端编码中编码 Unicode 字符串(在您的情况下为 cp1252)。cp1252 不支持西里尔字母,因此失败。这个是正常的”。您将在 Python 3.5 及更早版本中看到相同的行为。
\n\n在 Windows 控制台中,Python 3.6 应该打印实际的西里尔字符,所以令人惊讶的是你的“?????? ???”。这不是“正常”的,但也许您没有选择支持西里尔文的字体。我安装了几个 Python 版本:
\n\nC:\\>py -3.6 --version\nPython 3.6.2\n\nC:\\>py -3.6 test.py\n\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82 \xd0\xbc\xd0\xb8\xd1\x80\n\nC:\\>py -3.3 --version\nPython 3.3.5\n\nC:\\>py -3.3 test.py\nTraceback (most recent call last):\n File "test.py", line 1, in <module>\n print(\'\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442 \\u043c\\u0438\\u0440 \\u4f60\\u597d\')\n File "C:\\Python33\\lib\\encodings\\cp437.py", line 19, in encode\n return codecs.charmap_encode(input,self.errors,encoding_map)[0]\nUnicodeEncodeError: \'charmap\' codec can\'t encode characters in position 0-5: character maps to <undefined>\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
896 次 |
| 最近记录: |