Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cross-platform way of getting information from Python's OSError?

On a simple directory creation operation for example, I can make an OSError like this:

(Ubuntu Linux)

>>> import os >>> os.mkdir('foo') >>> os.mkdir('foo') Traceback (most recent call last):   File "<stdin>", line 1, in <module> OSError: [Errno 17] File exists: 'foo' 

Now I can catch that error like this:

>>> import os >>> os.mkdir('foo') >>> try: ...     os.mkdir('foo') ... except OSError, e: ...     print e.args ...  (17, 'File exists') 

Is there a cross-platform way that I can know that that the 17 or the 'File Exists' will always mean the same thing so that I can act differently depending on the situation?

(This came up during another question.)

like image 906
Ali Afshar Avatar asked Nov 07 '08 21:11

Ali Afshar


People also ask

Is Python OS cross platform?

Python is a cross-platform language: a Python program written on a Macintosh computer will run on a Linux system and vice versa. Python programs can run on a Windows computer, as long as the Windows machine has the Python interpreter installed (most other operating systems come with Python pre-installed).

What is an OSError in Python?

The os. error in Python is the error class for all I/O errors and is an alias of the OSError exception. All the methods present in the OS module will raise the os. error exception when an inaccessible or invalid file path is specified.


1 Answers

The errno attribute on the error should be the same on all platforms. You will get WindowsError exceptions on Windows, but since this is a subclass of OSError the same "except OSError:" block will catch it. Windows does have its own error codes, and these are accessible as .winerror, but the .errno attribute should still be present, and usable in a cross-platform way.

Symbolic names for the various error codes can be found in the errno module. For example,

import os, errno try:     os.mkdir('test') except OSError, e:     if e.errno == errno.EEXIST:         # Do something 

You can also perform the reverse lookup (to find out what code you should be using) with errno.errorcode. That is:

>>> errno.errorcode[17] 'EEXIST' 
like image 193
Brian Avatar answered Sep 20 '22 18:09

Brian