Converting WindowsError to OSError in python
<p>In the (legacy) code I maintain people are using <code>WindowsError</code>. I could go ahead and replace all occurrences with <code>OSError</code> but alas the <code>winerror</code> attribute is used, happily only in three cases - namely 123:</p>

<pre><code>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)
</code></pre>

<p>740:</p>

<pre><code>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)
</code></pre>

<p>and 32:</p>

<pre><code>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
</code></pre>

<p>How am I going to translate these codes to <code>OSError</code> ?</p>

<p>I am in python 2.7 so I can't use the nice exceptions introduced in <a href="https://www.python.org/dev/peps/pep-3151/#appendix-a-survey-of-common-errnos" rel="nofollow">pep-3151</a></p>

<p>Here is a <a href="http://www.gossamer-threads.com/lists/python/python/920347" rel="nofollow">discussion</a> on mapping winerror to the errno module</p>

<p>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:</p>

<pre><code>-            except WindowsError as werr:
-                if werr.winerror == 32:
+            except OSError as werr:
+                if werr.errno == errno.EACCES: # 13
</code></pre>

<p>For 123 (<a href="http://stackoverflow.com/q/21115580/281545">see also</a>):</p>

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

<p>so <code>errno.EINVAL</code>.</p>

<p>740 was in windows specific code so I left alone.</p>

python python-2.7 exception-handling cross-platform windowserror