今天更新mercurial的時候遇到了一個問題。
執行hg,結果報錯:LookupError: unknown encoding: x-mac-simp-chinese
想到這個問題我之前在用django的時候碰到過,原來覺得是django的問題,如今才知道原來是廣泛的python的問題。
去hg的源代碼裏面minirst.py裏面看了一下,發現是直接調用mercurial的encoding函數的encoding這個變量。
找到encoding.py裏面,
try:
encoding = os.environ.get("HGENCODING")
if not encoding:
encoding = locale.getpreferredencoding() or 'ascii'
encoding = _encodingfixers.get(encoding, lambda: encoding)()
except locale.Error:
encoding = 'ascii'
原來是locale這個模塊搞的鬼。。
去locale.py裏面看了一下,發現如下代碼:
if sys.platform in ('win32', 'darwin', 'mac'):
# On Win32, this will return the ANSI code page
# On the Mac, it should return the system encoding;
# it might return "ascii" instead
def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using."""
import _locale
return _locale._getdefaultlocale()[1]
嘗試執行了一下,直接返回了’x-mac-simp-chinese’
爲了瞭解正確的結果,python2.6 -c ‘import locale; print(locale.getpreferredencoding());’返回結果’UTF-8′.
而UTF-8正是我設置的LC_ALL和LANG的結果。
看來是這個_locale模塊搞得鬼。不過_locale啊。看名字就是c寫的。爲了省力。直接把
if sys.platform in ('win32', 'darwin', 'mac'):
改爲了
if sys.platform in ('win32'):
而後順手搜索了一下locale.py中的_locale,把全部的都改了。
執行hg,一切正常。
順帶搜了一下這個問題python的buglist裏面有沒有,果真看到了。http://bugs.python.org/issue1276。不過略看了一下,發現python2.5.x被無情的忽略了。看來只能本身hack了。:)。