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

查看:225
本文介绍了更改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),返回 setdefaultencoding已从 sys 中删除​​的code>函数:

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')

PS 这显然是一个黑客,因为 sys.setdefaultencoding()有意从 sys 中删除​​Python启动时。重新启用它并更改默认编码可能会中断代码它依赖于默认的ASCII(这个代码可以是第三方的,这通常会将其固定为不可能或危险的)。

PS: 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天全站免登陆