2010-04-19 110 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