的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。
一旦「站點」模塊被導入,'sys.setdefaultencoding'就從'sys'中移除。這是記錄和完成的原因。你不能這樣使用'sys.defaultencoding'。看到鏈接的問題。 – BrenBarn
其實,我通過使用Aptana Studio 3而不是使用IDLE解決了這個問題。這可能是因爲默認編碼設置彼此不同。 –