zoukankan      html  css  js  c++  java
  • python default encoding

    http://www.cnblogs.com/harrychinese/archive/2012/01/19/change_python_default_encoding.html


    今天碰到了 python 编码问题, 报错信息如下
    Traceback (most recent call last):
      File "ntpath.pyc", line 108, in join
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xa1 in position 36: ordinal not in range(128)

    显然是当前的编码为ascii, 无法解析0xa1(十进制为161, 超过上限128). 进入python console后, 发现默认编码确实是 ascii, 验证过程为:

    In [14]: import sys

    In [15]: sys.getdefaultencoding()
    Out[15]: 'ascii'

    In [16]: sys.setdefaultencoding("utf-8")
    ---------------------------------------------------------------------------
    AttributeError Traceback (most recent call last)
    C:\Users\Administrator\<ipython-input-16-0b4b562a5430> in <module>()
    ----> 1 sys.setdefaultencoding("utf-8")

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



    google 到一个 limodou 回复的帖子, http://www.linuxforum.net/forum/showflat.php?Cat=&Board=python&Number=580942&page=15&view=collapsed&sb=5&o=

    在python2.6中无法调用sys.setdefaultencoding()函数来修改默认编码,因为python在启动的时候会调用site.py文件,在这个文件中设置完默认编码后会删除sys的setdefaultencoding方法。不能再被调用了.  在确定sys已经导入的情况下, 可以reload sys这个模块之后, 再 sys.setdefaultencoding('utf8')

    In [17]: reload(sys)
    <module 'sys' (built-in)>

    In [18]: sys.setdefaultencoding("utf-8")

    In [19]: sys.getdefaultencoding()
    'utf-8'



    确实有效, 根据 limodou 讲解,  site.py 是 python 解释器启动后, 默认加载的一个脚本. 如果使用 python -S 启动的话, 将不会自动加载 site.py. 

    上面写的挺啰嗦的. 

    ==================================
    如何永久地将默认编码设置为utf-8呢?  有2种方法: 
    ==================================
    第一个方法<不推荐>: 编辑site.py, 修改setencoding()函数, 强制设置为 utf-8 
    第二个方法<推荐>: 增加一个名为 sitecustomize.py, 推荐存放的路径为 site-packages 目录下
    sitecustomize.py 是在 site.py 被import 执行的, 因为 sys.setdefaultencoding() 是在 site.py 的最后删除的, 所以, 可以在 sitecustomize.py 使用 sys.setdefaultencoding(). 

    #file name:  sitecustomize.py
    import sys  
    sys.setdefaultencoding('utf-8') 
    

      

    既然 sitecustomize.py 能被自动加载,  所以除了设置编码外, 也可以设置一些其他的东西

  • 相关阅读:
    构建之法第十三~十七章阅读
    构建之法第十,十一,十二章阅读
    构建之法第八,九,十章阅读
    Sprint会议计划
    作业6
    作业5 四则运算 测试与封装 5.2
    作业5 四则运算 测试与封装 5.1
    构建之法2
    做汉堡
    构建之法阅读
  • 原文地址:https://www.cnblogs.com/samlee/p/2406510.html
Copyright © 2011-2022 走看看