2011-01-29 14 views
3

鑑於從Python解釋器下面的代碼運行:Python中的Unicode工作在2.6.1上OSX,而​​不是在2.6.5在Ubuntu

import sys 
sys.getdefaultencoding() 
my_string = '\xc3\xa9' 
my_string = unicode(my_string, 'utf-8') 
my_string 
print my_string 

使用Python 2.6.1在Mac上,一切正常運行精細:

$ python 
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) 
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> sys.getdefaultencoding() 
'ascii' 
>>> my_string = '\xc3\xa9' 
>>> my_string = unicode(my_string, 'utf-8') 
>>> my_string 
u'\xe9' 
>>> print my_string 
é 
>>> 

使用Python 2.6.5在Ubuntu 10.04 LTS運行,它失敗:

$ python 
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> sys.getdefaultencoding() 
'ascii' 
>>> my_string = '\xc3\xa9' 
>>> my_string = unicode(my_string, 'utf-8') 
>>> my_string 
u'\xe9' 
>>> print my_string 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) 
>>> 

有事PY之間變化thon 2.6.1和2.6.5需要不同的unicode字符串處理?或者這是否與我的(默認Ubuntu服務器10.04 LTS)Linux環境中配置錯誤有關?

編輯:兩種環境有LANG =的en_US.UTF-8

+0

有趣的故事,雖然問題是關於`Python Unicorn` – 2011-01-29 02:44:41

+0

你在Ubuntu下使用什麼終端模擬器? – unutbu 2011-01-29 03:58:34

+0

我不確定。我在我的Mac中從終端使用ssh。服務器是無人的,運行在Rackspace上,我用最少的東西安裝它(基本上是apache和pylons)。 – Karl 2011-01-29 16:28:31

回答

3

我可以重現該錯誤與命令:

$ PYTHONIOENCODING=ascii python -c'print "\xc3\xa9".decode("utf-8")' 
Traceback (most recent call last): 
    File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0:\ 
ordinal not in range(128) 

sys.getdefaultencoding()'ascii',而不是非常默認情況下有用。

嘗試使用控制檯編碼:

$ PYTHONIOENCODING=utf-8 python -c'print "\xc3\xa9".decode("utf-8")' 
é 

$ python -c'import locale; print "\xc3\xa9".decode("utf-8").encode(
> locale.getpreferredencoding())' 
é 

檢查sys.stdout.encoding

$ python -c'import sys; o = sys.stdout; print o.isatty(), o.encoding' 
True UTF-8 

$ python -c'import sys; o = sys.stdout; print o.isatty(), o.encoding' | cat 
False None 

$ python -c'import sys; o = sys.stdout; print o.isatty(), o.encoding' >/tmp/out 
$ cat /tmp/out 
False None 

如果sys.stdout.encodingNone嘗試使用locale.getpreferredencoding()或如上圖所示設置PYTHONIOENCODING。請參閱http://wiki.python.org/moin/PrintFails

如果錯誤僅在交互式Python會話中出現,請查看sys.displayhook()

4

它可以與C語言環境發生。嘗試使用LANG=en_US.UTF-8 python運行Python並再次嘗試您的代碼。

+2

+1,另外,一個非unicode語言環境只能通過真正特殊的情況而被免除。 – 9000 2011-01-29 02:19:39

0

你有沒有嘗試在你的字符串前加u?

my_string = U '\ XC3版權所有\ xA9'

參見http://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code

在Python源代碼,的Unicode 文字寫爲與所述 'U' 或'前綴字符串 U' character:u'abcdefghijk'。具體的 代碼點可以使用 \ u轉義序列寫入,後面跟着 四個十六進制數字,代碼爲 點。 \ u轉義序列是 相似,但預計8個十六進制數字,不 4.

相關問題