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 functionality for creating files, manipulating files and directories, and creating, managing, and destroying processes. This chapter covers the filesystem-related capabilities of the os module, while Chapter 14 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. Possible values for name are 'posix' (all kinds of Unix-like platforms), 'nt' (all kinds of 32-bit Windows platforms), 'mac', 'os2', and 'java'. You can often exploit unique capabilities of a platform, at least in part, through functions supplied by os. This book deals with cross-platform programming, however, 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 each given piece of functionality is provided on different platforms.
When a request to the operating system fails, os raises an exception, an instance of OSError. os also exposes class OSError with the name os.error. Instances of OSError expose three useful attributes:
The numeric error code of the operating system error
A string that summarily describes the error
The name of the file on which the operation failed (for file-related functions only)
os functions can also raise other standard exceptions, typically TypeError or ValueError, when the error is that they have been called with invalid argument types or values and the underlying operating system functionality has not even been attempted.
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 only "file not found" errors, while propagating others:
try: os.some_os_function_or_other( ) except OSError, err: import errno # check for "file not found" errors if err.errno != errno.ENOENT: raise # reraise other cases # 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, such as 'ENOENT'. Displaying errno.errorcode[err.errno], as part of your diagnosis of some os.error instance err, can often make diagnosis clearer and more understandable to readers who are specialists of the specific platform.