更改 Python 的默认编码? [英] Changing default encoding of Python?

查看:32
本文介绍了更改 Python 的默认编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have many "can't encode" and "can't decode" problems with Python when I run my applications from the console. But in the Eclipse PyDev IDE, the default character encoding is set to UTF-8, and I'm fine.

我找了一圈设置默认编码,有人说Python在启动时删除了sys.setdefaultencoding函数,我们不能使用.

I searched around for setting the default encoding, and people say that Python deletes the sys.setdefaultencoding function on startup, and we can not use it.

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

So what's the best solution for it?

推荐答案

这里有一个更简单的方法 (hack),它可以让您恢复从 sys<中删除的 setdefaultencoding() 函数/代码>:

Here is a simpler method (hack) that gives you back the setdefaultencoding() function that was deleted from sys:

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

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

(Note for Python 3.4+: reload() is in the importlib library.)

这不是一件安全的事情,但是:这显然是一种黑客行为,因为 sys.setdefaultencoding() 是故意从 sys 中删除的代码> Python 启动时.重新启用它并更改默认编码 可以破解代码依赖于 ASCII 作为默认值(此代码可以是第三方的,这通常会使修复它变得不可能或危险).

This is not a safe thing to do, though: this is obviously a hack, since sys.setdefaultencoding() is purposely removed from sys when Python starts. Reenabling it and changing the default encoding can break code that relies on ASCII being the default (this code can be third-party, which would generally make fixing it impossible or dangerous).

这篇关于更改 Python 的默认编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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