xia*_*012 16 python encoding default
可能重复:
更改python的默认编码?
我正在阅读python中的潜水,它提到在XML解析章节中设置python的默认编码方案.
该setdefaultencoding在使用 python的安装-DIR /站点包/ pyanaconda/sitecustomize.py
import sys
sys.setdefaultencoding('utf-8')
Run Code Online (Sandbox Code Playgroud)
但是当我运行脚本时,它会引发:
AttributeError: 'module' object has no attribute 'setdefaultencoding'
Run Code Online (Sandbox Code Playgroud)
无论如何,如何设置默认编码?
我正在使用python 2.7
解决方案: 在python安装中找到site.py.
编辑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)
Run Code Online (Sandbox Code Playgroud)
我正在使用python 2.7
Python的sys模块setdefaultencoding从Python 2.0 开始就有了一个函数.然而,
此功能仅供站点模块实现使用,并在需要时由sitecustomize使用.一旦由站点模块使用,它将从sys模块的命名空间中删除.
回到Python 2.1的文档表明这种情况发生了,因此PyAnaconda永远不适合使用这种方法,而且我不确定它为什么会起作用.
无论如何,如何设置默认编码?
sys.setdefaultencoding在sitecustomize.pyPython启动时运行文件,该文件需要在sys.path(例如lib/site-packages)中.您可以使用验证更改sys.getdefaultencoding.
编辑匿名downvoter:
无论谁低估了这个答案,你会解释一下吗?这个问题仅适用于Python 2.x. sys.setdefaultencoding如果这是你的问题,那么在Python 3中没有.如果想要在Python 2中使用,我会支持我对如何使用此函数的解释.我没有捍卫它的使用或推荐它的使用.库应该永远不会触及它,这就是sys在site.py和sitecustomize.py有机会调用它之后将其从命名空间中删除的原因.库也应该永远不要假设2.x中的默认编码是ASCII.这取决于系统.我个人将其保留为ASCII.
| 归档时间: |
|
| 查看次数: |
29139 次 |
| 最近记录: |