Python設定編碼和PYTHONPATH

阿債發表於2012-05-15

 

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


相關文章