如何在Python中设置默认编码(setdefaultencoding()函数不存在)? [英] How to set default encoding in Python (setdefaultencoding() function does not exist)?

查看:1070
本文介绍了如何在Python中设置默认编码(setdefaultencoding()函数不存在)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

更改python的默认编码?

我正在阅读 dive in python ,它提到在XML解析章节中设置python的默认编码方案。

I am reading dive in python and it mentions setting python's default encoding scheme in the XML parsing chapter.

setdefaultencoding 用于 python-installed-dir / site-packages / pyanaconda / sitecustomize.py

import sys
sys.setdefaultencoding('utf-8')

但是当我运行脚本时,它会引发:

But when I run the script, it raises:

AttributeError: 'module' object has no attribute 'setdefaultencoding'

如何设置默认编码?无论如何?

How to set the default encoding,anyway?

我正在使用python 2.7

I am using python 2.7

解决方案: / strong>
在python安装中找到site.py。

Solution: find the site.py in the python installation.

编辑 setencoding 功能

def setencoding():
    encoding = "ascii" 
    if 0:
        import locale
        loc = locale.getdefaultlocale()
        if loc[1]:
            encoding = loc[1]
    if 0: #changes comes here, change 0 to 1
        encoding = "undefined" #the encoding you want
    if encoding != "ascii":
        sys.setdefaultencoding(encoding) 

我使用python 2.7

I am using python 2.7

推荐答案

Python的 sys 自Python以来,已经有一个 setdefaultencoding 函数2.0。但是,

Python's sys module has had a setdefaultencoding function since Python 2.0. However,


此功能仅用于由站点模块实现使用,并在必要时由sitecustomize使用。一旦被站点模块使用,它将从sys模块的命名空间中删除。

This function is only intended to be used by the site module implementation and, where needed, by sitecustomize. Once used by the site module, it is removed from the sys module’s namespace.

该文档至少回到Python 2.1,表示这种情况,所以PyAnaconda使用这种方法是不合适的,我不知道为什么它有效。

The docs back to at least Python 2.1 indicate this happens, so it was never appropriate for PyAnaconda to use this method, and I'm not sure why it ever worked.

这篇关于如何在Python中设置默认编码(setdefaultencoding()函数不存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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