python - 更改 Python 的默认编码?

标签 python encoding utf-8 console

Python 有很多“无法编码”和“无法解码”的问题当我从控制台运行我的应用程序时。但在 Eclipse PyDev IDE,默认字符编码设置为UTF-8 ,我很好。

四处寻找设置默认编码,有人说Python在启动时删除了sys.setdefaultencoding函数,不能使用。

那么最好的解决方案是什么?

最佳答案

这是一个更简单的方法(hack),它可以返回从 sys 中删除的 setdefaultencoding() 函数:

import sys
# sys.setdefaultencoding() does not exist, here!
reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8')

(Python 3.4+ 的注意事项:reload()importlib 库中。)

这样做并不安全:这显然是一个 hack,因为 sys.setdefaultencoding() 是故意从 sys Python 启动时。重新启用它并更改默认编码 can break code that relies on ASCII being the default (此代码可以是第三方的,这通常会使修复它变得不可能或很危险)。

PS:这个 hack 似乎不再适用于 Python 3.9。

关于python - 更改 Python 的默认编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2276200/

相关文章:

c# - 字符串返回字节数组 - 不工作

python - Unicode解码错误: ‘utf-8’ codec can’t decode byte 0xbe in position 2: invalid start byte

ios - 为什么用 %c 指定的 NSString 字符被改变了?

python - 如何将数据附加到 python 2.7.11 中的文本文件?

python - 在 Python3 的 Matplotlib 的极坐标/径向条形图中获取条形图顶部的标签

java - 列出文件时出现中文编码问题

php - PHP编码问题(UTF-8)

python - 在 Python 中继承方法的文档字符串

python - 打开名称文件

Python 编解码器行结尾