天天看点

Python设置编码和PYTHONPATH

Python中的编码是个恼人的问题,第一个是文件编码,在第一行设置了#-*- coding: utf-8 -*-就可以解决。

第二个是环境编码,就是你有个中文unicode的encode或decode操作,它给你报错。

我们最不喜欢看见这段出错信息了:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
      

加入这段代码在项目入口文件开头,可以解决这个问题。

import sys
try:
    reload(sys)
    sys.setdefaultencoding("utf-8")
except AttributeError:
    pass  #没起作用
      

或者将这段代码放在项目根目录下的sitecustomize.py文件中。

问题是python2.5之后的版本,有时不在项目开头自动加载这个文件。纠结啊,自己定义的方式自己有时不支持。

只好在入口文件加一段,确保执行sitecustomize.py

# -*- coding: utf-8 -*-

#解决Python2.5之后有时无法载入sitecustomize.py的问题
import sys
import os
sys.path = [os.getcwd()] + sys.path
import sitecustomize
reload(sitecustomize)
      

另外关于python的搜索路径PYTHONPATH,可以用以下方式增加一个路径到其中,比如项目根目录下的library

# -*- coding: utf-8 -*-

import os.path
import sys
import site

try:
    reload(sys)
    sys.setdefaultencoding("utf-8")
except AttributeError:
    pass

base_dir = os.path.dirname(os.path.abspath(__file__))
prev_sys_path = list(sys.path)

# site.addsitedir adds this directory to sys.path then scans for .pth files
# and adds them to the path too.
site.addsitedir(os.path.join(base_dir, 'library'))

# addsitedir adds its directories at the end, but we want our local stuff
# to take precedence over system-installed packages.
# See http://code.google.com/p/modwsgi/issues/detail?id=112
new_sys_path = []
for item in list(sys.path):
  if item not in prev_sys_path:
    new_sys_path.append(item)
    sys.path.remove(item)
sys.path[:0] = new_sys_path