Mr_and_Mrs_D Mr_and_Mrs_D - 3 months ago 9
Python Question

Converting WindowsError to OSError in python

In the (legacy) code I maintain people are using

WindowsError
. I could go ahead and replace all occurrences with
OSError
but alas the
winerror
attribute is used, happily only in three cases - namely 123:

try:
mtime = int(os.path.getmtime(self._s))
except WindowsError, werr:
if werr.winerror != 123: raise
deprint(u'Unable to determine modified time of %s - probably a unicode error' % self._s)


740:

try:
popen = subprocess.Popen(args, close_fds=bolt.close_fds)
if wait: popen.wait()
except UnicodeError:
self._showUnicodeError()
except WindowsError as werr:
if werr.winerror != 740:
self.ShowError(werr)


and 32:

try:
patchName.untemp() # calls shutil.move() and os.remove()
except WindowsError, werr:
while werr.winerror == 32 and self._retry(patchName.temp.s,
patchName.s):
try:
patchName.untemp()
except WindowsError, werr:
continue
break
else:
raise


How am I going to translate these codes to
OSError
?

I am in python 2.7 so I can't use the nice exceptions introduced in pep-3151

Here is a discussion on mapping winerror to the errno module

Answer

Turns out winerror and the errno attribute have different values - in good code practices I did not use the magic number but the constants from the errno module. So 32:

-            except WindowsError as werr:
-                if werr.winerror == 32:
+            except OSError as werr:
+                if werr.errno == errno.EACCES: # 13

For 123 (see also):

with open('file', 'w'): pass
newFileName = 'illegal characters: /\\:*?"<>|'
try:
    os.rename('file', newFileName)
except OSError as e: # winerror = 123, errno = 22
    print e

so errno.EINVAL.

740 was in windows specific code so I left alone.