gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:41 25 4
gpt4 key购买 nike

我需要将 Python 的编码从 Windows-1252 更改为为 UTF-8。我正在使用 Python 3.7.1,Atom ,以及终端的 Atom 脚本包。

我读过 PEP 540 -- Add a new UTF-8 Mode (解决这个问题?我不知道如何实现或是否有用)我找不到合理的解决方案。

目前它无法处理“\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() 时显示它们。

最佳答案

将以下内容放在 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')

关于python - 将 python 3.7 默认编码从 cp1252 更改为 cp65001 aka UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56995919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com