python 学习笔记:python 解释器所使用的两个 hook

先引用下原文:

2.2.5. 本地化模块

Python 提供了两个钩子 (方法) 来本地化: sitecustomize 和 usercustomize。为了见识它们,你首先需要找到你的 site-packages 的目录。启动 python 执行下面的代码:

1
2
3
>>>import site 
>>>site.getusersitepackages()
'/home/user/.local/lib/python2.7/site-packages'
  • 现在你可以在 site-packages 的目录下创建 usercustomize.py 文件,内容就悉听尊便了。这个文件将会影响 python 的每次调用,除非启动的时候加入 -s 选项禁止自动导入。*

sitecustomize 的工作方式一样,但是是由电脑的管理账户创建以及在 usercustomize 之前导入。具体可以参见 site 。

这里涉及到两个 hook 文件

一个是 sitecustomize.py,这个是全局定义的 hook,对所有用户都适用的 hook 方案

他的位置一般在 python 的安装目录下,如 / etc/python2.7/

另一个是 usercustomize.py,这个是用户自己定义的 hook,只对当前用户生效

他的位置被放在了用户目录下,如 / home/monolight/.local/lib/python2.7/site-packages/

使用实例:python 的 sitecustomize.py 妙用

在 zope 实例所采用的 python 的路径中,找到 site-packages 目录,在此目录中建立一个 sitecustomize.py 文件,设置相应的权限。文件的内容如下:

1
2
import sys
sys.setdefaultencoding("utf-8")

重启 zope 实例,这样将解决很多 unicodedecodeerror 错误。

1
2
3
4
#for python2.7 on ubuntu
/etc/python2.7/sitecustomize.py
#for python2.6 on centOS
/usr/local/lib/python2.6/site-packages/sitecustomize.py
1
2
3
4
5
6
7
8
http://www.grabner-online.de/div_into/html/ch09s04s03.html
# sitecustomize.py
# this file can be anywhere in your Python path,
# but it usually goes in ${pythondir}/lib/site-packages/
import sys
sys.setdefaultencoding('iso-8859-1')
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.