将python 3.7默认编码从cp1252更改为cp65001 aka UTF-8

时间:2019-07-11 19:13:53

标签: python encoding utf-8 atom-editor

我需要将python的编码从cp1252更改为UTF-8。使用python 3.7.1,Atom和Atom脚本包作为终端。

我已经读过https://www.python.org/dev/peps/pep-0540/(对此有解决方案?我不知道如何实现,或者如果有用),我找不到声音分辨率。

当前它不能处理'\ u2705'或其他。当检查Python文件目录时,我发现 ... Python \ Python37 \ lib \ encodings \ cp1252.py

#When I run 
import locale
import sys
print(sys.getdefaultencoding())
print(locale.getpreferredencoding())

#I get 
utf-8
cp1252
[Finished in 0.385s]

#Error for print('\u2705')
Traceback (most recent call last):
File "C:\Users\en4ijjp\Desktop\junk.py", line 7, in <module>
print('\u2705').decode('utf-8')
File "C:\Users\en4ijjp\AppData\Local\Programs\Python\Python37\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 '\u2705' in 
position 0: character maps to <undefined>
[Finished in 0.379s]

我希望我的终端能够处理字符并在使用print()时显示它们

1 个答案:

答案 0 :(得分:0)

将以下内容放在python脚本顶部时,可以解决此问题。我能够正确打印所有字符。

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')