问题描述
可能的重复:
更改python的默认编码?
我正在阅读深入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
The setdefaultencoding is used in 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'
如何设置默认编码?
我使用的是 python 2.7
I am using python 2.7
解决方案:在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
模块有一个 setdefaultencoding
函数自 Python 2.0 起.然而,
Python's sys
module has had a setdefaultencoding
function since Python 2.0. However,
此功能仅供站点模块实现使用,并在需要时供站点自定义使用.一旦被 site 模块使用,它就会从 sys 模块的命名空间中删除.
至少回到 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() 函数不存在)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!