2012-11-18 84 views
3

可能重複後不工作:
How to display utf-8 in windows console蟒蛇 「打印」 sys.setdefaultencoding函數( 'UTF-8')

蟒蛇 「打印」 語句不起作用。

爲了避免這種錯誤,

'ASCII' 編解碼器在0位置無法解碼字節0xec:有序不在範圍內(128)

我把幾條語句在我的代碼如下

import sys 

reload(sys) 

sys.setdefaultencoding('utf-8') 

之前的代碼,「打印」效果很好。但是,在代碼之後,「打印」不起作用。

print "A" 

import sys 

reload(sys) 

sys.setdefaultencoding('utf-8') 

print "B" 

在這裏,只有「A」印在我的電腦上,Python2.7.3(64bit)for Windows。 Python2.7 IDLE

我需要幫助

+1

一旦「站點」模塊被導入,'sys.setdefaultencoding'就從'sys'中移除。這是記錄和完成的原因。你不能這樣使用'sys.defaultencoding'。看到鏈接的問題。 – BrenBarn

+0

其實,我通過使用Aptana Studio 3而不是使用IDLE解決了這個問題。這可能是因爲默認編碼設置彼此不同。 –

回答

4

sys.setdefaultencoding是有原因的site被刪除,你不應該使用reload(sys)恢復它。相反,我的解決方案是什麼都不做,Python會根據ENV LANG變量或Windows編碼自動檢測編碼。

$ python 
Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> import os 
>>> sys.stdout.encoding 
'UTF-8' 
>>> os.environ["LANG"] 
'pl_PL.UTF-8' 
>>> print u"\xabtest\xbb" 
«test» 
>>> 

但是,這可能會導致編碼時沒有你想要的字符的問題。您應該嘗試優雅地降級 - 顯示您想要的字符的機會接近於0(所以您應該嘗試使用純ASCII版本,或使用Unidecode顯示可用輸出(或者簡單地失敗))。您可以嘗試捕獲異常並打印基本版本的字符串。

$ LANG=C python 
Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> import os 
>>> sys.stdout.encoding 
'ANSI_X3.4-1968' 
>>> os.environ["LANG"] 
'C' 
>>> print u"\xabtest\xbb" 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xab' in position 0: ordinal not in range(128) 
>>> 

但是有問題叫Windows有Unicode支持的問題。雖然技術上chcp 65001應該可以工作,但除非您使用Python 3.3,否則它實際上不起作用。 Python使用便攜式stdio.h,但cmd.exe預計Windows特定的調用,如WriteConsoleW()。只有8位編碼才能可靠地工作(如CP437)。

解決方法是使用其他正確支持Unicode的終端,例如Cygwin的控制檯或Python中包含的IDLE。

+0

感謝您的信息 –