python默认编码设置

时间:2023-03-09 03:27:58
python默认编码设置
打开python 的gui,输入
1
2
import sys
sys.getdefaultencoding()

查询系统当前默认编码

默认情况下显示编码方式为ASCII

在python安装目录下的Lib/site-packages文件夹下新建sitecustomize.py,内容为

1
2
3
4
5
# -*- coding: UTF-8 -*-
import sys  
reload(sys)  
sys.setdefaultencoding('utf8')

重启python,再次检查编码方式,发现已经改为utf8

sitecustomize.py is a special script; Python will try to import it on startup, so any code in it will be run automatically. As the comment mentions, it can go anywhere (as long as import can find it), but it usually goes in the site-packages directory within your Python lib directory.

setdefaultencoding function sets, well, the default encoding. This is the encoding scheme that Python will try to use whenever it needs to auto-coerce a unicode string into a regular string.

参考:

  1. https://docs.python.org/2/library/site.html

  2. http://www.cnblogs.com/dkblog/archive/2011/09/01/2161969.html

  3. http://blog.chinaunix.net/uid-22183602-id-2973101.html