10.7. The os Module
The os module is an umbrella module that presents a reasonably uniform cross-platform view of the different capabilities of various operating systems. The module provides ways to create and handle files and directories, and to create, manage, and destroy processes. This section covers the filesystem-related capabilities of the os module; "Running Other Programs with the os Module" on page 354 covers the process-related capabilities.
The os module supplies a name attribute, which is a string that identifies the kind of platform on which Python is being run. Common values for name are 'posix' (all kinds of Unix-like platforms, including Mac OS X), 'nt' (all kinds of 32-bit Windows platforms), 'mac' (old Mac systems), and 'java' (Jython). You can often exploit unique capabilities of a platform, at least in part, through functions supplied by os. However, this book deals with cross-platform programming, not with platform-specific functionality, so I do not cover parts of os that exist only on one kind of platform, nor do I cover platform-specific modules. All functionality covered in this book is available at least on both 'posix' and 'nt' platforms. However, I do cover any differences among the ways in which a given functionality is provided on different platforms.
10.7.1. OSError Exceptions
When a request to the operating system fails, os raises an exception, which is an instance of OSError. os also exposes built-in exception class OSError with the name os.error. Instances of OSError expose three useful attributes:
os functions can also raise other standard exceptions, typically TypeError or ValueError, when the cause of the error is that you have called them with invalid argument types or values so that the underlying operating system functionality has not even been attempted.
10.7.2. The errno Module
The errno module supplies symbolic names for error code numbers. To handle possible system errors selectively, based on error codes, use errno to enhance your program's portability and readability. For example, here's how you might handle "file not found" errors, while propagating all other kinds of errors:
try: os.some_os_function_or_other( ) except OSError, err: import errno # check for "file not found" errors, re-raise other cases if err.errno != errno.ENOENT: raise # proceed with the specific case you can handle print "Warning: file", err.filename, "not found -- continuing"
errno also supplies a dictionary named errorcode: the keys are error code numbers, and the corresponding names are the error names, which are strings such as 'ENOENT'. Displaying errno.errorcode[err.errno], as part of your diagnosis of some os.error instance err, can often make the diagnosis clearer and more understandable to readers who specialize in the specific platform.