Linux/Unix > Python Essential Reference, Second Edition > A. The Python Library > Operating System Services | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105080005017050165152143

### Operating System Services

The modules in this section provide access to a wide variety of operating system services with an emphasis on file, process, and terminal management.

Note: A general familiarity with basic operating system concepts is assumed in this section. Furthermore, a number of modules provide advanced functionality which is beyond the scope of this book to introduce, but which is presented for readers who know what they’re doing.

Most of Python’s operating system modules are based on POSIX interfaces. POSIX is a standard that defines a core set of operating system interfaces. Most UNIX systems support POSIX, and other platforms such as Windows and Macintosh support large portions of the interface.

Readers may want to supplement the material presented here with additional references. The C Programming Language, Second Edition by Brian W. Kernighan and Dennis M. Ritchie (Prentice Hall, 1989, ISBN 0-13-110362-8) provides a good overview of files, file descriptors, and the low-level interfaces on which many of the modules in this section are based. More advanced readers may want to consult a book such as W. Richard Stevens’ Advanced Programming in the UNIX Environment (Addison-Wesley, 1992, ISBN 0-201-56317-7). Background material regarding operating system concepts can be found in a text such as Operating Systems Concepts, 5th Edition by Abraham Silberschatz and Peter Baer Galvin (John Wiley & Sons, 1998). Threads and network programming are presented in separate sections of this appendix.

#### `commands`

The `commands` module is used to execute system commands as a string and return their output as a string.

    getoutput(cmd)

Executes `cmd` in a shell and returns a string containing both the standard output and standard error streams of the command.

    getstatus(filename)

Returns the output of `'ls -ld` `filename` `'` as a string. UNIX.

    getstatusoutput(cmd)

Like `getoutput()` except that a 2-tuple (`status` `,` `output` ) is returned, where `status` is the exit code as returned by the `os.wait()` function and `output` is the string returned by `getoutput()`.

    mkarg(str)

Turns `str` into an argument that can be safely used within a command string (using quoting rules of the shell).

##### Notes

- The `os.popen2()` call is used to execute commands. This module is available on most UNIX systems, but is not supported on all versions of Windows.

- The returned output strings don’t include a trailing newline.

? See Also os (180), popen2 (195).

#### `crypt`

The `crypt` module provides an interface to the UNIX `crypt()` routine that’s used to encrypt passwords on many UNIX systems.

    crypt(word, salt)

Encrypts `word` using a modified DES algorithm. `salt` is a two-character seed used to initialize the algorithm. Returns the encrypted word as a string. Only the first eight characters of `word` are significant.

##### Example

The following code reads a password from the user and compares it against the value in the system password database:

    import getpass
    import pwd
    import crypt
    uname  = getpass.getuser()            # Get username from environment
    pw     = getpass.getpass()            # Get entered password
    realpw = pwd.getpwnam(uname)[1]       # Get real password
    entrpw = crypt.crypt(pw,realpw[:2])   # Encrypt
    if realpw == entrpw:                  # Compare
           print 'Password Accepted'
    else:
           print 'Get lost.'

##### Note

- Many modern UNIX systems use MD5 or other crytographic hashing algorithms to store passwords.

? See Also pwd (196), getpass (167).

#### `errno`

The `errno` module defines symbolic names for the integer error codes returned by various operating system calls. These codes are typically found in the `errno` attribute of an `OSError` or `IOError` exception. The `os.strerror()` function can be used to translate an error code into a string error message. The following dictionary can also be used to translate an integer error code into its symbolic name:

    errorcode

Dictionary mapping `errno` integers to symbolic names (such as `'EPERM'`).

The following list shows the POSIX symbolic names for many system error codes. Not all names are available on all machines. Some platforms may define additional codes. The codes U,W, M, and A are used to indicate availability of the following codes for UNIX,Windows, Macintosh, and all platforms, respectively.

Error Code | Platform | Description
--- | --- | ---
`E2BIG` | A | Arg list too long.
`EACCES` | A | Permission denied.
`EADDRINUSE` | A | Address already in use.
`EADDRNOTAVAIL` | A | Cannot assign requested address.
`EADV` | U | Advertise error.
`EAFNOSUPPORT` | A | Address family not supported by protocol.
`EAGAIN` | A | Try again.
`EALREADY` | A | Operation already in progress.
`EBADE` | U | Invalid exchange.
`EBADF` | A | Bad file number.
`EBADFD` | U | File descriptor in bad state.
`EBADMSG` | U | Not a data message.
`EBADR` | U | Invalid request descriptor.
`EBADRQC` | U | Invalid request code.
`EBADSLT` | U | Invalid slot.
`EBFONT` | U | Bad font file format.
`EBUSY` | A | Device or resource busy.
`ECHILD` | A | No child processes.
`ECHRNG` | U | Channel number out of range.
`ECOMM` | U | Communication error on send.
`ECONNABORTED` | A | Software caused connection abort.
`ECONNREFUSED` | A | Connection refused.
`ECONNRESET` | A | Connection reset by peer.
`EDEADLK` | A | Resource deadlock would occur.
`EDEADLOCK` | U,W | File-locking deadlock error.
`EDESTADDRREQ` | A | Destination address required.
`EDOM` | A | Math argument out of domain of func.
`EDOTDOT` | U | RFS-specific error.
`EDQUOT` | A | Quota exceeded.
`EEXIST` | A | File exists.
`EFAULT` | A | Bad address.
`EFBIG` | A | File too large.
`EHOSTDOWN` | A | Host is down.
`EHOSTUNREACH` | A | No route to host.
`EIDRM` | U | Identifier removed.
`EILSEQ` | U,W | Illegal byte sequence.
`EINPROGRESS` | U,W | Operation now in progress.
`EINTR` | A | Interrupted system call.
`EINVAL` | A | Invalid argument.
`EIO` | A | I/O error.
`EISCONN` | A | Transport endpoint is already connected.
`EISDIR` | A | Is a directory.
`EISNAM` | U | Is a named type file.
`EL2HLT` | U | Level 2 halted.
`EL2NSYNC` | U | Level 2 not synchronized.
`EL3HLT` | U | Level 3 halted.
`EL3RST` | U | Level 3 reset.
`ELIBACC` | U | Cannot access a needed shared library.
`ELIBBAD` | U | Accessing a corrupted shared library.
`ELIBEXEC` | U | Cannot `exec` a shared library directly.
`ELIBMAX` | U | Attempting to link in too many shared libraries.
`ELIBSCN` | U | `.lib` section in `a.out` corrupted.
`ELNRNG` | U | Link number out of range.
`ELOOP` | A | Too many symbolic links encountered.
`EMFILE` | A | Too many open files.
`EMLINK` | U,W | Too many links.
`EMSGSIZE` | U,W | Message too long.
`EMULTIHOP` | U | Multihop attempted.
`ENAMETOOLONG` | U | Filename too long.
`ENAVAIL` | U | No XENIX semaphores available.
`ENETDOWN` | U,W | Network is down.
`ENETRESET` | U,W | Network dropped connection because of reset.
`ENETUNREACH` | U,W | Network is unreachable.
`ENFILE` | U,W | File table overflow.
`ENOANO` | U | No anode.
`ENOBUFS` | A | No buffer space available.
`ENOCSI` | U | No CSI structure available.
`ENODATA` | U | No data available.
`ENODEV` | A | No such device.
`ENOENT` | A | No such file or directory.
`ENOEXEC` | A | `exec` format error.
`ENOLCK` | A | No record locks available.
`ENOLINK` | U | Link has been severed.
`ENOMEM` | A | Out of memory.
`ENOMSG` | U | No message of desired type.
`ENONET` | U | Machine is not on the network.
`ENOPKG` | U | Package not installed.
`ENOPROTOOPT` | A | Protocol not available.
`ENOSPC` | A | No space left on device.
`ENOSR` | U | Out of streams resources.
`ENOSTR` | U | Device not a stream.
`ENOSYS` | A | Function not implemented.
`ENOTBLK` | U, M | Block device required.
`ENOTCONN` | A | Transport endpoint is not connected.
`ENOTDIR` | A | Not a directory.
`ENOTEMPTY` | A | Directory not empty.
`ENOTNAM` | U | Not a XENIX named type file.
`ENOTSOCK` | A | Socket operation on non-socket.
`ENOTTY` | A | Not a terminal.
`ENOTUNIQ` | U | Name not unique on network.
`ENXIO` | A | No such device or address.
`EOPNOTSUPP` | A | Operation not supported on transport endpoint.
`EOVERFLOW` | U | Value too large for defined data type.
`EPERM` | A | Operation not permitted.
`EPFNOSUPPORT` | A | Protocol family not supported.
`EPIPE` | A | Broken pipe.
`EPROTO` | U | Protocol error.
`EPROTONOSUPPORT` | A | Protocol not supported.
`EPROTOTYPE` | A | Protocol wrong type for socket.
`ERANGE` | A | Math result not representable.
`EREMCHG` | U | Remote address changed.
`EREMOTE` | A | Object is remote.
`EREMOTEIO` | U | Remote I/O error.
`ERESTART` | U | Interrupted system call should be restarted.
`EROFS` | A | Read-only filesystem.
`ESHUTDOWN` | A | Cannot send after transport endpoint shutdown.
`ESOCKTNOSUPPORT` | A | Socket type not supported.
`ESPIPE` | A | Illegal seek.
`ESRCH` | A | No such process.
`ESRMNT` | U | srmount error.
`ESTALE` | A | Stale NFS file handle.
`ESTRPIPE` | U | Streams pipe error.
`ETIME` | U | Timer expired.
`ETIMEDOUT` | A | Connection timed out.
`ETOOMANYREFS` | A | Too many references: Cannot splice.
`ETXTBSY` | U, M | Text file busy.
`EUCLEAN` | U | Structure needs cleaning.
`EUNATCH` | U | Protocol driver not attached.
`EUSERS` | A | Too many users.
`EWOULDBLOCK` | A | Operation would block.
`EXDEV` | A | Cross-device link.
`EXFULL` | U | Exchange full.
`WSAEACCES` | W | Permission denied.
`WSAEADDRINUSE` | W | Address already in use.
`WSAEADDRNOTAVAIL` | W | Cannot assign requested address.
`WSAEAFNOSUPPORT` | W | Address family not supported by protocol family.
`WSAEALREADY` | W | Operation already in progress.
`WSAEBADF` | W | Invalid file handle.
`WSAECONNABORTED` | W | Software caused connection abort.
`WSAECONNREFUSED` | W | Connection refused.
`WSAECONNRESET` | W | Connection reset by peer.
`WSAEDESTADDRREQ` | W | Destination address required.
`WSAEDISCON` | W | Remote shutdown.
`WSAEDQUOT` | W | Disk quota exceeded.
`WSAEFAULT` | W | Bad address.
`WSAEHOSTDOWN` | W | Host is down.
`WSAEHOSTUNREACH` | W | No route to host.
`WSAEINPROGRESS` | W | Operation now in progress.
`WSAEINTR` | W | Interrupted system call.
`WSAEINVAL` | W | Invalid argument.
`WSAEISCONN` | W | Socket already connected.
`WSAELOOP` | W | Cannot translate name.
`WSAEMFILE` | W | Too many open files.
`WSAEMSGSIZE` | W | Message too long.
`WSAENAMETOOLONG` | W | Name too long.
`WSAENETDOWN` | W | Network is down.
`WSAENETRESET` | W | Network dropped connection on reset.
`WSAENETUNREACH` | W | Network is unreachable.
`WSAENOBUFS` | W | No buffer space is available.
`WSAENOPROTOOPT` | W | Bad protocol option.
`WSAENOTCONN` | W | Socket is not connected.
`WSAENOTEMPTY` | W | Cannot remove non-empty directory.
`WSAENOTSOCK` | W | Socket operation on non-socket.
`WSAEOPNOTSUPP` | W | Operation not supported.
`WSAEPFNOSUPPORT` | W | Protocol family not supported.
`WSAEPROCLIM` | W | Too many processes.
`WSAEPROTONOSUPPORT` | W | Protocol not supported.
`WSAEPROTOTYPE` | W | Protocol wrong type for socket.
`WSAEREMOTE` | W | Item not available locally.
`WSAESHUTDOWN` | W | Cannot send after socket shutdown.
`WSAESOCKTNOSUPPORT` | W | Socket type not supported.
`WSAESTALE` | W | File handle no longer available.
`WSAETIMEDOUT` | W | Connection timed out.
`WSAETOOMANYREFS` | W | Too many references to a kernel object.
`WSAEUSERS` | W | Quota exceeded.
`WSAEWOULDBLOCK` | W | Resource temporaily unavailable.
`WSANOTINITIALISED` | W | Successful WSA Startup not performed.
`WSASYSNOTREADY` | W | Network subsystem not available.
`WSAVERNOTSUPPORTED` | W | `Winsock.dll` version out of range.

? See Also os (180).

#### `fcntl`

The `fcntl` module performs file and I/O control on UNIX file descriptors. File descriptors can be obtained using the `fileno()` method of a file or socket object. This module relies on a large number of constants defined in the `FCNTL` module (that should also be imported).

    fcntl(fd, cmd [, arg])

Performs command `cmd` on an open file descriptor `fd` . `cmd` is an integer command code. `arg` is an optional argument that’s either an integer or a string. If `arg` is passed as an integer, the return value of this function is an integer. If `arg` is a string, it’s interpreted as a binary data structure, and the return value of the call is the contents of the buffer converted back into a string object. The following commands are available (these constants are defined in the `FCNTL` module):

Command | Description
--- | ---
`F_DUPFD` | Duplicates a file descriptor. `arg` is the lowest number that the new file descriptor can assume. Similar to the `os.dup()` system call.
`F_SETFD` | Sets the `close-on-exec` flag to `arg` (`0` or `1`). If set, the file is closed on an `exec()` system call.
`F_GETFD` | Returns the `close-on-exec` flag.
`F_SETFL` | Sets status flags to `arg` , which is the bitwise-or of the following: `O_NDELAY`—Nonblocking I/O (System V). `O_APPEND`—Append mode (System V). `O_SYNC`—Synchronous write (System V). `FNDELAY`—Nonblocking I/O (BSD).

`FAPPEND`—Append mode (BSD).

`FASYNC`—Sends `SIGIO` signal to process group when I/O is possible (BSD).

`F_GETFL` | Gets status flags as set by `F_SETFL`.
`F_GETOWN` | Gets process ID or process group ID set to receive `SIGIO` and `SIGURG` signals (BSD).
`F_SETOWN` | Sets process ID or process group ID to receive `SIGIO` and `SIGURG` signals (BSD).
`F_GETLK` | Returns flock structure used in file locking operations.
`F_SETLK` | Locks a file, returning `-1` if the file is already locked.
`F_SETLKW` | Locks a file, but waits if the lock cannot be acquired.

An `IOError` exception is raised if the `fcntl()` function fails. The `F_GETLK` and `F_SETLK` commands are supported through the `lockf()` function.

    ioctl(fd, op, arg)

This function is like the `fcntl()` function, except that the operations are defined in the library module `IOCTL`. The `IOCTL` module may be unavailable on some platforms.

    flock(fd, op)

Performs a lock operation `op` on file descriptor `fd` . `op` is the bitwise-or of the following constants found in `fnctl`:

Item | Description
--- | ---
`LOCK_EX` | Exclusive lock.
`LOCK_NB` | Don’t lock when locking.
`LOCK_SH` | Shared lock.
`LOCK_UN` | Unlock.

In nonblocking mode, an `IOError` exception is raised if the lock cannot be acquired.

    lockf(fd, op [, len [, start [, whence]]])

Performs record or range locking on part of a file. `op` is the same as for the `flock()` function. `len` is the number of bytes to lock. `start` is the starting position of the lock relative to the value of `whence` . `whence` is `0` for the beginning of the file, `1` for the current position, and `2` for the end of the file.

##### Examples

    import fcntl, FCNTL

    # Set the close-on-exec bit for a file object f
    fcntl.fcntl(f.fileno(), FCNTL.F_SETFD, 1)

    # Lock a file (blocking)
    fcntl.flock(f.fileno(), fcntl.LOCK_EX)

    # Lock the first 8192 bytes of a file (nonblocking)
    try:
        fcntl.lockf(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB, 8192, 0, 0)
    except IOError,e:
        print "Unable to acquire lock", e

##### Notes

- The set of available `fcntl()` commands and options is system-dependent. The `FCNTL` module may contain well over 100 constants on some platforms.

- Many of the functions in this module can also be applied to the file descriptors of sockets.

? See Also os (180), socket (252).

#### `filecmp`

The `filecmp` module provides functions that can be used to compare files and directories.

    cmp(file1, file2 [, shallow[, use_statcache]])

Compares the files `file1` and `file2` and returns `1` if they’re equal, `0` if not. By default, files that have identical attributes as returned by `os.stat()` are considered to be equal. If the `shallow` parameter is specified and is false, the contents of the two files are compared to determine equality. In this case, subsequent comparisons between the same two files will return a cached result unless the `os.stat()` data for one of the files changes. If `use_statcache` is given, values of `os.stat()` are cached and used in subsequent comparisons. This latter option improves performance, but prevents the module from detecting changes to previously compared files.

    cmpfiles(dir1, dir2, common[, shallow[, use_statcache]])

Compares the contents of the files contained in the list `common` in the two directories `dir1` and `dir2` . Returns a tuple containing three lists of filenames `(``match` `,` `mismatch` `,``errors` `)`. `match` lists the files that are the same in both directories, `mismatch` lists the files that don’t match, and `errors` lists the files that could not be compared for some reason. The `shallow` and `use_statcache` parameters have the same meaning as for `cmp()`.

    dircmp(dir1, dir2 [, ignore[, hide]])

Creates a directory comparison object that can be used to perform various comparison operations on the directories `dir1` and `dir2` . `ignore` is a list of filenames to ignore and has a default value of `['RCS','CVS','tags']`. `hide` is a list of filenames to find and defaults to the list `[os.curdir, os.pardir]` (`['.', '..']` on UNIX).

A directory object `d` returned by `dircmp()` has the following methods and attributes:

    d.report()

Compares directories `dir1` and `dir2` and prints a report to `sys.stdout`.

    d.report_partial_closure()

Compares `dir1` and `dir2` and common immediate subdirectories.

    d.report_full_closure()

Compares `dir1` and `dir2` and all subdirectories recursively.

    d.left_list

Lists the files and subdirectories in `dir1` . The contents are filtered by `hide` and `ignore` .

    d.right_list

Lists the files and subdirectories in `dir2` . The contents are filtered by `hide` and `ignore` .

    d.common

Lists the files and subdirectories found in both `dir1` and `dir2` .

    d.left_only

Lists the files and subdirectories found only in `dir1` .

    d.right_only

Lists the files and subdirectories found only in `dir2` .

    d.common_dirs

Lists the subdirectories that are common to `dir1` and `dir2` .

    d.common_files

Lists the files that are common to `dir1` and `dir2` .

    d.common_funny

Lists the files in `dir1` and `dir2` with different types or for which no information can be obtained from `os.stat()`.

    d.same_files

Lists the files with identical contents in `dir1` and `dir2` .

    d.diff_files

Lists the files with different contents in `dir1` and `dir2` .

    d.funny_files

Lists the files that are in both `dir1` and `dir2` , but that could not be compared.

    d.subdirs

A dictionary that maps names in `d` `.common_dirs` to additional `dircmp` objects.

##### Note

- The attributes of a `dircmp` object are evaluated lazily and not determined at the time the `dircmp` object is first created.

#### `fileinput`

The `fileinput` module iterates over a list of input files and reads their contents line by line. The main interface to the module is the following function:

    input([files [, inplace [, backup]]])

Creates an instance of the `FileInput` class. `files` is an optional list of filenames to be read (a single filename is also permitted). If omitted, the filenames are read from the command line in `sys.argv[1:]`. An empty list implies input from `stdin`, as does a filename of `'-'`. If `inplace` is set to `1`, each input file is moved to a backup file and `sys.stdout` is redirected to overwrite the original input file. The backup file is then removed when the output is closed. The `backup` option specifies a filename extension such as `.bak` that is appended to each filename in order to create the names of backup files. When given, the backup files are not deleted. By default, `backup` is the empty string and no backup files are created.

All `FileInput` instances have the following methods. These methods are also available as functions that apply to the last instance created by the `input()` function.

Method | Description
--- | ---
`filename()` | Returns the name of the file currently being read
`lineno()` | Returns the cumulative line number just read
`filelineno()` | Returns the line number in the current file
`isfirstline()` | Returns true if the line just read was the first line of a file
`isstdin()` | Returns true if the input is `stdin`
`nextfile()` | Closes the current file and skips to the next file
`close()` | Closes the file sequence

In addition, the `FileInput` instance returned by `input()` can be used as an iterator for reading all input lines.

##### Example

The following code reads and prints all the input lines from a list of files supplied on the command line:

    import fileinput
    for line in fileinput.input():
         print '%5d %s' % (fileinput.lineno(), line),

##### Notes

- All files opened by this module are opened in text mode.

- An `IOError` is raised if a file cannot be opened.

- Empty files are opened and closed immediately.

- All lines returned include trailing newlines unless the last line of an input file doesn’t include a newline.

- MS-DOS/Windows short filenames (eight characters plus a three-letter suffix) are not supported.

? See Also glob (170), fnmatch (165).

#### `findertools`

The `findertools` module is used to access some of the functionality in the Macintosh Finder. All file and folder parameters can be specified either as full pathname strings or as `FSSpec` objects as created using the `macfs` module.

    launch(file)

Launches a file either by launching an application or by opening a document in the correct application.

    Print(file)

Prints a file.

    copy(file, destdir)

Copies `file` to the folder `destdir` .

    move(file, destdir)

Moves `file` to the folder `destdir` .

    sleep()

Puts the Macintosh to sleep (if supported).

    restart()

Restarts the machine.

    shutdown()

Shuts down the machine.

? See Also macfs (173), macostools (176).

#### `fnmatch`

The `fnmatch` module provides support for matching filenames using UNIX shell-style wildcard characters:

Character(s) | Description
--- | ---
`*` | Matches everything
`?` | Matches any single character
`[``seq` `]` | Matches any character in `seq`
`[!``seq` `]` | Matches any character not in `seq`

The following functions can be used to test for a wildcard match:

    fnmatch(filename, pattern)

Returns true or false depending on whether `filename` matches `pattern` . Case sensitivity depends on the operating system (certain platforms, such as Windows, are not case sensitive).

    fnmatchcase(filename, pattern)

Performs a case-sensitive comparison of `filename` against `pattern` .

##### Examples

    fnmatch('foo.gif', '*.gif')               # Returns true
    fnmatch('part37.html', 'part3[0-5].html') # Returns false

? See Also glob (170).

#### `getopt`

The `getopt` module is used to parse command-line options (typically passed in `sys.argv`).

    getopt(args, options [, long_options])

Parses the command-line options supplied in the list `args` . `options` is a string of letters corresponding to the single-letter options that a program wants to recognize (for example, `'-x'`). If an option requires an argument, the option letter must be followed by a colon. If supplied, `long_options` is a list of strings corresponding to long option names. When supplied in `args` , these options are always preceded by a double hyphen (`-`) such as in `'--exclude'` (the leading `-`is not supplied in `long_options` ). Long option names requiring an argument should be followed by an equal sign (`=`). The function returns a list of (`option` `,` `value` ) pairs matched and a list of program arguments supplied after all of the options. The options are placed in the list in the same order in which they were found. Long and short options can be mixed. Option names are returned with the leading hyphen () or double hyphen (`-`).

##### Exception

    error

Exception raised when an unrecognized option is found or when an option requiring an argument is given none. The exception argument is a string indicating the cause of the error.

##### Example

    >>> import getopt
    >>> args = ['-a', '-b', 'foo', '-cd', 'blah', '--exclude','bar', 'x1', 'x2']
    >>> opts, pargs = getopt.getopt(args, 'ab:cd:', ['exclude='])
    >>> opts
    [('-a', ''), ('-b', 'foo'), ('-c',''), ('-d,'blah'),('--exclude', 'bar')]
    >>> pargs
    ['x1', 'x2']
    >>>

##### Notes

- Only single-letter command-line options can be recognized with a single hyphen (). For example, `'-n 3'` is legal, but `'-name 3'` isn’t.

- More than one single-letter option can be combined, provided that all but the last option take no arguments. The `'-cd blah'` option in the example illustrates this behavior.

? See Also sys (116).

#### `getpass`

The `getpass` module provides support for reading passwords and usernames.

    getpass([prompt])

Prompts the user for a password without echoing. The default prompt is `'Password: '`. Returns the entered password as a string.

    getuser()

Returns the login name of the user by first checking the environment variables `$LOGNAME`, `$USER`, `$LNAME`, and `$USERNAME` and then checking the system password database. Raises a `KeyError` exception if no name can be found. UNIX and Windows.

##### Notes

- An example of `getpass` is shown in the documentation for the `crypt` module.

- On UNIX, the `getpass` module depends on the `termios` module, which is disabled by default on some systems.

? See Also pwd (196), crypt (155).

#### `gettext`

The `gettext` module provides an interface to the GNU `gettext` library, which is used to provide support for internationalization (i18n). The primary use of `gettext` is to provide translation of selected program text in a way that’s easy to extend and that’s mostly transparent to the programmer. For example, if you’re writing a program that prompts a user for a password, you might want it to print `password` in English, `passwort` in German, `contraseña` in Spanish, and so forth.

`gettext` works by making simple string substitutions of selected program text. To do this, it consults a specially constructed locale database that contains mappings of the original program text to translated versions in various languages. This database is application-specific and must be constructed with special tools (described shortly).

The standard interface to `gettext` relies on the following functions, which are used to both locate the translation database and produce translated strings.

    bindtextdomain(domain [, localedir])

Sets the location of the locale directory for a given domain. `domain` is typically the name of the application and `localedir` is a path such as `/usr/local/share/locale`.

When searching for translation text, `gettext` looks for a file in the directory `localedir` `/``language` `/LC_MESSAGES/domain.mo` where `language` is a language name such as `en`, `de`, `fr`, etc. Normally, the value of `language` is determined according to one of the following environment variables: `$LANGUAGE`, `$LANG`, `$LC_MESSAGES`, `$LC_ALL`. The `language` parameter and environment variables can also be a colon-separated list of acceptable languages. If `localedir` is omitted, the current binding for `domain` is returned.

    textdomain([domain])

Sets the domain that will be used for subsequent text translations. If `domain` is omitted, the name of the current domain is returned.

    gettext(message)

Returns the translated version of `message` according to the values of the current domain, locale database location, and language. If no suitable translation can be found, `message` is returned unmodified. This function is usually aliased to `_()` as described below.

    dgettext(domain, message)

Like `gettext()`, but `message` is looked up in the specified `domain` .

##### Example

The following example shows how the `gettext` module is used in an application and how a programmer can construct the translation database.

    # myapp.py
    import getpass
    import gettext

    gettext.bindtextdomain("myapp","./locale")    # Set locale directory
    gettext.textdomain("myapp")                   # Enabled 'myapp'
    _ = gettext.gettext                           # Alias _() to gettext()

    pw = getpass.getpass(_("password:"))
    if pw != "spam":
         print _("Authorization failed.\n");
         raise SystemExit

The use of the `_()` alias is a critical feature of the application. For one thing, this shortens the amount of code that needs to be typed. More importantly, in order to construct the translation database, automatic tools are used to extract translation text from program source by looking for special sequences such as _ `("...")`. For Python, the program `pygettext.py` (found in the `Tools/i18n` directory of the Python distribution) is used to do this. For example:

    % pygettext.py -o myapp.po myapp.py

The output of `pygettext.py` is a human-readable `.po` file that contains information about the translation strings marked by `_("...')` in the original source. To support a new language, the entries of this file are edited by supplying a foreign language translation. For example, an edited version of `myapp.po` might look like this:

    #: myapp.py:8
    msgid "Password:"
    msgstr "Passwort:"
    #: myapp.py:10
    msgid  "Authorization failed.\n"
    msgstr "Authorisierung fehlgeschlagen.\n"

Once the translations for a specific language are entered, the `myapp.po` file is converted to a binary form using the special `msgfmt.py` program (found in the same directory as `pygettext.py`). For example:

    % msgfmt.py myapp

This produces a file `myapp.mo` that can be copied to an appropriate subdirectory with the locale directory; for example, `locale/de/LC_MESSAGES/myapp.mo`. At this point, you can test the translation by setting the `$LANGUAGE` environment variable to the string `"de"` and running the application. You should now see translated text being printed instead of the original program text.

##### Class-Based Interface

In addition to the standard `gettext` interface, Python provides a class-based interface that provides better support for Unicode and is more flexible. The following functions are used for this interface:

    find(domain[, localedir[, languages]])

Locates the appropriate translation file (`.mo` file) based on the given domain, locale directory, and languages setting. `domain` and `localedir` are the same strings as used with the `bindtextdomain()` function. `languages` is a list of language strings to be searched. If `localedir` and `languages` are omitted, they default to the same values as for `bindtextdomain()`. Returns the filename of the translation file on success or `None` if no match is found.

    install(domain[, localedir[, unicode]])

Installs the `_()` function in the built-in namespace using the settings of `domain` and `localedir` . The `unicode` flag makes translation strings return as Unicode strings.

    translation(domain[, localedir[, languages[, class_]]])

Returns an instance of a translation object for the given `domain` , `localedir` , and `languages` parameters. `domain` and `localedir` are strings and `languages` is a list of language names. The `class` `_` parameter specifies alternative translation implementations and is primarily reserved for future expansion. The default value is `GNUTranslations`.

The translation object `t` returned by `translation()` supports the following methods and attributes:

    t.gettext(message)

Returns the translated version of `message` as a standard string.

    t.ugettext(message)

Returns the translated version of `message` as a Unicode string.

    t.info()

Returns a dictionary containing meta-data about the translation, including the character set, author, creation date, and so forth.

    t.charset()

Returns the character set encoding for the translation, such as `'ISO-8859-1'`.

##### Example

The following example illustrates the use of the class-based interface:

    # myapp.py
    import getpass
    import gettext

    gettext.install("myapp","./locale")
    pw = getpass.getpass(_("password:"))
    if pw != "spam":
         print _("Authorization failed.\n");
         raise SystemExit

Alternatively, you can directly control a translation instance as follows:

    import gettext
    t = gettext.translation("myapp","./locale", ["de"])
    a = t.gettext("password:")

##### Notes

- Currently, only the GNU `gettext` format is supported by this module. However, the module may be modified to support alternative translation encoding at a later date.

- When Python is run interactively, the `_` variable is used to hold the result of the last evaluated expression. This has the potential to clash with the `_()` function installed by the `gettext` module. However, such clashes are probably unlikely in practice.

#### `glob`

The `glob` module returns all filenames in a directory that match a pattern specified using the rules of the UNIX shell (as described in the fnmatch module).

    glob(pattern)

Returns a list of pathnames that match `pattern` .

##### Examples

    glob('*.html')
    glob('image[0-5]*.gif')

##### Note

- Tilde (~) and shell variable expansion are not performed. Use `os.path.expanduser()` and `os.path.expandvars()`, respectively, to perform these expansions prior to calling `glob()`.

? See Also fnmatch (165), os.path (193).

#### `grp`

The `grp` module provides access to the UNIX group database.

    getgrgid(gid)

Returns the group database entry for a group ID as a 4-tuple (`gr_name` , `gr_passwd` , `gr_gid` , `gr_mem` ):

- gr_name is the group name.

- gr_passwd is the group password (if any).

- gr_gid is the integer group ID.

- gr_mem is a list of usernames in the group.

Raises `KeyError` if the group doesn’t exist.

    getgrnam(name)

Same as `getgrgid()`, but looks up a group by name.

    getgrall()

Returns all available group entries as a list of tuples as returned by `getgrgid()`.

? See Also pwd (196).

#### `gzip`

The `gzip` module provides a class `GzipFile` that can be used to read and write files compatible with the GNU `gzip` program. `GzipFile` objects work like ordinary files except that data is automatically compressed or decompressed.

    GzipFile([filename [, mode [, compresslevel [, fileobj]]]])

Opens a `GzipFile`. `filename` is the name of a file and `mode` is one of `'r'`, `'rb'`, `'a'`, `'ab'`, `'w'`, or `'wb'`. The default is `'rb'`. `compresslevel` is an integer from `1` to `9` that controls the level of compression. `1` is the fastest and produces the least compression. `9` is the slowest and produces the most compression (the default). `fileobj` is an existing file object that should be used. If supplied, it’s used instead of the file named by `filename` .

    open(filename [, mode [, compresslevel]])

Same as `GzipFile(``filename` `,` `mode` `,` `compresslevel` `)`. The default mode is `'rb'`. The default `compresslevel` is 9.

##### Notes

- Calling the `close()` method of a `GzipFile` object doesn’t close files passed in `fileobj` . This allows additional information to be written to a file after the compressed data.

- Files produced by the UNIX `compress` program are not supported.

- This module requires the `zlib` module.

? See Also zlib (217), zipfile (214).

#### `locale`

The `locale` module provides access to the POSIX locale database, which allows programmers to handle certain cultural issues in an application without knowing all the specifics of each country where the software is executed. A “locale” defines a set of parameters that describe the representation of strings, time, numbers, and currency. These parameters are grouped into the following category codes:

Category | Description
--- | ---
`LC_CTYPE` | Character conversion and comparison.
`LC_COLLATE` | String sorting. Affects `strcoll()` and `strxfrm()`.
`LC_TIME` | Time formatting. Affects `time.strftime()`.
`LC_MONETARY` | Formatting of monetary values.
`LC_MESSAGES` | Message display. This may affect error messages returned by functions such as `os.strerror()`.
`LC_NUMERIC` | Number formatting. Affects `format()`, `atoi()`, `atof()`, and `str()`.
`LC_ALL` | A combination of all locale settings.

The following functions are available:

    setlocale(category [, locale])

If `locale` is specified, this function changes the locale setting for a particular category. `locale` is a string that specifies the locale name. If set to `'C'`, the portable locale is selected (the default). If the empty string, the default locale from the user’s environment is selected. If `locale` is omitted, a string representing the setting for the given category is returned. Raises the exception `locale.Error` on failure.

    localeconv()

Returns the database of local conventions as a dictionary.

    strcoll(string1, string2)

Compares two strings according to the current `LC_COLLATE` setting. Returns a negative, positive, or zero value depending on whether `string1` collates before or after `string2` or is equal to it.

    strxfrm(string)

Transforms a string to one that can be used for the built-in function `cmp()` and still return locale-aware results.

    format(format, val [, grouping = 0])

Formats a number `val` according to the current `LC_NUMERIC` setting. The `format` follows the conventions of the `%` operator. For floating-point values, the decimal point is modified, if appropriate. If `grouping` is true, the locale grouping is taken into account.

    str(float)

Formats a floating-point number using the same format as the built-in function `str(``float` `)`, but takes the decimal point into account.

    atof(string)

Converts a string to a floating-point number according to the `LC_NUMERIC` settings.

    atoi(string)

Converts a string to an integer according to the `LC_NUMERIC` conventions.

##### Exception

    Error

Raised on failure of the `setlocale()` function.

##### Note

- Additional information about this module is available in the online library reference.

? See Also http://www.python.org/doc/lib/module-locale.html.

#### `macfs`

The `macfs` module is used to manipulate files and aliases on the Macintosh. For any function or method that expects a file argument, the argument may be a full or partial Macintosh pathname string, an `FSSpec` object, or a 3-tuple (`wdRefNum` `,` `parID` `,` `name` ).

    FSSpec(file)

Creates an `FSSpec` object for the specified file.

    RawFSSpec(data)

Creates an `FSSpec` object, given the raw data for the underlying `FSSpec` C data structure as a string.

    RawAlias(data)

Creates an `Alias` object, given the raw data for the underlying `alias` C data structure as a string.

    FInfo()

Creates a zero-filled `FInfo` object.

    ResolveAliasFile(file)

Resolves an alias file. Returns a 3-tuple (`fsspec` `,` `isfolder` `,` `aliased` ) in which `fsspec` is the resulting `FSSpec` object, `isfolder` is true if `fsspec` points to a folder, and `aliased` is true if the file was an alias.

    StandardGetFile([type1 [, type2 [, ... ]]])

Presents an “open input file” dialog and requests the user to select a file. Up to four four-character file types can be passed to limit the types of files from which the user can choose. Returns a tuple containing an `FSSpec` object and a flag indicating whether the user completed the dialog without canceling.

    PromptGetFile(prompt type1 [, type2, [, ...]])

Similar to `StandardGetFile()`, but allows a prompt to be specified.

    StandardPutFile(prompt [, default])

Presents an “open output file” dialog and requests the user to select a filename. `prompt` is a prompt string and `default` is the default filename. Returns a tuple containing an `FSSpec` object and a flag indicating whether the user completed the dialog without canceling.

    GetDirectory([prompt])

Presents a “select a directory” dialog. `prompt` is a prompt string. Returns a tuple containing an `FSSpec` object and a success indicator.

    SetFolder([fsspec])

Sets the folder that’s initially presented to the user when one of the file selection dialogs is presented. `fsspec` should point to a file in the folder, not the folder itself (the file need not exist, though). If no argument is passed, the folder will be set to the current directory.

    FindFolder(where, which, create)

Locates a special Macintosh folder such as the Trash or Preferences folder. `where` is the disk to search and is typically set to `MACFS.kOnSystemDisk`. `which` is a four character string specifying the folder to locate. (These strings are often specified using one of the symbols in the following table.) `create` , if set to `1`, causes the folder to be created if it doesn’t exist. Returns a tuple (`vrefnum` `,` `dirid` ). The contents of this tuple can be used as the first two elements of the 3-tuple (`vrefnum` `,` `dirid` `,` `name` ) suitable for use as a filename.

The following list shows the symbolic names in the `MACFS` module used for the `which` parameter of `FindFolder()`:

`kALMLocationsFolderType` | `kModemScriptsFolderType`
`kALMModulesFolderType` | `kOpenDocEditorsFolderType`
`kALMPreferencesFolderType` | `kOpenDocFolderType`
`kAppleExtrasFolderType` | `kOpenDocLibrariesFolderType`
`kAppleMenuFolderType` | `kOpenDocShellPlugInsFolderType`
`kApplicationAliasType` | `kPreferencesFolderType`
`kApplicationSupportFolderType` | `kPrintMonitorDocsFolderType`
`kApplicationsFolderType` | `kPrinterDescriptionFolderType`
`kAssistantsFolderType` | `kPrinterDriverFolderType`
`kChewableItemsFolderType` | `kScriptingAdditionsFolderType`
`kColorSyncProfilesFolderType` | `kSharedLibrariesFolderType`
`kContextualMenuItemsFolderType` | `kShutdownItemsDisabledFolderType`
`kControlPanelDisabledFolderType` | `kStartupFolderType`
`kControlPanelFolderType` | `kStartupItemsDisabledFolderType`
`kControlStripModulesFolderType` | `kStationeryFolderType`
`kDesktopFolderType` | `kSystemExtensionDisabledFolderType`
`kDocumentsFolderType` | `kSystemFolderType`
`kEditorsFolderType` | `kTemporaryFolderType`
`kExtensionDisabledFolderType` | `kTextEncodingsFolderType`
`kExtensionFolderType` | `kThemesFolderType`
`kFavoritesFolderType` | `kTrashFolderType`
`kFontsFolderType` | `kUtilitiesFolderType`
`kGenEditorsFolderType` | `kVoicesFolderType`
`kHelpFolderType` | `kVolumeRootFolderType`
`kInternetPlugInFolderType` | `kWhereToEmptyTrashFolderType`
`kMacOSReadMesFolderType` |

    NewAliasMinimalFromFullPath(pathname)

Returns a minimal alias object that points to the given file, which must be specified as a full pathname. This is the only way to create an alias pointing to a nonexistent file.

    FindApplication(creator)

Locates the application with the four-character creator code `creator` . The function returns an `FSSpec` object pointing to the application.

An instance `f` of an `FSSpec` object has the following attributes and methods:

    f.data

The raw data from the underlying `FSSpec` object.

    f.as_pathname()

Returns the full pathname.

    f.as_tuple()

Returns the (`wdRefNum,` `parID` `,` `name` ) tuple of the file.

    f.NewAlias([file])

Creates an `Alias` object pointing to the file described by `f` . If the optional `file` parameter is given, the alias is created relative to that file; otherwise, it’s absolute.

    f.NewAliasMinimal()

Creates a minimal alias pointing to this file.

    f.GetCreatorType()

Returns the four-character creator code and file type.

    f.SetCreatorType(creator, type)

Sets the four-character `creator` and `type` of the file.

    f.GetFInfo()

Returns the `FInfo` object describing the finder information for the file.

    f.SetFInfo(finfo)

Sets the finder info for the file to the values in the `FInifo` object `finfo` .

    f.GetDates()

Returns a tuple with three floating-point values representing the creation date, modification date, and backup date of the file.

    f.SetDates(crdate, moddate, backupdate)

Sets the creation, modification, and backup dates of the file.

An `Alias` object `a` has the following attributes and methods:

    a.data

The raw data for the `Alias` record as a binary string.

    a.Resolve([file])

Resolves the alias and returns a tuple containing the `FSSpec` for the file pointed to and a flag indicating whether the `Alias` object was modified during the search process. If the file doesn’t exist but the path leading up to it does, a valid `FSSpec` is returned. `file` is an optional file that must be supplied if the alias was originally created as a relative alias.

    a.GetInfo(index)

Retrieves alias information. `index` is an integer code that specifies the information to retrieve, and is one of the following values:

Value | Description
--- | ---
`-3` | Zone name
`-2` | Server name
`-1` | Volume name
`0` | Target name
`1` | Parent directory name

    a.Update(file [, file2])

Updates the alias to point to `file` . If `file2` is present, a relative alias will be created. An `FInfo` object `finfo` has the following attributes:

    finfo.Creator

The four-character creator code of the file.

    finfo.Type

The four-character type code of the file.

    finfo.Flags

The finder flags for the file, as 16-bit integers. The bit values in `Flags` are defined by the following constants defined in the module `MACFS`: `kHasBeenInited`, `kHasBundle`, `kHasCustomIcon`, `kIsAlias`, `kIsInvisible`, `kIsOnDesk`, `kIsShared`, `kIsStationary`, `kNameLocked`.

    finfo.Location

A pointer giving the position of the file’s icon in its folder.

    finfo.Fldr

The folder the file is in (as an integer).

? See Also macostools (176), findertools (165), http://www.python.org/doc/mac (Macintosh Library Reference).

#### `macostools`

The `macostools` module contains functions for file manipulation on the Macintosh.

    copy(src, dst [, createpath [, copytimes]])

Copies file `src` to `dst` . If `createpath` is nonzero, `dst` must be a pathname, and the folders leading to the destination are created if necessary. By default, the data and resource forks are copied in addition to some Finder information. If `copytimes` is nonzero, the creation, modification, and backup times are copied as well. Custom icons, comments, and icon positions are not copied. If `src` is an alias, the original to which the alias points is copied, not the alias file.

    copytree(src, dst)

Recursively copies a file tree from `src` to `dst` , creating folders as needed. `src` and `dst` must be pathname strings.

    mkalias(src, dst)

Creates a Finder alias `dst` pointing to `src` .

    touched(dst)

Tells the finder that the Finder information of `dst` has changed and that the Finder should update the file’s icon and other currently viewable information.

    BUFSIZ

The buffer size used for copying (in bytes). The default is 1 megabyte.

##### Note

- Except for `copytree()`, filenames can be specified as strings or as `FSSpec` objects created by the `macfs` module.

? See Also macfs (173).

#### `mmap`

The `mmap` module provides support for a memory-mapped file object. This object behaves both like a file and a string and can be used in most places where an ordinary file or string is expected. Furthermore, the contents of a memory-mapped file are mutable. This means that modifications can be made using index-assignment and slice-assignment operators. Unless a private mapping of the file has been made, such changes directly alter the contents of the underlying file.

A memory-mapping file is created by the `mmap()` function, which is slightly different on UNIX and Windows.

    mmap(fileno, length [, flags, prot])

(UNIX) Returns an `mmap` object that maps `length` bytes from the file with integer file descriptor `fileno` . `flags` specifies the nature of the mapping and is the bitwise-or of the following:

Flag | Meaning
--- | ---
`MAP_PRIVATE` | Create a private copy-on-write mapping. Changes to the object will be private to this process.
`MAP_SHARED` | Share the mapping with all other processes mapping the same areas of the file. Changes to the object will affect all mappings.
`MAP_ANON` | Used when creating an anonymous shared-memory region on BSD.
`MAP_DENYWRITE` | Disallow writes (not available on all platforms).
`MAP_EXECUTABLE` | Map memory as executable (not available on all platforms).

The default `flags` setting is `MAP_SHARED`. `prot` specifies the memory protections of the object and is the bitwise-or of the following:

Setting | Meaning
--- | ---
`PROT_READ` | Data can be read from the object.
`PROT_WRITE` | Modifications can be made to the object.
`PROT_EXEC` | The object can contain executable instructions.

The default value of `prot` is `PROT_READ | PROT_WRITE`. The modes specified in `prot` must match the access permissions used to open the underlying file descriptor `fileno` . In most cases, this means that the file should be opened in read/write mode (for example, `os.open(``name` `, os.O_RDWR)`).

    mmap(fileno, length[, tagname])

(Windows) Returns an `mmap` object that maps `length` bytes from the file specified by the integer file descriptor `fileno` . This file should be open for both reading and writing or an error will be generated. `tagname` is an optional string that can be used to name the mapping. If the `tagname` refers to an existing mapping, that mapping is opened. Otherwise, a new mapping is created. If `tagname` is `None`, an unnamed mapping is created.

A memory-mapped file object `m` supports the following methods.

    m.close()

Closes the file. Subsequent operations will result in an exception.

    m.find(string[, start])

Returns the index of the first occurrence of `string` . `start` specifies an optional starting position. Returns `-1` if no match is found.

    m.flush([offset, size])

Flushes modifications of the in-memory copy back to the filesystem. `offset` and `size` specify an optional range of bytes to flush. Otherwise, the entire mapping is flushed.

    m.move(dst, src, count)

Copies `count` bytes starting at index `src` to the destination index `dst` . This copy is performed using the C `memmove()` function, which is guaranteed to work correctly when the source and destination regions happen to overlap.

    m.read(n)

Reads up to `n` bytes from the current file position and returns the data as a string.

    m.read_byte()

Reads a single byte from the current file position and returns it as a string of length `1`.

    m.readline()

Returns a line of input starting at the current file position.

    m.resize(newsize)

Resizes the memory-mapped object to contain `newsize` bytes.

    m.seek(pos [, whence])

Sets the file position to a new value. `pos` and `whence` have the same meaning as for the `seek()` method on file objects.

    m.size()

Returns the length of the file. This value may be larger than the size of the memory-mapped region.

    m.tell()

Returns the value of the file pointer.

    m.write(string)

Writes a string of bytes to the file at the current file pointer.

    m.write_byte(byte)

Writes a single byte into memory at the current file pointer.

##### Notes

- Certain memory mappings may only work with a length that’s a multiple of the system pagesize, which is contained in the constant `mmap.PAGESIZE`.

- On UNIX SVR4 systems, anonymous mapped memory can be obtained by calling `mmap()` on the file `/dev/zero`, opened with appropriate permissions.

- On UNIX BSD systems, anonymous mapped memory can be obtained by calling `mmap()` with a negative file descriptor and the flag `mmap.MAP_ANON`.

#### `msvcrt`

The `msvcrt` module provides access to a number of useful functions in the Microsoft Visual C runtime library. This module is available only on Windows.

    getch()

Reads a keypress and returns the resulting character. This call blocks if a keypress is not available. If the pressed key was a special function key, the call returns `'\000'` or `'\xe0'` and the next call returns the keycode. This function doesn’t echo characters to the console, nor can the function be used to read Ctrl+C.

    getche()

Like `getch()` except that characters are echoed (if printable).

    get_osfhandle(fd)

Returns the file handle for file descriptor `fd` . Raises `IOError` if `fd` is not recognized.

    heapmin()

Forces the internal Python memory manager to return unused blocks to the operating system. This works only on Windows NT and raises `IOError` on failure.

    kbhit()

Returns true if a keypress is waiting to be read.

    locking(fd, mode, nbytes)

Locks part of a file, given a file descriptor from the C runtime. `nbytes` is the number of bytes to lock relative to the current file pointer. `mode` is one of the following integers:

Setting | Description
--- | ---
`0` | Unlocks the file region (`LK_UNLCK`)
`1` | Locks the file region (`LK_LOCK`)
`2` | Locks the file region; nonblocking (`LK_NBLCK`)
`3` | Locks for writing (`LK_RLCK`)
`4` | Locks for writing; nonblocking (`LK_NBRLCK`)

Attempts to acquire a lock that take more than approximately 10 seconds result in an error.

    open_osfhandle(handle, flags)

Creates a C runtime file descriptor from the file handle `handle` . `flags` is the bitwise-or of `os.O_APPEND`, `os.O_RDONLY`, and `os.O_TEXT`. Returns an integer file descriptor that can be used as a parameter to `os.fdopen()` to create a file object.

    putch(char)

Prints the character `char` to the console without buffering.

    setmode(fd, flags)

Sets the line-end translation mode for file descriptor `fd` . `flags` is `os.O_TEXT` for text mode and `os.O_BINARY` for binary mode.

    ungetch(char)

Causes the character `char` to be “pushed back” into the console buffer. It will be the next character read by `getch()` or `getche()`.

##### Note

- A wide variety of Win32 extensions are available that provide access to the Microsoft Foundation Classes, COM components, graphical user interfaces, and so forth. These topics are far beyond the scope of this book, but detailed information about many of these topics is available in Python Programming on Win32 by Mark Hammond and Andy Robinson (O’Reilly & Associates, 1999). http://www.python.org also maintains an extensive list of contributed modules for use under Windows.

? See Also _winreg (211).

#### `os`

The `os` module provides a portable interface to common operating-system services. It does this by searching for an OS-dependent built-in module such as `mac` or `posix` and exporting the functions and data as found there. Unless otherwise noted, functions are available on Windows, Macintosh, and UNIX.

The following general-purpose variables are defined:

    environ

A mapping object representing the current environment variables. Changes to the mapping are reflected in the current environment.

    linesep

The string used to separate lines on the current platform. May be a single character such as `'\n'` for POSIX or `'\r'` for MacOS, or multiple characters such as `'\r\n'` for Windows.

    name

The name of the OS-dependent module imported: `'posix'`, `'nt'`, `'dos'`, `'mac'`, or `'os2'`.

    path

The OS-dependent standard module for pathname operations. This module can also be loaded using `import` `os.path`.

##### Process Environment

The following functions are used to access and modify various parameters related to the environment in which a process runs. Process, group, process group, and session IDs are integers unless otherwise noted.

    chdir(path)

Changes the current working directory to `path` .

    ctermid()

Returns a string with the filename of the control terminal for the process. UNIX.

    getcwd()

Returns a string with the current working directory.

    getegid()

Returns the effective group ID. UNIX.

    geteuid()

Returns the effective user ID. UNIX.

    getgid()

Returns the real group ID of the process. UNIX.

    getgroups()

Return a list of integer group IDs to which the process owner belongs. UNIX.

    getpgrp()

Returns the ID of the current process group. Process groups are typically used in conjunction with job control. The process group is not necessarily the same as the group ID of the process. UNIX.

    getpid()

Returns the real process ID of the current process. UNIX and Windows.

    getppid()

Returns the process ID of the parent process. UNIX.

    getuid()

Returns the real user ID of the current process. UNIX.

    putenv(varname, value)

Sets environment variable `varname` to `value` . Changes affect subprocesses started with `os.system()`, `popen()`, `fork()`, and `execv()`. Assignments to items in `os.environ` automatically call `putenv()`. However, calls to `putenv()` don’t update `os.environ`. UNIX and Windows.

    setgid(gid)

Sets the group ID of the current process. UNIX.

    setpgrp()

Creates a new process group by calling the system call `setpgrp()` or `setpgrp(0, 0)`, depending on which version is implemented (if any). Returns the ID of the new process group. UNIX.

    setpgid(pid, pgrp)

Assigns process `pid` to process group `pgrp` . If `pid` is equal to `pgrp` , the process becomes a new process group leader. If `pid` is not equal to `pgrp` , the process joins an existing group. If `pid` is `0`, the process ID of the calling process is used. If `pgrp` is `0`, the process specified by `pid` becomes a process group leader. UNIX.

    setreuid(ruid, euid)

Set the real and effective user ID of the calling process. UNIX.

    setregid(rgid, egid)

Set the real and effective group ID of the calling process. UNIX.

    setsid()

Creates a new session and returns the newly created session ID. Sessions are typically associated with terminal devices and the job control of processes that are started within them. UNIX.

    setuid(uid)

Sets the real user ID of the current process. This function is privileged and often can be performed only by processes running as root. UNIX.

    strerror(code)

Returns the error message corresponding to the integer error `code` . UNIX and Windows.

? See Also errno (156).

    umask(mask)

Sets the current numeric umask and returns the previous umask. The umask is used to clear permissions bits on files created by the process. UNIX and Windows.

? See Also `os.open` (184).

    uname()

Returns a tuple of strings (`sysname` , `nodename` , `release` , `version` , `machine` ) identifying the system type. UNIX.

##### File Creation and File Descriptors

The following functions provide a low-level interface for manipulating files and pipes. In these functions, files are manipulated in terms of an integer file descriptor `fd` . The file descriptor can be extracted from a file object by invoking its `fileno()` method.

    close(fd)

Closes the file descriptor `fd` previously returned by `open()` or `pipe()`.

    dup(fd)

Duplicates file descriptor `fd` . Returns a new file descriptor that’s the lowest-numbered unused file descriptor for the process. The new and old file descriptors can be used interchangeably. Furthermore, they share state such as the current file pointer and locks. UNIX and Windows.

    dup2(oldfd, newfd)

Duplicates file descriptor `oldfd` to `newfd` . If `newfd` already corresponds to a valid file descriptor, it’s closed first. UNIX and Windows.

    fdopen(fd [, mode [, bufsize]])

Returns an open file object connected to file descriptor `fd` . The `mode` and `bufsize` arguments have the same meaning as in the built-in `open()` function.

    fpathconf(fd, name)

Returns configurable pathname variables associated with the open file with descriptor `fd` . `name` is a string that specifies the name of the value to retrieve. The values are usually taken from parameters contained in system header files such as `<limits.h>` and `<unistd.h>`. POSIX defines the following constants for `name` :

Constant | Description
--- | ---
`"PC_ASYNC_IO"` | Indicates whether asynchronous I/O can be performed on `fd` .
`"PC_CHOWN_RESTRICTED"` | Indicates whether the `chown()` function can be used. If `fd` refers to a directory, this applies to all files in the directory.
`"PC_FILESIZEBITS"` | Maximum size of a file.
`"PC_LINK_MAX"` | Maximum value of the file’s link count.
`"PC_MAX_CANON"` | Maximum length of a formatted input line. `fd` refers to a terminal.
`"PC_MAX_INPUT"` | Maximum length of an input line. `fd` refers to a terminal.
`"PC_NAME_MAX"` | Maximum length of a filename in a directory.
`"PC_NO_TRUNC"` | Indicates whether an attempt to create a file with a name longer than `PC_NAME_MAX` for a directory will fail with an `ENAMETOOLONG` error.
`"PC_PATH_MAX"` | Maximum length of a relative pathname when the directory `fd` is the current working directory.
`"PC_PIPE_BUF"` | Size of the pipe buffer when `fd` refers to a pipe or FIFO.
`"PC_PRIO_IO"` | Indicates whether priority I/O can be performed on `fd` .
`"PC_SYNC_IO"` | Indicates whether synchronous I/O can be performed on `fd` .
`"PC_VDISABLE"` | Indicates whether `fd` allows special-character processing to be disabled. `fd` must refer to a terminal.

Not all names are available on all platforms, and some systems may define additional configuration parameters. However, a list of the names known to the operating system can be found in the directionary `os.pathconf_names`. If a known configuration name is not included in `os.pathconf_names`, its integer value can also be passed as `name` . Even if a name is recognized by Python, this function may still raise an `OSError` if the host operating system doesn’t recognize the parameter or associate it with the file `fd` . This function is available only on some versions of UNIX.

    fstat(fd)

Returns the status for file descriptor `fd` . Returns the same values as the `os.stat()` function. UNIX and Windows.

    fstatvfs(fd)

Returns information about the filesystem containing the file associated with file descriptor `fd` . Returns the same values as the `os.statvfs()` function. UNIX.

    ftruncate(fd, length)

Truncates the file corresponding to file descriptor `fd` , so that it’s at most `length` bytes in size. UNIX.

    lseek(fd, pos, how)

Sets the current position of file descriptor `fd` to position `pos` . Values of `how` are as follows: `0` sets the position relative to the beginning of the file, `1` sets it relative to the current position, and `2` sets it relative to the end of the file.

    open(file [, flags [, mode]])

Opens the file `file` . `flags` is the bitwise-or of the following constant values:

Value | Description
--- | ---
`O_RDONLY` | Open the file for reading.
`O_WRONLY` | Open the file for writing.
`O_RDWR` | Open for reading and writing (updates).
`O_APPEND` | Append bytes to the end of the file.
`O_CREAT` | Create the file if it doesn’t exist.
`O_NONBLOCK` | Don’t block on open, read,or write (UNIX).
`O_NDELAY` | Same as `O_NONBLOCK` (UNIX).
`O_DSYNC` | Synchronous writes (UNIX).
`O_NOCTTY` | When opening a device, don’t set controlling terminal (UNIX).
`O_TRUNC` | If the file exists, truncates to zero length.
`O_RSYNC` | Synchronous reads (UNIX).
`O_SYNC` | Synchronous writes (UNIX).
`O_EXCL` | Error if `O_CREAT` and the file already exists.
`O_TEXT` | Text mode (Windows).
`O_BINARY` | Binary mode (Windows).

Synchronous I/O modes (`O_SYNC`, `O_DSYNC`, `O_RSYNC`) force I/O operations to block until they’ve been completed at the hardware level (for example, a write will block until the bytes have been physically written to disk). The `mode` parameter contains the file permissions represented as the bitwise-or of the following octal values:

Mode | Meaning
--- | ---
`0100` | User has execute permission.
`0200` | User has write permission.
`0400` | User has read permission.
`0010` | Group has execute permission.
`0020` | Group has write permission.
`0040` | Group has read permission.
`0001` | Others have execute permission.
`0002` | Others have write permission.
`0004` | Others have read permission.

The default mode of a file is (`0777 & ~umask`) where the umask setting is used to remove selected permissions. For example, a umask of `0022` removes write permission for groups and others. The umask can be changed using the `os.umask()` function. The umask setting has no effect on Windows and Macintosh.

    openpty()

Opens a pseudo-terminal and returns a pair of file descriptors `(``master` `,``slave` `)` for the PTY and TTY. Available on some versions of UNIX.

    pipe()

Creates a pipe that can be used to establish unidirectional communication with another process. Returns a pair of file descriptors `(``r` `,` `w` `)` usable for reading and writing, respectively. This function is usually called prior to executing a `fork()` function. After the `fork()`, the sending process closes the read end of the pipe and the receiving process closes the write end of the pipe. At this point, the pipe is activated and data can be sent from one process to another using `read()` and `write()` functions. UNIX.

    popen(command [, mode [, bufsize]])

Opens a pipe to or from a command. The return value is an open file object connected to the pipe, which can be read or written depending on whether `mode` is `'r'` (the default) or `'w'`. `bufsize` has the same meaning as in the built-in `open()` function. The exit status of the command is returned by the `close()` method of the returned file object, except that when the exit status is zero, `None` is returned.

    popen2(cmd [, bufsize[, mode]])

Executes `cmd` as a subprocess and returns the file objects `(``child_stdin` `,` `child_stdout` `)`. `bufsize` is the buffer size. `mode` is `'t'` or `'b'` to indicate text or binary mode, which is needed on Windows.

    popen3(cmd [, bufsize[, mode]])

Executes `cmd` as a subprocess and returns three file objects `(``child_stdin` `,` `child_stdout` `,` `child_stderr` `)`.

    popen4(cmd [, bufsize[, mode]])

Executes `cmd` as a subprocess and returns two file objects `(``child_stdin` `,` `child_stdout_stderr` `)`, in which the standard output and standard error of the child are combined.

    read(fd, n)

Reads at most `n` bytes from file descriptor `fd` . Returns a string containing the bytes read.

    tcgetpgrp(fd)

Returns the process group associated with the control terminal given by `fd` . UNIX.

    tcsetpgrp(fd, pg)

Sets the process group associated with the control terminal given by `fd` . UNIX.

    ttyname(fd)

Returns a string that specifies the terminal device associated with file descriptor `fd` . If `fd` is not associated with a terminal device, an exception is raised. UNIX.

    write(fd, str)

Writes the string `str` to file descriptor `fd` . Returns the number of bytes actually written.

##### Files and Directories

The following functions and variables are used to manipulate files and directories on the filesystem. To handle variances in file-naming schemes, the following variables contain information about the construction of pathnames:

Variable | Description
--- | ---
`altsep` | An alternative character used by the OS to separate pathname components, or `None` if only one separator character exists. This is set to `'/'` on DOS and Windows systems, where `sep` is a backslash.
`curdir` | The string used to refer to the current working directory: `'.'` for UNIX and Windows and `':'` for Macintosh.
`pardir` | The string used to refer to the parent directory: `'..'` for UNIX and Windows and `'::'` for Macintosh.
`pathsep` | The character used to separate search path components (as contained in the `$PATH` environment variable): `':'` for UNIX and `';'` for DOS and Windows.
`sep` | The character used to separate pathname components: `'/'` for UNIX and Windows and `':'` for Macintosh.

The following functions are used to manipulate files:

    access(path, accessmode)

Checks read/write/execute permissions for this process or file path. `accessmode` is `R_OK`, `W_OK`, `X_OK`, or `F_OK` for read, write, execute, or existence, respectively. Returns `1` if access is granted, `0` if not. UNIX.

    chmod(path, mode)

Changes the mode of `path` . `mode` has the same values as described for the `open()` function. UNIX and Windows.

    chown(path, uid, gid)

Changes the owner and group ID of `path` to the numeric `uid` and `gid` . UNIX.

    getbootvol()

Returns the name of the boot disk. Macintosh.

    link(src, dst)

Creates a hard link named `dst` that points to `src` . UNIX.

    listdir(path)

Returns a list containing the names of the entries in the directory `path` . The list is returned in arbitrary order and doesn’t include the special entries of `'.'` and `'..'`.

    lstat(path)

Like `stat()`, but doesn’t follow symbolic links. UNIX.

    mkfifo(path [, mode])

Creates a FIFO (a named pipe) named `path` with numeric mode `mode` . The default mode is `0666`. UNIX.

    mkdir(path [, mode])

Creates a directory named `path` with numeric mode `mode` . The default mode is `0777`. On non–UNIX systems, the `mode` setting may have no effect or be ignored.

    makedirs(path [, mode])

Recursive directory-creation function. Like `mkdir()`, but makes all the intermediate-level directories needed to contain the leaf directory. Raises an `OSError` exception if the leaf directory already exists or cannot be created.

    pathconf(path, name)

Returns configurable system parameters related to the pathname `path` . `name` is a string that specifies the name of the parameter and is the same as described for the `fpathconf()` function. UNIX.

? See Also `fpathconf` (182).

    readlink(path)

Returns a string representing the path to which a symbolic link `path` points. UNIX.

    remove(path)

Removes the file `path` . This is identical to the `unlink()` function.

    removedirs(path)

Recursive directory-removal function. Works like `rmdir()` except that, if the leaf directory is successfully removed, directories corresponding to the rightmost path segments will be pruned away until either the whole path is consumed or an error is raised (which is ignored, because it generally means that a parent directory isn’t empty). Raises an `OSError` exception if the leaf directory could not be removed successfully.

    rename(src, dst)

Renames the file or directory `src` to `dst` .

    renames(old, new)

Recursive directory-renaming or file-renaming function. Works like `rename()` except first attempting to create any intermediate directories needed to make the new pathname. After the rename, directories corresponding to the rightmost path segments of the old name will be pruned away using `removedirs()`.

    rmdir(path)

Removes the directory `path` .

    stat(path)

Performs a `stat()` system call on the given `path` to extract information about a file. The return value is a tuple of at least 10 integers in the order `st_mode` , `st_ino` , `st_dev` , `st_nlink` , `st_uid` , `st_gid` , `st_size` , `st_atime` , `st_mtime` , `st_ctime` . More items may be added at the end by some implementations, and on non–UNIX platforms some items are filled with dummy values. The standard module `stat` defines functions and constants that are useful for extracting information from a `stat` tuple.

    statvfs(path)

Performs a `statvfs()` system call on the given `path` to get information about the filesystem. The return value is a tuple of 10 integers in the order `f_bsize` , `f_frsize` , `f_blocks` , `f_bfree` , `f_bavail` , `f_files` , `f_ffree` , `f_favail` , `f_flag` , `f_namemax` . The standard module `statvfs` defines constants that can be used to extract information from the returned `statvfs` data. UNIX.

    symlink(src, dst)

Creates a symbolic link named `dst` that points to `src` .

    sync()

Syncs the filesystem. Macintosh.

    unlink(path)

Removes the file `path` . Same as `remove()`.

    utime(path, (atime, mtime))

Sets the access and modified time of the file to the given values. (The second argument is a tuple of two items.) The time arguments are specified in terms of the numbers returned by the `time.time()` function.

    xstat(path)

Like `stat()`, but the returned tuple includes three additional fields containing the size of the resource fork and the four-character creator and type codes. Macintosh.

##### Process Management

The following functions and variables are used to create, destroy, and manage processes.

    abort()

Generates a `SIGABRT` signal that’s sent to the calling process. Unless the signal is caught with a signal handler, the default is for the process to terminate with an error.

    defpath

This variable contains the default search path used by the `exec*p*()` functions if the environment doesn’t have a `'PATH'` variable.

    execl(path, arg0, arg1, ...)

Equivalent to `execv(``path` `, (``arg0` `,` `arg1` `, ...))`. UNIX and Windows.

    execle(path, arg0, arg1, ..., env)

Equivalent to `execve(``path` `, (``arg0` `,` `arg1` `, ...),` `env` `)`. UNIX and Windows.

    execlp(path, arg0, arg1, ...)

Equivalent to `execvp(``path` `, (``arg0` `,` `arg1` `, ...))`. UNIX and Windows.

    execv(path, args)

Executes the executable program `path` with argument list `args` , replacing the current process (that is, the Python interpreter). The argument list may be a tuple or list of strings. UNIX and Windows.

    execve(path, args, env)

Executes a new program like `execv()`, but additionally accepts a dictionary `env` that defines the environment in which the program runs. `env` must be a dictionary mapping strings to strings. UNIX and Windows.

    execvp(path, args)

Like `execv(``path` `,` `args` `)`, but duplicates the shell’s actions in searching for an executable file in a list of directories. The directory list is obtained from `environ['PATH']`. UNIX and Windows.

    execvpe(path, args, env)

Like `execvp()`, but with an additional environment variable as in the `execve()` function. UNIX and Windows.

    _exit(n)

Exits immediately to the system with status `n` , without performing any cleanup actions. Note: The standard way to exit Python programs is `sys.exit(``n` `)`. UNIX and Windows.

    fork()

Creates a child process. Returns `0` in the newly created child process and the child’s process ID in the original process. The child process is a clone of the original process and shares many resources such as open files. UNIX.

    forkpty()

Creates a child process using a new pseudo-terminal as the child’s controlling terminal. Returns a pair (`pid` `,` `fd` ) in which `pid` is `0` in the child and `fd` is a file descriptor of the master end of the pseudo-terminal. This function is available only in certain versions of UNIX.

    kill(pid, sig)

Sends the process `pid` the signal `sig` . A list of signal names can be found in the `signal` module. UNIX.

    nice(increment)

Adds an increment to the scheduling priority (the “niceness”) of the process. Returns the new niceness. Typically, users can only decrease the priority of a process, since increasing the priority requires root access. UNIX.

    plock(op)

Locks program segments into memory, preventing them from being swapped. The value of `op` is an integer that determines which segments are locked. The value of `op` is platform-specific, but is typically one of `UNLOCK`, `PROCLOCK`, `TXTLOCK`,or `DATLOCK`. These constants are not defined by Python, but might be found in the `<``sys` `/lock.h>` header file. This function is not available on all platforms and often can be performed only by a process with an effective user ID of `0` (root). UNIX.

    spawnv(mode, path, args)

Executes the program `path` in a new process, passing the arguments specified in `args` as command-line parameters. `args` can be a list or a tuple. The first element of `args` should be the name of the program. `mode` is one of the following constants:

Constant | Description
--- | ---
`P_WAIT` | Executes the program and waits for it to terminate. Returns the program’s exit code.
`P_NOWAIT` | Executes the program and returns the process handle.
`P_NOWAITO` | Same as `P_NOWAIT`.
`P_OVERLAY` | Executes the program and destroys the calling process (same as the `exec` functions).
`P_DETACH` | Executes the program and detaches from it. The calling program continues to run, but cannot wait for the spawned process.

`spawnv()` is available on Windows and some versions of UNIX.

    spawnve(mode, path, args, env)

Executes the program `path` in a new process, passing the arguments specified in `args` as command-line parameters and the contents of the mapping `env` as the environment. `args` can be a list or a tuple. `mode` has the same meaning as described for `spawnv()`. Windows and UNIX.

    startfile(path)

Launches the application associated with the file `path` . This performs the same action as would occur if you double-clicked the file in Windows Explorer. The function returns as soon as the application is launched. Furthermore, there is no way to wait for completion or to obtain exit codes from the application. `path` is relative to the current directory. Windows.

    system(command)

Executes `command` (a string) in a subshell. On UNIX, the return value is the exit status of the process as returned by `wait()`. On Windows, the exit code is always `0`. UNIX and Windows.

    times()

Returns a 5-tuple of floating-point numbers indicating accumulated times in seconds. On UNIX, the tuple contains the user time, system time, children’s user time, children’s system time, and elapsed real time. On Windows, the tuple contains the user time, system time, and zeros for the other three values. UNIX and Windows. Not supported on Windows 95/98.

    wait([pid])

Waits for completion of a child process and returns a tuple containing its process ID and exit status. The exit status is a 16-bit number whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero). The high bit of the low byte is set if a core file was produced. `pid` , if given, specifies the process to wait for. If omitted, `wait()` returns when any child process exits. UNIX.

    waitpid(pid, options)

Waits for a change in the state of a child process given by process ID `pid` , and returns a tuple containing its process ID and exit status indication, encoded as for `wait()`. `options` should be `0` for normal operation or `WNOHANG` to avoid hanging if no child process status is available immediately. This function can also be used to gather information about child processes that have only stopped executing for some reason (refer to the UNIX man pages for `waitpid` for details). UNIX.

The following functions take a process status code as returned by `waitpid()` and are used to examine the state of the process (UNIX only).

    WIFSTOPPED(status)

Returns true if the process has been stopped.

    WIFSIGNALED(status)

Returns true if the process exited due to a signal.

    WIFEXITED(status)

Returns true if the process exited using the `exit()` system call.

    WEXITSTATUS(status)

If `WIFEXITED(``status` `)` is true, returns the integer parameter to the `exit()` system call. Otherwise, the return value is meaningless.

    WSTOPSIG(status)

Returns the signal that caused the process to stop.

    WTERMSIG(status)

Returns the signal that caused the process to exit.

##### System Configuration

The following functions are used to obtain system configuration information:

    confstr(name)

Returns a string-valued system configuration varible. `name` is a string specifying the name of the variable. The acceptable names are platform-specific, but a dictionary of known names for the host system is found in `os.confstr_names`. If a configuration value for a specified name is not defined, the empty string is returned. If `name` is unknown, `ValueError` is raised. An `OSError` may also be raised if the host system doesn’t support the configuration name. The parameters returned by this function mostly pertain to the build environment on the host machine and include paths of system utilities, compiler options for various program configurations (for example, 32-bit, 64-bit, and largefile support), and linker options. UNIX.

    sysconf(name)

Returns an integer-valued system configuration variable. `name` is a string specifying the name of the variable. The names defined on the host system can be found in the dictionary `os.sysconf_names`. Returns `-1` if the configuration name is known but the value is not defined. Otherwise a `ValueError` or `OSError` may be raised. Some systems may define well over 100 different system parameters. However, the following table lists the parameters defined by POSIX.1 that should be available on most UNIX systems:

Parameter | Description
--- | ---
`"SC_ARG_MAX"` | Maximum length of the arguments that can be used with `exec()`.
`"SC_CHILD_MAX"` | Maximum number of processes per user ID.
`"SC_CLK_TCK"` | Number of clock ticks per second.
`"SC_NGROUPS_MAX"` | Maximum number of simultaneous supplementary group IDs.
`"SC_STREAM_MAX"` | Maximum number of streams a process can open at one time.
`"SC_TZNAME_MAX"` | Maximum number of bytes in a timezone name.
`"SC_OPEN_MAX"` | Maximum number of files a process can open at one time.
`"SC_JOB_CONTROL"` | System supports job control.
`"SC_SAVED_IDS"` | Indicates whether each process has a saved set-user-ID and a saved set-group-ID.

##### Exception

    error

Exception raised when a function returns a system-related error. This is the same as the built-in exception `OSError`. The exception carries two values: `errno` and `strerr`. The first contains the integer error value as described for the `errno` module. The latter contains a string error message. For exceptions involving the filesystem, the exception also contains a third attribute, `filename`, which is the filename passed to the function.

##### Example

The following example uses the `os` module to implement a minimalistic UNIX shell that can run programs and perform I/O redirection:

    import os, sys, string
    print 'Welcome to the Python Shell!'
    while 1:
         cmd = string.split(raw_input('pysh % '))
         if not cmd: continue
         progname = cmd[0]
         outfile = None
         infile = None
         args = [progname]
         for c in cmd[1:]:
              if c[0] == '>':
                  outfile = c[1:]
              elif c[0] == '<':
                  infile = c[1:]
              else:
                  args.append(c)
         # Check for a change in working directory
         if progname == 'cd':
               if len(args) > 1:
                   try:
                         os.chdir(args[1])
                   except OSError,e:
                         print e
               continue
         # Exit from the shell
         if progname == 'exit':
               sys.exit(0)
         # Spawn a process to run the command
         pid = os.fork()
         if not pid:
              # Open input file (redirection)
              if infile:
                  ifd = os.open(infile,os.O_RDONLY)
                  os.dup2(ifd,sys.stdin.fileno())
              # Open output file (redirection)
              if outfile:
                  ofd = os.open(outfile,os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
                  os.dup2(ofd,sys.stdout.fileno())
              # Run the command
              os.execvp(progname, args)
         else:
              childpid,ec = os.wait(pid)
              if ec:
                  print 'Exit code ',ec

##### Note

- The `os.popen2()`, `os.popen3()`, and `os.popen4()` functions can also be found in the `popen2` module. However, the order of the returned file objects is different.

? See Also os.path (193), stat (202), statvfs (203), time (208) , popen2 (195), signal (200), fcntl (161).

#### `os.path`

The `os.path` module is used to manipulate pathnames in a portable manner. It’s imported by the `os` module.

    abspath(path)

Returns an absolute version of the pathname `path` , taking the current working directory into account. For example, `abspath('../Python/foo')` might return `'/home/beazley/Python/foo'`.

    basename(path)

Returns the basename of pathname `path` . For example, `basename('/usr/local/python')` returns `'python'`.

    commonprefix(list)

Returns the longest string that’s a prefix of all strings in `list` . If `list` is empty, returns the empty string.

    dirname(path)

Returns the directory name of pathname `path` . For example, `dirname('/usr/local/python')` returns `'/usr/local'`.

    exists(path)

Returns true if `path` refers to an existing path.

    expanduser(path)

Replaces pathnames of the form `'~user'` with a user’s home directory. If the expansion fails or `path` does not begin with `'~'`, the path is returned unmodified.

    expandvars(path)

Expands environment variables of the form `'$``name` `'` or `'${``name` `}'` in `path` . Malformed or nonexistent variable names are left unchanged.

    getatime(path)

Returns the time of last access as the number of seconds since the epoch (see the time module).

    getmtime(path)

Returns the time of last modification as the number of seconds since the epoch (see the time module).

    getsize(path)

Returns the file size in bytes.

    isabs(path)

Returns true if `path` is an absolute pathname (begins with a slash).

    isfile(path)

Returns true if `path` is a regular file. This function follows symbolic links, so both `islink()` and `isfile()` can be true for the same path.

    isdir(path)

Returns true if `path` is a directory. Follows symbolic links.

    islink(path)

Returns true if `path` refers to a symbolic link. Returns false if symbolic links are unsupported.

    ismount(path)

Returns true if `path` is a mount point.

    join(path1 [, path2 [, ...]])

Intelligently joins one or more path components into a pathname. For example, `join('/home', 'beazley', 'Python')` returns `'/home/beazley/Python'` on UNIX.

    normcase(path)

Normalizes the case of a pathname. On non–case-sensitive filesystems, this converts `path` to lowercase. On Windows, forward slashes are also converted to backslashes.

    normpath(path)

Normalizes a pathname.This collapses redundant separators and up-level references so that `'A//B'`, `'A/./B'`, and `'A/foo/../B'` all become `'A/B'`. On Windows, forward slashes are converted to backslashes.

    samefile(path1, path2)

Returns true if `path1` and `path2` refer to the same file or directory. Macintosh and UNIX.

    sameopenfile(fp1, fp2)

Returns true if the open file objects `fp1` and `fp2` refer to the same file. Macintosh and UNIX.

    samestat(stat1, stat2)

Returns true if the stat tuples `stat1` and `stat2` as returned by `fstat()`, `lstat()`,or `stat()` refer to the same file. Macintosh and UNIX.

    split(path)

Splits `path` into a pair (`head` `,` `tail` ) where `tail` is the last pathname component and `head` is everything leading up to that. For example, `'/home/user/foo'` gets split into `('/home/user', 'foo')`. This tuple is the same as would be returned by `(dirname(), basename())`.

    splitdrive(path)

Splits `path` into a pair (`drive` `,` `filename` ) where `drive` is either a drive specification or the empty string. `drive` is always the empty string on machines without drive specifications.

    splitext(path)

Splits a pathname into a base filename and suffix. For example, `splitext('foo.txt')` returns `('foo', '.txt')`.

    walk(path, visitfunc, arg)

This function recursively walks all the directories rooted at `path` and calls the function `visitfunc(``arg` `,` `dirname` `,` `names` `)` for each directory. `dirname` specifies the visited directory and `names` is a list of the files in the directory as retrieved using `os.listdir(``dirname` `)`. The `visitfunc` function can modify the contents of names to alter the search process if necessary.

? See Also fnmatch (165), glob (170), os (180).

#### `popen2`

The `popen2` module is used to spawn processes and connect to their input/ output/error streams using pipes on UNIX and Windows. Note that these functions are also available in the `os` module with slightly different return values.

    popen2(cmd [, bufsize [, mode]])

Executes `cmd` as a subprocess and returns a pair of file objects (`child_stdout` `,` `child_stdin` ) corresponding to the input and output streams of the subprocess. `bufsize` specifies the buffer size for the I/O pipes. `mode` is one of `'t'` or `'b'` to indicate text or binary data, which is needed on Windows.

    popen3(cmd [, bufsize [, mode]])

Executes `cmd` as a subprocess like `popen2()`, but returns a triple (`child_stdout` `,` `child_stdin` `,` `child_stderr` ) that includes the standard error stream.

    popen4(cmd [, bufsize [, mode]])

Executes `cmd` as a subprocess like `popen2()`, but returns a pair of file objects `(``child_stdout_stderr` `,` `child_stdin` `)` in which the standard output and standard error streams have been combined.

In addition to the functions just described, the UNIX version of this module provides the following classes that can be used to control processes:

    Popen3(cmd [, capturestderr [, bufsize]])

This class represents a child process. `cmd` is the shell command to execute in a subprocess. The `capturestderr` flag, if true, specifies that the object should capture standard error output of the child process. `bufsize` is the size of the I/O buffers.

    Popen4(cmd [, bufsize])

Like the class `Popen3`, but combines standard output and standard error.

An instance `p` of the `Popen3` or `Popen4` class has the following methods and attributes:

    p.poll()

Returns the exit code of the child or `-1` if the child process has not finished yet.

    p.wait()

Waits for the child process to terminate and returns its exit code.

    p.fromchild

A file object that captures the output of the child process.

    p.tochild

A file object that sends input to the child process.

    p.childerr

A file object that captures the standard error stream of the child process. May be `None`.

    p.pid

Process ID of the child.

##### Note

- The order of file objects returned by `popen2()`, `popen3()`, and `popen4()` differs from the standard UNIX ordering of `stdin` , `stdout` , and `stderr` . The versions in the `os` module correct this.

? See Also commands (155), `os.popen` (185).

#### `pwd`

The `pwd` module provides access to the UNIX password database.

    getpwuid(uid)

Returns the password database entry for a numeric user ID `uid` . Returns a 7-tuple (`pw_name` `,` `pw_passwd` `,` `pw_uid` `,` `pw_gid` `,` `pw_gecos` `,` `pw_dir` `,` `pw_shell` ). The `pw_uid` and `pw_gid` items are integers; all others are strings. `KeyError` is raised if the entry cannot be found.

    getpwnam(name)

Returns the password database entry for a username.

    getpwall()

Returns a list of all available password database entries. Each entry is a tuple as returned by `getpwuid()`.

##### Example

    >>> import pwd
    >>> pwd.getpwnam('beazley')
    ('beazley', 'x', 100, 1, 'David M. Beazley', '/home/beazley', '/usr/local/bin/tcsh')
    >>>

? See Also grp (171), getpass (167), crypt (155) .

#### `readline`

The `readline` module enables and provides an interface to the GNU readline library on UNIX. This library extends Python’s interactive mode with command history, command completion, and advanced editing capabilities. These features are also extended to functions such as `raw_input()` and `input()`.

The `readline` module enables the following key bindings when running interactively:

Key(s) | Description
--- | ---
Ctrl+a | Moves to the start of the line.
Ctrl+b | Moves back one character.
Esc b | Moves back one word.
Esc c | Capitalizes the current word.
Ctrl+d | Deletes the character under the cursor.
Esc d | Kills to the end of the current word.
Del | Deletes the character to the left of the cursor.
Esc Del | Kills to the start of the previous word.
Ctrl+e | Moves to the end of the line.
Ctrl+f | Moves forward one character.
Esc f | Moves forward one word.
Ctrl+k | Kills the text to the end of the line.
Ctrl+l | Clears the screen.
Esc l | Converts the current word to lowercase.
Ctrl+n | Moves down through the history list.
Ctrl+p | Moves up through the history list.
Ctrl+r | Reverses incremental search through the history.
Ctrl+t | Transposes characters.
Esc t | Transposes words.
Esc u | Converts the current word to uppercase.
Ctrl+w | Kills from the cursor to the previous whitespace.
Ctrl+y | Yanks back the most recently killed text.
Esc y | Rotates the kill-ring and yanks the new top.
Esc < | Goes to the first line in history.
Esc > | Goes to the last line in history.

##### Notes

- Key sequences involving Esc are sometimes available using the Meta key.

- Many commands accept a numeric argument that’s entered by first typing Esc `nnn` . For example, typing Esc `5 0` Ctrl+f moves forward 50 characters.

- The `readline` module is an optional Python feature. If you’re installing from source and want to use the `readline` module, you’ll need to enable it by following the directions given in the distribution (these vary by Python version).

? See Also `rlcompleter` (http://www.python.org/doc/lib/module-rlcompleter.html).

#### `resource`

The `resource` module is used to measure and control the system resources used by a program on UNIX systems. Resource usage is limited using the `setrlimit()` function. Each resource is controlled by a soft limit and a hard limit. The soft limit is the current limit, and may be lowered or raised by a process over time. The hard limit can be lowered to any value greater than the soft limit, but never raised (except by the superuser).

    getrlimit(resource)

Returns a tuple (`soft` , `hard` ) with the current soft and hard limits of a resource. `resource` is one of the following symbolic constants:

Constant | Description
--- | ---
`RLIMIT_CORE` | The maximum core file size (in bytes).
`RLIMIT_CPU` | The maximum CPU time (in seconds). If exceeded, a `SIGXCPU` signal is sent to the process.
`RLIMIT_FSIZE` | The maximum file size that can be created.
`RLIMIT_DATA` | The maximum size (in bytes) of the process heap.
`RLIMIT_STACK` | The maximum size (in bytes) of the process stack.
`RLIMIT_RSS` | The maximum resident set size.
`RLIMIT_NPROC` | The maximum number of processes that can be created.
`RLIMIT_NOFILE` | The maximum number of open file descriptors.
`RLIMIT_OFILE` | The BSD name for `RLIMIT_NOFILE`.
`RLIMIT_MEMLOC` | The maximum memory size that can be locked in memory.
`RLIMIT_VMEM` | The largest area of mapped memory that can be used.
`RLIMIT_AS` | The maximum area (in bytes) of address space that can be used.

    setrlimit(resource, limits)

Sets new limits for a resource. `limits` is a tuple (`soft`, `hard` ) of two integers describing the new limits. A value of `-1` can be used to specify the maximum possible upper limit.

    getrusage(who)

This function returns a large tuple that describes the resources consumed by either the current process or its children. `who` is one of the following values:

Value | Description
--- | ---
`RUSAGE_SELF` | Information about the current process
`RUSAGE_CHILDREN` | Information about child processes
`RUSAGE_BOTH` | Information about both current and child processes

The returned tuple contains system resource-usage data in the following order:

Offset | Resource
--- | ---
`0` | Time in user mode (float)
`1` | Time in system mode (float)
`2` | Maximum resident set size (pages)
`3` | Shared memory size (pages)
`4` | Unshared memory size (pages)
`5` | Unshared stack size (pages)
`6` | Page faults not requiring I/O
`7` | Page faults requiring I/O
`8` | Number of swapouts
`9` | Block input operations
`10` | Block output operations
`11` | Messages sent
`12` | Messages received
`13` | Signals received
`14` | Voluntary context switches
`15` | Involuntary context switches

    getpagesize()

Returns the number of bytes in a system page.

##### Exception

    error

Exception raised for unexpected failures of the `getrlimit()` and `setrlimit()` system calls.

##### Note

- Not all resource names are available on all systems.

? See Also UNIX man pages for `getrlimit(2)`.

#### `shutil`

The `shutil` module is used to perform high-level file operations such as copying, removing, and renaming.

    copyfile(src, dst)

Copies the contents of `src` to `dst` .

    copymode(src, dst)

Copies the permission bits from `src` to `dst` .

    copystat(src, dst)

Copies the permission bits, last access time, and last modification time from `src` to `dst` . The contents, owner, and group of `dst` are unchanged.

    copy(src, dst)

Copies the file `src` to the file or directory `dst` , retaining file permissions.

    copy2(src, dst

Like `copy()`, but also copies the last access and modification times.

    copytree(src, dst [, symlinks])

Recursively copies an entire directory tree rooted at `src` . The destination directory `dst` will be created (and should not already exist). Individual files are copied using `copy2()`. If `symlinks` is true, symbolic links in the source tree are represented as symbolic links in the new tree. If `symlinks` is false or omitted, the contents of linked files are copied to the new directory tree. Errors are reported to standard output.

    rmtree(path [, ignore_errors [, onerror]])

Deletes an entire directory tree. If `ignore_errors` is true, errors will be ignored. Otherwise, errors are handled by the `onerror` function (if supplied). This function must accept three parameters (`func` , `path` , `excinfo` ), where `func` is the function that caused the error (`os.remove()` or `os.rmdir()`), `path` is the pathname passed to the function, and `excinfo` is the exception information returned by `sys.exc_info()`. If an error occurs and `onerror` is omitted, an exception is raised.

##### Note

- On MacOS, the resource fork is ignored on file copies.

? See Also os.path (193), macostools (176).

#### `signal`

The `signal` module is used to write signal handlers in Python. Signals usually correspond to asychronous events that are sent to a program due to the expiration of a timer, arrival of incoming data, or some action performed by a user. The signal interface emulates that of UNIX, although the module is supported on other platforms.

    alarm(time)

If `time` is nonzero, schedules a `SIGALRM` signal to be sent to the program in `time` seconds.Any previously scheduled alarm is canceled. If `time` is zero, no alarm is scheduled and any previously set alarm is canceled. Returns the number of seconds remaining before any previously scheduled alarm, or zero if no alarm was scheduled. UNIX.

    getsignal(signalnum)

Returns the signal handler for signal `signalnum` . The returned object is a callable Python object. The function may also return `SIG_IGN` for an ignored signal, `SIG_DFL` for the default signal handler, or `None` if the signal handler was not installed from the Python interpreter.

    pause()

Goes to sleep until the next signal is received. UNIX.

    signal(signalnum, handler)

Sets a signal handler for signal `signalnum` to the function `handler` . `handler` must be a callable Python object taking two arguments: the signal number and frame object. `SIG_IGN` or `SIG_DFL` can also be given to ignore a signal or use the default signal handler, respectively. The return value is the previous signal handler, `SIG_IGN`, or `SIG_DFL`. When threads are enabled, this function can only be called from the main thread. Otherwise, a `ValueError` exception is raised.

Individual signals are identified using symbolic constants of the form `SIG*`. These names correspond to integer values that are machine-specific. Typical values are as follows:

Signal Name | Description
--- | ---
`SIGABRT` | Abnormal termination
`SIGALRM` | Alarm
`SIGBUS` | Bus error
`SIGCHLD` | Change in child status
`SIGCLD` | Change in child status
`SIGCONT` | Continue
`SIGFPE` | Floating-point error
`SIGHUP` | Hangup
`SIGILL` | Illegal instruction
`SIGINT` | Terminal interrupt character
`SIGIO` | Asynchronous I/O
`SIGIOT` | Hardware fault
`SIGKILL` | Terminate
`SIGPIPE` | Write to pipe, no readers
`SIGPOLL` | Pollable event
`SIGPROF` | Profiling alarm
`SIGPWR` | Power failure
`SIGQUIT` | Terminal quit character
`SIGSEGV` | Segmentation fault
`SIGSTOP` | Stop
`SIGTERM` | Termination
`SIGTRAP` | Hardware fault
`SIGTSTP` | Terminal stop character
`SIGTTIN` | Control TTY
`SIGTTOU` | Control TTY
`SIGURG` | Urgent condition
`SIGUSR1` | User defined
`SIGUSR2` | User defined
`SIGVTALRM` | Virtual time alarm
`SIGWINCH` | Window size change
`SIGXCPU` | CPU limit exceeded
`SIGXFSZ` | File size limit exceeded

In addition, the module defines the following variables:

Variable | Description
--- | ---
`SIG_DFL` | Signal handler that invokes the default signal handler
`SIG_IGN` | Signal handler that ignores a signal
`NSIG` | One more than the highest signal number

##### Example

The following example illustrates a timeout on establishing a network connection:

    import signal, socket
    def handler(signum, frame):
         print 'Timeout!'
         raise IOError, 'Host not responding.'
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    signal.signal(signal.SIGALRM, handler)
    signal.alarm(5)                       # 5-second alarm
    sock.connect('www.python.org', 80)  # Connect
    signal.alarm(0)                       # Clear alarm

##### Notes

- Signal handlers remain installed until explicitly reset, with the exception of `SIGCHLD` (whose behavior is implementation-specific).

- It’s not possible to temporarily disable signals.

- Signals are only handled between the atomic instructions of the Python interpreter. The delivery of a signal can be delayed by long-running calculations written in C (as might be performed in an extension module).

- If a signal occurs during an I/O operation, the I/O operation may fail with an exception. In this case, the `errno` value is set to `errno` `.EINTR` to indicate an interrupted system call.

- Certain signals such as `SIGSEGV` cannot be handled from Python.

- Python installs a small number of signal handlers by default. `SIGPIPE` is ignored, `SIGINT` is translated into a `KeyboardInterrupt` exception, and `SIGTERM` is caught in order to perform cleanup and invoke `sys.exitfunc`.

- Extreme care is needed if signals and threads are used in the same program. Currently, only the main thread of execution can set new signal handlers or receive signals.

- Signal handling on Windows and Macintosh is of only limited functionality. The number of supported signals is extremely limited on these platforms.

? See Also thread (219), errno (156).

#### `stat`

The `stat` module defines constants and functions for interpreting the results of `os.stat()`, `os.fstat()` and `os.lstat()`. These functions return a 10-tuple containing file information. The following variables define the indices within the tuple for certain items:

Variable | Description
--- | ---
`ST_MODE` | Inode protection mode
`ST_INO` | Inode number
`ST_DEV` | Device the inode resides on
`ST_NLINK` | Number of links to the inode
`ST_UID` | User ID of the owner
`ST_GID` | Group ID of the owner
`ST_SIZE` | File size in bytes
`ST_ATIME` | Time of last access
`ST_MTIME` | Time of last modification
`ST_CTIME` | Time of last status change

The following functions can be used to test file properties given the mode value returned using `os.stat(``path` `)[stat.ST_MODE]`:

Function | Description
--- | ---
`S_ISDIR(``mode` `)` | Returns nonzero if `mode` is from a directory.
`S_ISCHR(``mode` `)` | Returns nonzero if `mode` is from a character-special device file.
`S_ISBLK(``mode` `)` | Returns nonzero if `mode` is from a block-special device file.
`S_ISREG(``mode` `)` | Returns nonzero if `mode` is from a regular file.
`S_ISFIFO(``mode` `)` | Returns nonzero if `mode` is from a FIFO (named pipe).
`S_ISLNK(``mode` `)` | Returns nonzero if `mode` is from a symbolic link.
`S_ISSOCK(``mode` `)` | Returns nonzero if `mode` is from a socket.
`S_IMODE(``mode` `)` | Returns the portion of the file’s mode that can be set by `os.chmod()`. This is the file’s permission bits, sticky bit, set-group-ID, and set-user-ID bits.
`S_IFMT(``mode` `)` | Returns the portion of the file’s mode that describes the file type (used by the `S_IS*()` functions above).

##### Note

- Much of the functionality in this module is also provided in a more portable form by the `os.path` module.

? See Also os (180), os.path (193), statvfs (203).

#### `statvfs`

The `statvfs` module defines constants used to interpret the result of the `os.statvfs()` function on UNIX. The constants defined in this module define the indices into the tuple returned by `os.statvfs()` for specific information.

Constant | Description
--- | ---
`F_BSIZE` | Preferred filesystem block size
`F_FRSIZE` | Fundamental filesystem block size
`F_BLOCKS` | Total number of blocks in the filesystem
`F_BFREE` | Total number of free blocks
`F_BAVAIL` | Free blocks available to a non-superuser
`F_FILES` | Total number of file nodes
`F_FFREE` | Total number of free file nodes
`F_FAVAIL` | Free nodes available to a non-superuser
`F_FLAG` | Flags (system-dependent)
`F_NAMEMAX` | Maximum filename length

? See Also os (180), stat (202).

#### `tempfile`

The `tempfile` module is used to generate temporary filenames and files:

    mktemp([suffix])

Returns a unique temporary filename. `suffix` is an optional file suffix to append to the filename. This function only generates a unique filename and doesn’t actually create or open a temporary file.

    gettempprefix()

Returns the prefix used to generate temporary files. Does not include the directory in which the file would reside.

    TemporaryFile([mode [, bufsize [, suffix]]])

Creates a temporary file and returns a file-like object that supports the same methods as an ordinary file object. `mode` is the file mode and defaults to `'w+b'`. `bufsize` specifies the buffering behavior and has the same meaning as for the `open()` function. `suffix` is the suffix to append to the filename (if any). The object returned by this function is only a wrapper around a built-in file object that’s accessible in the file attribute. The file created by this function is automatically destroyed when the temporary file object is destroyed.

Two global variables are used to construct temporary names. They can be assigned to new values if desired. Their default values are system-dependent.

Variable | Description
--- | ---
`tempdir` | The directory in which filenames returned by `mktemp()` reside.
`template` | The prefix of filenames generated by `mktemp()`. A string of decimal digits is added to `template` to generate unique filenames.

#### `termios`

The `termios` module provides a POSIX-style interface for controlling the behavior of TTYs and other serial communication devices on UNIX systems.All the functions operate on integer file descriptors such as those returned by the `os.open()` function or the `fileno()` method of a file object. In addition, the module relies on a large collection of constants that are defined in the `TERMIOS` module, which should also be loaded.

    tcgetattr(fd)

Returns a list `[``iflag` `,` `oflag` `,` `cflag` `,` `lflag` `,` `ispeed` `,` `ospeed` `,` `cc` `]` of TTY attributes for a file descriptor `fd` . The meaning of these fields is as follows:

Field | Description
--- | ---
`iflag` | Input modes (integer)
`oflag` | Output modes (integer)
`cflag` | Control modes (integer)
`lflag` | Local modes (integer)
`ispeed` | Input speed (integer)
`ospeed` | Output speed (integer)
`cc` | A list of control characters (as strings)

The mode fields `iflag` , `oflag` , `cflag` , and `lflag` are bit fields that are interpreted using constants in `TERMIOS`.

##### Input Modes

Mode | Description
--- | ---
`TERMIOS.IGNBRK` | Ignore break condition on input.
`TERMIOS.BRKINT` | Generate `SIGINT` signal on break if `IGNBRK` is not set.
`TERMIOS.IGNPAR` | Ignore framing and parity errors.
`TERMIOS.PARMRK` | Mark characters with a parity error.
`TERMIOS.INPCK` | Enable input parity checking.
`TERMIOS.ISTRIP` | Strip off the eighth bit.
`TERMIOS.INLCR` | Translate newlines to carriage returns.
`TERMIOS.IGNCR` | Ignore carriage returns.
`TERMIOS.ICRNL` | Translate carriage returns to newlines.
`TERMIOS.IUCLC` | Map uppercase characters to lowercase.
`TERMIOS.IXON` | Enable XON/XOFF flow control on output.
`TERMIOS.IXANY` | Enable any character to restart output.
`TERMIOS.IXOFF` | Enable XON/XOFF flow control on input.
`TERMIOS.IXMAXBEL` | Ring bell when the input queue is full.

##### Output Modes

Mode | Description
--- | ---
`TERMIOS.OPOST` | Implementation-defined output processing.
`TERMIOS.OLCUC` | Map lowercase to uppercase on output.
`TERMIOS.ONLCR` | Map newlines to carriage returns.
`TERMIOS.OCRNL` | Map carriage returns to newlines.
`TERMIOS.ONLRET` | Don’t output carriage returns.
`TERMIOS.OFILL` | Send fill characters for delay.
`TERMIOS.OFDEL` | Set the fill character to ASCII DEL.
`TERMIOS.NLDLY` | Newline delay mask.Values are `NL0` and `NL1`.
`TERMIOS.CRDLY` | Carriage return delay mask.Values are `CR0`, `CR1`, `CR2`, or `CR3`.
`TERMIOS.TABDLY` | Horizontal tab delay mask: `TAB0`, `TAB1`, `TAB2`, `TAB3`, or `XTABS`.
`TERMIOS.BSDLY` | Backspace delay mask: `BS0` or `BS1`.
`TERMIOS.VTDLY` | Vertical tab delay mask: `VT0` or `VT1`.
`TERMIOS.FFDLY` | Formfeed delay mask: `FF0` or `FF1`.

##### Control Modes

Mode | Description
--- | ---
`TERMIOS.CSIZE` | Character size mask: `CS5`, `CS6`, `CS7`, or `CS8`.
`TERMIOS.CSTOPB` | Set two stop bits.
`TERMIOS.CREAD` | Enable receiver.
`TERMIOS.PARENB` | Enable parity generation and checking.
`TERMIOS.PARODD` | Use odd parity.
`TERMIOS.HUPCL` | Lower modem control lines when device is closed.
`TERMIOS.CLOCAL` | Ignore modem control lines.
`TERMIOS.CRTSCTS` | Flow control.

##### Local Modes

Mode | Description
--- | ---
`TERMIOS.ISIG` | Generate corresponding signals when `INTR`, `QUIT`, `SUSP`, or `DSUSP` characters are received.
`TERMIOS.ICANON` | Enable canonical mode.
`TERMIOS.XCASE` | Perform case conversion if `ICANON` is set.
`TERMIOS.ECHO` | Echo input characters.
`TERMIOS.ECHOE` | If `ICANON` is set, the `ERASE` character erases the preceding input character. `WERASE` erases the preceding word.
`TERMIOS.ECHOK` | If `ICANON` is set, the `KILL` character erases the current line.
`TERMIOS.ECHONL` | If `ICANON` is set, echo newline (NL) characters.
`TERMIOS.ECHOCTL` | If `ECHO` is set, echo control characters as `^X`.
`TERMIOS.ECHOPRT` | Print characters as they’re erased.
`TERMIOS.ECHOKE` | Echo `KILL` by erasing each character one at a time.
`TERMIOS.FLUSHO` | Output is being flushed.
`TERMIOS.NOFLSH` | Disable flushing the input/output queues when generating the `SIGINT` and `SIGQUIT` signals.
`TERMIOS.TOSTOP` | Send the `SIGTTOU` signal to the process group of a background process that writes to its controlling terminal.
`TERMIOS.PENDIN` | Reprint all characters in the input queue when the next character is typed.
`TERMIOS.IEXTEN` | Enable implementation-defined input processing.

##### Speeds

Speeds are defined by constants such as `TERMIOS.B0`, `TERMIOS.B50`, `TERMIOS.B75`, and `TERMIOS.B230400` indicating a baud rate. The available values are implementation-specific and defined in `TERMIOS`.

##### Control Characters

The following symbols in `TERMIOS` are indices into the `cc` list. This can be used to changed various key bindings.

Character | Description
--- | ---
`TERMIOS.VINTR` | Interrupt character (typically Ctrl+C)
`TERMIOS.VQUIT` | Quit
`TERMIOS.VERASE` | Erase the preceding character (typically Del)
`TERMIOS.VWERASE` | Erase the preceding word (Ctrl+w)
`TERMIOS.VKILL` | Delete the entire line
`TERMIOS.VREPRINT` | Reprint all characters that have not been read yet
`TERMIOS.VEOF` | End of file (Ctrl+D)
`TERMIOS.VNL` | Line delimiter (line feed)
`TERMIOS.VSUSP` | Suspend (Ctrl+Z)
`TERMIOS.VSTOP` | Stop output (Ctrl+S)
`TERMIOS.VSTART` | Start output (Ctrl+Q)

    tcsetattr(fd, when, attributes)

Sets the TTY attributes for a file descriptor `fd` . `attributes` is a list in the same form as returned by `tcgetattr()`. The `when` argument determines when the changes take effect:

Argument | Description
--- | ---
`TERMIOS.TCSANOW` | Changes take place immediately
`TERMIOS.TCSADRAIN` | After transmitting queued output
`TERMIOS.TCSAFLUSH` | After transmitting queued output and discarding queued input

    tcsendbreak(fd, duration)

Sends a break on file descriptor `fd` . A duration of zero sends a break for approximately 0.25–0.5 seconds. A nonzero duration is implementation-defined.

    tcdrain(fd)

Waits until all output written to file descriptor `fd` has been transmitted.

    tcflush(fd, queue)

Discards queued data on file descriptor `fd` . `queue` determines which data to discard:

Queue | Description
--- | ---
`TERMIOS.TCIFLUSH` | Input queue
`TERMIOS.TCOFLUSH` | Output queue
`TERMIOS.TCIOFLUSH` | Both queues

    tcflow(fd, action)

Suspends or resumes input or output on file descriptor `fd` . `action` is one of the following:

Action | Description
--- | ---
`TERMIOS.TCOOFF` | Suspends output
`TERMIOS.TCOON` | Restarts output
`TERMIOS.TCIOFF` | Suspends input
`TERMIOS.TCION` | Restarts input

##### Example

The following function prompts for a password with local echoing turned off:

    def getpass():
           import termios, TERMIOS, sys
           fd = sys.stdin.fileno()
           tc = termios.tcgetattr(fd)
           old = tc[3] & TERMIOS.ECHO
           tc[3] = tc[3] & ~TERMIOS.ECHO          # Disable echo
           try:
               termios.tcsetattr(fd, TERMIOS.TCSADRAIN, tc)
               passwd = raw_input('Password: ')
           finally:
               tc[3] = tc[3] | old               # Restore old echo setting
               termios.tcsetattr(fd, TERMIOS.TCSADRAIN, tc)
           return passwd

? See Also tty (211), getpass (167), signal (200).

#### `time`

The `time` module provides various time-related functions. In Python, time is measured as the number of seconds since the “epoch.” The epoch is the beginning of time (the point at which time = 0 seconds). The epoch is January 1, 1970 on UNIX and Windows, and January 1, 1900 on the Macintosh.

The following variables are defined:

    accept2dyear

A Boolean value that indicates whether two-digit years are accepted. Normally this is true, but it’s set to false if the environment variable `$PYTHONY2K` is set to a non-empty string. The value can be changed manually as well.

    altzone

The timezone used during daylight saving time (DST), if applicable.

    daylight

Sets to a nonzero value if a DST timezone has been defined.

    timezone

The local (non–DST) timezone.

    tzname

A tuple containing the name of the local timezone and the name of the local daylight saving timezone (if defined).

The following functions can be used:

    asctime([tuple])

Converts a tuple representing a time as returned by `gmtime()` or `localtime()` to a string of the form `'Mon Jul 16 14:45:23 2001'`. If no arguments are supplied, the current time is used.

    clock()

Returns the current CPU time in seconds as a floating-point number.

    ctime([secs])

Converts a time expressed in seconds since the epoch to a string representing local time. `ctime(``secs` `)` is the same as `asctime(localtime(``secs` `))`. If `secs` is omitted, the current time is used.

    gmtime([secs])

Converts a time expressed in seconds since the epoch to a time tuple in UTC (Coordinated Universal Time, a.k.a. Greenwich Mean Time). The returned tuple consists of nine integers of the form (`year` `,` `month` `,` `day` `,` `hour` `,` `minute` `,` `second` `,` `weekday` `,` `day` `,` `dst` ). The following numerical ranges are used for tuple elements:

Element | Value
--- | ---
`year` | A four-digit value such as `2002`
`month` | `1-12`
`day` | `1-31`
`hour` | `0-23`
`minute` | `0-59`
`second` | `0-61`
`weekday` | `0-6` (`0` =Monday)
`day` | `1-366`
`dst` | `-1`, `0`, `1`

The `dst` field is `1` if daylight saving time is in effect, `0` if not, and `-1` if no information is available. If `secs` is omitted, the current time is used.

    localtime([secs])

Returns a time tuple such as `gmtime()`, but corresponding to the local timezone. If `secs` is omitted, the current time is used.

    mktime(tuple)

This function takes a time tuple representing a time in the local timezone (in the same format as returned by `localtime()`) and returns a floating-point number representing the number of seconds since the epoch. An `OverflowError` exception is raised if the input value is not a valid time.

    sleep(secs)

Puts the current process to sleep for `secs` seconds. `secs` is a floating-point number.

    strftime(format [, tuple])

Converts a tuple representing a time as returned by `gmtime()` or `localtime()` to a string. `format` is a format string in which the following format codes can be embedded:

Directive | Meaning
--- | ---
`%a` | Locale’s abbreviated weekday name
`%A` | Locale’s full weekday name
`%b` | Locale’s abbreviated month name
`%B` | Locale’s full month name
`%c` | Locale’s appropriate date and time representation
`%d` | Day of the month as a decimal number [`01-31`]
`%H` | Hour (24-hour clock) as a decimal number [`00-23`]
`%I` | Hour (12-hour clock) as a decimal number [`01-12`]
`%j` | Day of the year as a decimal number [`001-366`]
`%m` | Month as a decimal number [`01-12`]
`%M` | Minute as a decimal number [`00-59`]
`%p` | Locale’s equivalent of either `AM` or `PM`
`%S` | Seconds as a decimal number [`00-61`]
`%U` | Week number of the year [`00-53`] (Sunday as first day)
`%w` | Weekday as a decimal number [`0` (Sunday) `-6`]
`%W` | Week number of the year (Monday as first day)
`%x` | Locale’s appropriate date representation
`%X` | Locale’s appropriate time representation
`%y` | Year without century as a decimal number [`00-99`]
`%Y` | Year with century as a decimal number
`%Z` | Timezone name (or empty string if no timezone exists)
`%%` | The `%` character

The format codes can include a width and precision in the same manner as used with the `%` operator on strings. If `tuple` is omitted, the time tuple corresponding to the current time is used.

    strptime(string [, format])

Parses a string representing a time and returns a time tuple of the same form as returned by `localtime()` or `gmtime()`. The `format` parameter uses the same specifiers as used by `strftime()` and defaults to `'%a %b %d %H:%M:%S %Y'`. This is the same format as produced by the `ctime()` function. If the string cannot be parsed, a `ValueError` exception is raised.

    time()

Returns the current time as the number of seconds since the epoch in UTC (Coordinated Universal Time).

##### Notes

- When two-digit years are accepted, they’re converted to four-digit years according to the POSIX X/Open standard, where the values `69-99` are mapped to `1969-1999` and the values `0-68` are mapped to `2000-2068`.

- The functions in this module are not intended to handle dates and times far in the past or future. In particular, dates before the epoch are illegal, as are dates beyond the maximum time (231 seconds since the epoch on many machines).

- In versions of Python prior to 2.1, the optional arguments to `asctime()`, `ctime()`, `gmtime()`, `localtime()`, and `strftime()` were required. If you’re concerned with backward compatibility, remember to supply these arguments.

- The range of values for `secs` is `0` to `61` in order to account for leap seconds.

? See Also locale (172).

#### `tty`

The `tty` module provides functions for putting a TTY into cbreak and raw modes on UNIX systems. Raw mode forces a process to receive every character on a TTY with no interpretation by the system. Cbreak mode enables system processing for special keys such as the interrupt and quit keys (which generate signals).

    setraw(fd [, when])

Changes the mode of the file descriptor `fd` to raw mode. `when` specifies when the change occurs and is `TERMIOS.TCSANOW`, `TERMIOS.TCSADRAIN`, or `TERMIOS.TCSAFLUSH` (the default).

    setcbreak(fd [, when])

Changes the mode of file descriptor `fd` to cbreak mode. `when` has the same meaning as in `setraw()`.

##### Note

- Requires the `termios` module.

? See Also termios (204).

#### `_winreg`

The `_winreg` module provides a low-level interface to the Windows Registry. The Registry is a large hierarchical tree in which each node is called a key. The children of a particular key are known as subkeys and may contain additional subkeys or values. For example, the setting of the Python `sys.path` variable is typically contained in the Registry as follows:

    \HKEY_LOCAL_MACHINE\Software\Python\PythonCore\2.0\PythonPath

In this case, `Software` is a subkey of `HKEY_LOCAL_MACHINE`, `Python` is a subkey of `Software`, and so forth. The value of the `PythonPath` key contains the actual path setting.

Keys are accessed through open and close operations. Open keys are represented by special handles (which are wrappers around the integer handle identifiers normally used by Windows).

    CloseKey(key)

Closes a previously opened registry key with handle `key` .

    ConnectRegistry(computer_name, key)

Returns a handle to a predefined registry key on another computer. `computer_name` is the name of the remote machine as a string of the form `\\``computername` . If `computer_name` is `None`, the local registry is used. `key` is a predefined handle such as `HKEY_CURRENT_USER` or `HKEY_USERS`. Raises `EnvironmentError` on failure.

    CreateKey(key, sub_key)

Creates or opens a key and returns a handle. `key` is a previously opened key or a predefined key defined by the `HKEY_*` constants. `sub_key` is the name of the key that will be opened or created. If `key` is a predefined key, `sub_key` may be `None`, in which case `key` is returned.

    DeleteKey(key, sub_key)

Deletes `sub_key` . `key` is an open key or one of the predefined `HKEY_*` constants. `sub_key` is a string that identifies the key to delete. `sub_key` must not have any sub-keys or `EnvironmentError` is raised.

    DeleteValue(key, value)

Deletes a named value from a registry key. `key` is an open key or one of the predefined `HKEY_*` constants. `value` is a string containing the name of the value to remove.

    EnumKey(key, index)

Returns the name of a subkey by index. `key` is an open key or one of the predefined `HKEY_*` constants. `index` is an integer that specifies the key to retrieve. If `index` is out of range, an `EnvironmentError` is raised.

    EnumValue(key, index)

Returns a value of an open key. `key` is an open key or a predefined `HKEY_*` constant. `index` is an integer specifying the value to retrieve. The function returns a tuple `(``name` `,` `data` `,` `type` `)` in which `name` is the value name, `data` is an object holding the value data, and `type` is an integer that specifies the type of the value data. The following type codes are currently defined:

Code | Description
--- | ---
`REG_BINARY` | Binary data
`REG_DWORD` | 32-bit number
`REG_DWORD_LITTLE_ENDIAN` | 32-bit little-endian number
`REG_DWORD_BIG_ENDIAN` | 32-bit number in big-endian format
`REG_EXPAND_SZ` | Null-terminated string with unexpanded references to environment variables
`REG_LINK` | Unicode symbolic link
`REG_MULTI_SZ` | Sequence of null-terminated strings
`REG_NONE` | No defined value type
`REG_RESOURCE_LIST` | Device driver resource list
`REG_SZ` | Null-terminated string

    FlushKey(key)

Writes the attributes of `key` to the Registry, forcing changes to disk. This function should only be called if an application requires absolute certainty that Registry data is stored on disk. Does not return until data is written. It is not necessary to use this function under normal circumstances.

    RegLoadKey(key, sub_key, filename)

Creates a subkey and stores registration information from a file into it. `key` is an open key or a predefined `HKEY_*` constant. `sub_key` is a string identifying the subkey to load. `filename` is the name of the file from which to load data. The contents of this file must be created with the `SaveKey()` function and the calling process must have the `SE_RESTORE_PRIVILEGE` for this to work. If `key` was returned by `ConnectRegistry()`, filename should be a path that’s relative to the remote computer.

    OpenKey(key, sub_key[, res [, sam]])

Opens a key. `key` is an open key or an `HKEY_*` constant. `sub_key` is a string identifying the subkey to open. `res` is a reserved integer that must be zero (the default). `sam` is an integer defining the security access mask for the key. The default is `KEY_READ`. Other possible values for `sam` :

- `KEY_ALL_ACCESS`

- `KEY_CREATE_LINK`

- `KEY_CREATE_SUB_KEY`

- `KEY_ENUMERATE_SUB_KEYS`

- `KEY_EXECUTE`

- `KEY_NOTIFY`

- `KEY_QUERY_VALUE`

- `KEY_READ`

- `KEY_SET_VALUE`

- `KEY_WRITE`

    OpenKeyEx()

Same as `OpenKey()`.

    QueryInfoKey(key)

Returns information about a key as a tuple `(``num_subkeys` `,` `num_values` `,` `last_modified` `)` in which `num_subkeys` is the number of subkeys, `num_values` is the number of values, and `last_modified` is a long integer containing the time of last modification. Time is measured from January 1, 1601, in units of 100 nanoseconds.

    QueryValue(key, sub_key)

Returns the unnamed value for a key as a string. `key` is an open key or an `HKEY_*` constant. `sub_key` is the name of the subkey to use, if any. If omitted, the function returns the value associated with `key` instead. This function returns the data for the first value with a null name. However, the type is returned (use `QueryValueEx` instead).

    QueryValueEx(key, value_name)

Returns a tuple (`value` `,` `type` ) containing the data and type for a key. `key` is an open key or `HKEY_*` constant. `value_name` is the name of the value to return. The returned type is one of the integer codes as described for the `EnumValue()` function.

    SaveKey(key, filename)

Saves `key` and all of its subkeys to a file. `key` is an open key or a predefined `HKEY_*` constant. `filename` must not already exist and should not include a filename extension. Furthermore, the caller must have backup privileges for the operation to succeed.

    SetValue(key, sub_key, type, value)

Sets the value of a key. `key` is an open key or `HKEY_*` constant. `sub_key` is the name of the subkey with which to associate the value. `type` is an integer type code, currently limited to `REG_SZ`. `value` is a string containing the value data. If `sub_key` does not exist, it is created. `key` must have been opened with `KEY_SET_VALUE` access for this function to succeed.

    SetValueEx(key, value_name, reserved, type, value)

Sets the value field of a key. `key` is an open key or an `HKEY_*` constant. `value_name` is the name of the value. `type` is an integer type code as described for the `EnumValue()` function. `value` is a string containing the new value. When setting the values of numeric types (for example, `REG_DWORD`), `value` is still a string containing the raw data. This string can be created using the `struct` module. `reserved` is currently ignored and can be set to anything (the value is not used).

#### `zipfile`

The `zipfile` module is used to manipulate files encoded in the popular ZIP format. The following functions are available:

    is_zipfile(filename)

Tests `filename` to see whether it’s a valid ZIP file. Returns `1` if `filename` is a ZIP file, `None` otherwise.

    ZipFile(filename [, mode [, compression]])

Opens a ZIP file `filename` and returns a `ZipFile` instance. `mode` is `'r'` to read from an existing file, `'w'` to truncate the file and write a new file, or `'a'` to append to an existing file. For `'a'` mode, if `filename` is an existing ZIP file, new files are added to it. If `filename` is not a ZIP file, the archive is simply appended to the end of the file. `compression` is the ZIP compression method used when writing to the archive and is one of `ZIP_STORED` or `ZIP_DEFLATED`. The default is `ZIP_STORED`.

    PyZipFile(filename [, mode[, compression]])

Opens a ZIP file like `ZipFile()`, but returns a special `PyZipFile` instance with one extra method `writepy()` that’s used to add Python source files to the archive.

    ZipInfo([filename [, date_time]])

Manually creates a new `ZipInfo` instance, used to contain information about an archive member. Normally, it’s not necessary to call this function except when using the `z` `.writestr()` method of a `ZipFile` instance (described below).

An instance `z` of `ZipFile` or `PyZipFile` supports the following methods and attributes:

    z.close()

Closes the archive file. This must be called in order to flush records to the ZIP file before program termination.

    z.getinfo(name)

Returns information about the archive member name as a `ZipInfo` instance (described below).

    z.infolist()

Returns a list of `ZipInfo` objects for all the members of the archive.

    z.namelist()

Returns a list of the archive member names.

    z.printdir()

Prints the archive directory to `sys.stdout`.

    z.read(name)

Reads archive contents for member `name` and returns the data as a string.

    z.testzip()

Reads all the files in the archive and verifies their CRC checksums. Returns the name of the first corrupted file or `None` if all files are intact.

    z.write(filename[, arcname[, compress_type]])

Writes `filename` to the archive with archive name `arcname` . `compress_type` is the compression parameter and is one of `ZIP_STORED` or `ZIP_DEFLATED`. By default, the compression parameter given to the `ZipFile()` or `PyZipFile()` function is used. The archive must be open in `'w'` or `'a'` mode for writes to work.

    z.writepy(pathname[, basename])

This method, available only with `PyZipFile` instances, is used to write Python source files (`*.py` files) to a ZIP archive and can be used to easily package Python applications for distribution. If `pathname` is a file, it must end with `.py`. In this case, one of the corresponding `.pyo`, `.pyc`, or `.py` files will be added (in that order). If `pathname` is a directory and the directory is not a Python package directory, all of the corresponding `.pyo`, `.pyc`, or `.py` files are added at the top level. If the directory is a package, the files are added under the package name as a file path. If any sub-directories are also package directories, they are added recursively. `basename` is used internally and is not normally specified.

    z.writestr(zinfo, bytes)

Writes a string of bytes to the archive. Information about the bytes is contained in the `ZipInfo` instance `zinfo` , which must minimally contain a filename, date, and time. The `ZipInfo()` function can be used to create a `ZipInfo` instance.

    z.debug

Debugging level in the range of `0` (no output) to `3` (most output).

`ZipInfo` instances returned by the `ZipInfo()`, `z` `.getinfo()`, and `z` `.infolist()` functions have the following attributes:

    zinfo.filename

Archive member name.

    zinfo.date_time

Tuple `(``year` `,``month` `,``day` `,``hours` `,``minutes` `,``seconds` `)` containing the last modification time. `month` and `day` are numbers in the range `1-12` and `1-31`, respectively. All other values start at `0`.

    zinfo.compress_type

Compression type for the archive member. Only `ZIP_STORED` and `ZIP_DEFLATED` are currently supported by this module.

    zinfo.comment

Archive member comment.

    zinfo.extra

Expansion field data, used to contain additional file attributes. The data stored here depends on the system that created the file.

    zinfo.create_system

Integer code describing the system that created the archive. Common values include those in the following table:

Value | Description
--- | ---
`0` | MS-DOS (FAT/VFAT/FAT32 filesystems)
`3` | UNIX
`7` | Macintosh
`10` | Windows NTFS

    zinfo.create_version

Integer PKZIP version code that created the ZIP archive.

    zinfo.extract_version

Minimum PKZIP version needed to extract the archive.

    zinfo.reserved

Reserved field. Currently set to `0`.

    zinfo.flag_bits

ZIP flag bits that describe the encoding of the data, including encryption and compression.

    zinfo.volume

Volume number of the file header.

    zinfo.internal_attr

Describes the internal structure of the archive contents. If the low-order bit is `1`, the data is ASCII text. Otherwise, binary data is assumed.

    zinfo.external_attr

External file attributes. Operating system dependent.

    zinfo.header_offset

Byte offset to the file header.

    zinfo.file_offset

Byte offset to the start of the file data.

    zinfo.CRC

CRC-32 checksum of the uncompressed file.

    zinfo.compress_size

Size of the compressed file data.

    zinfo.file_size

Size of the uncompressed file.

##### Notes

- This module requires the use of the `zlib` module.

- Detailed documentation about the internal structure of ZIP files can be found as a PKZIP Application Note at http://www.pkware.com/appnote.html.

#### `zlib`

The `zlib` module supports data compression by providing access to the zlib library.

    adler32(string [, value])

Computes the Adler-32 checksum of `string` . `value` is used as the starting value (which can be used to compute a checksum over the concatenation of several strings). Otherwise, a fixed default value is used.

    compress(string [, level])

Compresses the data in `string` , where `level` is an integer from `1` to `9` controlling the level of compression. `1` is the least (fastest) compression and `9` is the best (slowest) compression. The default value is `6`. Returns a string containing the compressed data or raises `error` if an error occurs.

    compressobj([level])

Returns a compression object. `level` has the same meaning as in the `compress()` function.

    crc32(string [, value])

Computes a CRC checksum of `string` . If `value` is present, it’s used as the starting value of the checksum. Otherwise, a fixed value is used.

    decompress(string [, wbits [, buffsize]])

Decompresses the data in `string` . `wbits` controls the size of the window buffer and `buffsize` is the initial size of the output buffer. Raises `error` if an error occurs.

    decompressobj([wbits])

Returns a compression object. The `wbits` parameter controls the size of the window buffer.

A compression object `c` has the following methods:

    c.compress(string)

Compresses `string` . Returns a string containing compressed data for at least part of the data in `string` . This data should be concatenated to the output produced by earlier calls to `c` `.compress()` to create the output stream. Some input data may be stored in internal buffers for later processing.

    c.flush([mode])

Compresses all pending input and returns a string containing the remaining compressed output. `mode` is `Z_SYNC_FLUSH`, `Z_FULL_FLUSH`, or `Z_FINISH` (the default). `Z_SYNC_FLUSH` and `Z_FULL_FLUSH` allow further compression and are used to allow partial error recovery on decompression. `Z_FINISH` terminates the compression stream.

A decompression object `d` has the following methods:

    d.decompress(string)

Decompresses `string` and returns a string containing uncompressed data for at least part of the data in `string` . This data should be concatenated with data produced by earlier calls to `decompress()` to form the output stream. Some input data may be stored in internal buffers for later processing.

    d.flush()

All pending input is processed, and a string containing the remaining uncompressed output is returned. The decompression object cannot be used again after this call.

##### Exception

    error

Exception raised on compression and decompression errors.

##### Note

- The zlib library is available at http://www.cdrom.com/pub/infozip/zlib.

? See Also gzip (171).

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.