问题描述
我正在阅读 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以来,已经有一个函数2.0。但是,
Python's sys
module has had a setdefaultencoding
function since Python 2.0. However,
该文档至少回到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()函数不存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!