How to get around Python "Problems with WindowsError set incorrectly"?

This is a problem when Python raised a WindowsError, the encoding of the exception message is always os-native-encoded. For instance:

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

Well, here we get the exception:

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

Since the language of my Windows7 is traditional Chinese, the default error message that I get is encoded in big5 (known as 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')
>>>

As you can see here, the error message is not Unicode, after which I will get another coding exception when I try to print it. This is the problem: it can be found in the Python list of issues: http://bugs.python.org/issue1754

The question is how to handle this? How to get your own WindowsError encoding? Python version I'm using 2.6.

Thank.

+3
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])
...

, - exc_info=True logging.error().

+3

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

This is only the repr () line of the same error message. Since your console already supports cp950, just print the component you need. This works on my system after reconfiguration to use cp950 in my console. I had to explicitly raise the error message, since my system is English, not Chinese:

>>> 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]
...
系統找不到指定的檔案。

Alternatively use Python 3.X. It prints repr () using console encoding. Here is an example:

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
source

Source: https://habr.com/ru/post/1741788/


All Articles