2010-04-19 116 views
3

當Python引發WindowsError時,這是一個麻煩,異常消息的編碼總是os-native-encoded。例如:如何解決Python「WindowsError消息編碼不正確」的問題?

import os 
os.remove('does_not_exist.file') 

好了,現在我們有一個例外:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
WindowsError: [Error 2] 系統找不到指定的檔案。: 'does_not_exist.file' 

由於我的Windows7的語言是中國傳統,默認的錯誤消息我得到的是用Big5編碼(如知道的CP950 )。

>>> try: 
...  os.remove('abc.file') 
... except WindowsError, value: 
...  print value.args 
... 
(2, '\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C') 
>>> 

正如你在這裏看到,錯誤消息不統一的話,我會得到另一種編碼異常,當我試圖把它打印出來。這是問題,它可以在Python問題列表中找到: http://bugs.python.org/issue1754

問題是,如何解決這個問題?如何獲得WindowsError的本機編碼? 我使用的Python版本是2.6。

謝謝。

+0

如果打印時發生異常,請顯示異常。打印它應該工作,看到我的答案在下面。 – 2010-04-20 06:37:12

回答

3

我們在俄羅斯版本的MS Windows的同樣的問題:默認的語言環境是cp1251的代碼頁,但在Windows控制檯的默認代碼頁是cp866

>>> import sys 
>>> print sys.stdout.encoding 
cp866 
>>> import locale 
>>> print locale.getdefaultlocale() 
('ru_RU', 'cp1251') 

該解決方案應該是解碼具有默認語言環境編碼的Windows消息:

>>> try: 
...  os.remove('abc.file') 
... except WindowsError, err: 
...  print err.args[1].decode(locale.getdefaultlocale()[1]) 
... 

壞消息是,你仍然CA不在logging.error()中使用exc_info=True

0

sys.getfilesystemencoding()應該有所幫助。

import os, sys 
try: 
    os.delete('nosuchfile.txt') 
except WindowsError, ex: 
    enc = sys.getfilesystemencoding() 
    print (u"%s: %s" % (ex.strerror, ex.filename.decode(enc))).encode(enc) 

對於其他的目的,而不是打印到控制檯,您可能希望最終編碼更改爲「utf-8」

0

這僅僅是同樣的錯誤消息的再版()的字符串。由於您的控制檯已經支持cp950,只需打印您想要的組件。這可以在我的系統上重新配置爲在我的控制檯中使用cp950。我有,因爲我的系統是英文,而不是中國明確地引發錯誤消息:

>>> try: 
...  raise WindowsError(2,'系統找不到指定的檔案。') 
... except WindowsError, value: 
...  print value.args 
... 
(2, '\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C') 
>>> try: 
...  raise WindowsError(2,'系統找不到指定的檔案。') 
... except WindowsError, value: 
...  print value.args[1] 
... 
系統找不到指定的檔案。 

另外,使用Python 3.x的它使用控制檯編碼打印repr()。這裏有一個例子:

Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> '系統找不到指定的檔案。' 
'\xa8t\xb2\xce\xa7\xe4\xa4\xa3\xa8\xec\xab\xfc\xa9w\xaa\xba\xc0\xc9\xae\xd7\xa1C' 

Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> '系統找不到指定的檔案。' 
'系統找不到指定的檔案。' 
+0

實際上,當我試圖將錯誤消息寫入記錄器時,我遇到了異常,這就是爲什麼我必須處理這個問題。記錄器的處理程序可能是文件,控制檯甚至SMTP。此外,控制檯可能與Windows OS的編碼不同,例如,運行程序IDLE或Pydev,似乎編碼是utf8而不是CP950,只有在使用Windows的CMD運行程序時,它纔是區域設置編碼。 – 2010-04-22 09:19:26