This is /home/pdm/install/Python-2.1/Doc/lib/python-lib.info, produced
by makeinfo version 4.0 from lib.texi.

   April 15, 2001		2.1


File: python-lib.info,  Node: PyZipFile Objects,  Next: ZipInfo Objects,  Prev: ZipFile Objects,  Up: zipfile

PyZipFile Objects
-----------------

   The `PyZipFile' constructor takes the same parameters as the
`ZipFile' constructor.  Instances have one method in addition to those
of `ZipFile' objects.

`writepy(pathname[, basename])'
     Search for files `*.py' and add the corresponding file to the
     archive.  The corresponding file is a `*.pyo' file if available,
     else a `*.pyc' file, compiling if necessary.  If the pathname is a
     file, the filename must end with `.py', and just the
     (corresponding `*.py[co]') file is added at the top level (no path
     information).  If it is a directory, and the directory is not a
     package directory, then all the files `*.py[co]' are added at the
     top level.  If the directory is a package directory, then all
     `*.py[oc]' are added under the package name as a file path, and if
     any subdirectories are package directories, all of these are added
     recursively.  BASENAME is intended for internal use only.  The
     `writepy()' method makes archives with file names like this:

              string.pyc                                # Top level name
              test/__init__.pyc                         # Package directory
              test/testall.pyc                          # Module test.testall
              test/bogus/__init__.pyc                   # Subpackage directory
              test/bogus/myfile.pyc                     # Submodule test.bogus.myfile


File: python-lib.info,  Node: ZipInfo Objects,  Prev: PyZipFile Objects,  Up: zipfile

ZipInfo Objects
---------------

   Instances of the `ZipInfo' class are returned by the `getinfo()' and
`infolist()' methods of `ZipFile' objects.  Each object stores
information about a single member of the ZIP archive.

   Instances have the following attributes:

`filename'
     Name of the file in the archive.

`date_time'
     The time and date of the last modification to to the archive
     member.  This is a tuple of six values:

     Index                              Value
     ------                             -----
     0                                  Year
     1                                  Month (one-based)
     2                                  Day of month (one-based)
     3                                  Hours (zero-based)
     4                                  Minutes (zero-based)
     5                                  Seconds (zero-based)

`compress_type'
     Type of compression for the archive member.

`comment'
     Comment for the individual archive member.

`extra'
     Expansion field data.  The  contains some comments on the internal
     structure of the data contained in this string.

`create_system'
     System which created ZIP archive.

`create_version'
     PKZIP version which created ZIP archive.

`extract_version'
     PKZIP version needed to extract archive.

`reserved'
     Must be zero.

`flag_bits'
     ZIP flag bits.

`volume'
     Volume number of file header.

`internal_attr'
     Internal attributes.

`external_attr'
     External file attributes.

`header_offset'
     Byte offset to the file header.

`file_offset'
     Byte offset to the start of the file data.

`CRC'
     CRC-32 of the uncompressed file.

`compress_size'
     Size of the compressed data.

`file_size'
     Size of the uncompressed file.


File: python-lib.info,  Node: readline,  Next: rlcompleter,  Prev: zipfile,  Up: Optional Operating System Services

GNU readline interface
======================

   This section was written by Skip Montanaro <skip@mojam.com>.
GNU readline support for Python.

   The `readline' module defines a number of functions used either
directly or from the `rlcompleter' module to facilitate completion and
history file read and write from the Python interpreter.

   The `readline' module defines the following functions:

`parse_and_bind(string)'
     Parse and execute single line of a readline init file.

`get_line_buffer()'
     Return the current contents of the line buffer.

`insert_text(string)'
     Insert text into the command line.

`read_init_file([filename])'
     Parse a readline initialization file.  The default filename is the
     last filename used.

`read_history_file([filename])'
     Load a readline history file.  The default filename is
     `~{}/.history'.

`write_history_file([filename])'
     Save a readline history file.  The default filename is
     `~{}/.history'.

`get_history_length()'
     Return the desired length of the history file.  Negative values
     imply unlimited history file size.

`set_history_length(length)'
     Set the number of lines to save in the history file.
     `write_history_file()' uses this value to truncate the history
     file when saving.  Negative values imply unlimited history file
     size.

`set_completer([function])'
     Set or remove the completer function.  The completer function is
     called as `FUNCTION(TEXT, STATE)', `for i in [0, 1, 2, ...]' until
     it returns a non-string.  It should return the next possible
     completion starting with TEXT.

`get_begidx()'
     Get the beginning index of the readline tab-completion scope.

`get_endidx()'
     Get the ending index of the readline tab-completion scope.

`set_completer_delims(string)'
     Set the readline word delimiters for tab-completion.

`get_completer_delims()'
     Get the readline word delimiters for tab-completion.

   See also:

   *Note rlcompleter:: Completion of Python identifiers at the
interactive prompt.

* Menu:

* Example 6::


File: python-lib.info,  Node: Example 6,  Prev: readline,  Up: readline

Example
-------

   The following example demonstrates how to use the `readline'
module's history reading and writing functions to automatically load
and save a history file named `.pyhist' from the user's home directory.
The code below would normally be executed automatically during
interactive sessions from the user's `PYTHONSTARTUP' file.

     import os
     histfile = os.path.join(os.environ["HOME"], ".pyhist")
     try:
         readline.read_history_file(histfile)
     except IOError:
         pass
     import atexit
     atexit.register(readline.write_history_file, histfile)
     del os, histfile


File: python-lib.info,  Node: rlcompleter,  Prev: readline,  Up: Optional Operating System Services

Completion function for GNU readline
====================================

   This section was written by Moshe Zadka <moshez@zadka.site.co.il>.
Python identifier completion for the GNU readline library.

   The `rlcompleter' module defines a completion function for the
`readline' module by completing valid Python identifiers and keywords.

   This module is UNIX-specific due to it's dependence on the
`readline' module.

   The `rlcompleter' module defines the `Completer' class.

   Example:

     >>> import rlcompleter
     >>> import readline
     >>> readline.parse_and_bind("tab: complete")
     >>> readline. <TAB PRESSED>
     readline.__doc__          readline.get_line_buffer  readline.read_init_file
     readline.__file__         readline.insert_text      readline.set_completer
     readline.__name__         readline.parse_and_bind
     >>> readline.

   The `rlcompleter' module is designed for use with Python's
interactive mode.  A user can add the following lines to his or her
initialization file (identified by the `PYTHONSTARTUP' environment
variable) to get automatic <Tab> completion:

     try:
         import readline
     except ImportError:
         print "Module readline not available."
     else:
         import rlcompleter
         readline.parse_and_bind("tab: complete")

* Menu:

* Completer Objects::


File: python-lib.info,  Node: Completer Objects,  Prev: rlcompleter,  Up: rlcompleter

Completer Objects
-----------------

   Completer objects have the following method:

`complete(text, state)'
     Return the STATEth completion for TEXT.

     If called for TEXT that doesn't include a period character (`.'),
     it will complete from names currently defined in `__main__',
     `__builtin__' and keywords (as defined by the `keyword' module).

     If called for a dotted name, it will try to evaluate anything
     without obvious side-effects (i.e., functions will not be
     evaluated, but it can generate calls to `__getattr__()') upto the
     last part, and find matches for the rest via the `dir()' function.


File: python-lib.info,  Node: Unix Specific Services,  Next: Python Debugger,  Prev: Optional Operating System Services,  Up: Top

Unix Specific Services
**********************

   The modules described in this chapter provide interfaces to features
that are unique to the UNIX operating system, or in some cases to some
or many variants of it.  Here's an overview:

* Menu:

* posix::
* pwd::
* grp::
* crypt::
* dl::
* dbm::
* gdbm::
* termios::
* TERMIOS::
* tty::
* pty::
* fcntl::
* pipes::
* posixfile::
* resource::
* nis::
* syslog::
* commands::


File: python-lib.info,  Node: posix,  Next: pwd,  Prev: Unix Specific Services,  Up: Unix Specific Services

The most common POSIX system calls
==================================

   The most common POSIX system calls (normally used via module `os').

   This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly
disguised UNIX interface).

   *Do not import this module directly.*  Instead, import the module
`os', which provides a _portable_ version of this interface.  On UNIX,
the `os' module provides a superset of the `posix' interface.  On
non-UNIX operating systems the `posix' module is not available, but a
subset is always available through the `os' interface.  Once `os' is
imported, there is _no_ performance penalty in using it instead of
`posix'.  In addition, `os'provides some additional functionality, such
as automatically calling `putenv()' when an entry in `os.environ' is
changed.

   The descriptions below are very terse; refer to the corresponding
UNIX manual (or POSIX documentation) entry for more information.
Arguments called PATH refer to a pathname given as a string.

   Errors are reported as exceptions; the usual exceptions are given for
type errors, while errors reported by the system calls raise `error' (a
synonym for the standard exception `OSError'), described below.

* Menu:

* Large File Support::
* Module Contents::


File: python-lib.info,  Node: Large File Support,  Next: Module Contents,  Prev: posix,  Up: posix

Large File Support
------------------

   This section was written by Steve Clift <clift@mail.anacapa.net>.
Several operating systems (including AIX, HPUX, Irix and Solaris)
provide support for files that are larger than 2 Gb from a C
programming model where `int' and `long' are 32-bit values. This is
typically accomplished by defining the relevant size and offset types
as 64-bit values. Such files are sometimes referred to as "large files".

   Large file support is enabled in Python when the size of an `off_t'
is larger than a `long' and the `long long' type is available and is at
least as large as an `off_t'. Python longs are then used to represent
file sizes, offsets and other values that can exceed the range of a
Python int. It may be necessary to configure and compile Python with
certain compiler flags to enable this mode. For example, it is enabled
by default with recent versions of Irix, but with Solaris 2.6 and 2.7
you need to do something like:

     CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \
             ./configure

   On large-file-capable Linux systems, this might work:

     CC="-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64"
     export CC
     ./configure


File: python-lib.info,  Node: Module Contents,  Prev: Large File Support,  Up: posix

Module Contents
---------------

   Module `posix' defines the following data item:

`environ'
     A dictionary representing the string environment at the time the
     interpreter was started. For example, `environ['HOME']' is the
     pathname of your home directory, equivalent to `getenv("HOME")' in
     C.

     Modifying this dictionary does not affect the string environment
     passed on by `execv()', `popen()' or `system()'; if you need to
     change the environment, pass `environ' to `execve()' or add
     variable assignments and export statements to the command string
     for `system()' or `popen()'.

     *Note:* The `os' module provides an alternate implementation of
     `environ' which updates the environment on modification.  Note
     also that updating `os.environ' will render this dictionary
     obsolete.  Use of the `os' for this is recommended over direct
     access to the `posix' module.

   Additional contents of this module should only be accessed via the
`os' module; refer to the documentation for that module for further
information.


File: python-lib.info,  Node: pwd,  Next: grp,  Prev: posix,  Up: Unix Specific Services

The password database
=====================

   The password database (`getpwnam()' and friends).

   This module provides access to the UNIX user account and password
database.  It is available on all UNIX versions.

   Password database entries are reported as 7-tuples containing the
following items from the password database (see `<pwd.h>'), in order:

Index                    Field                    Meaning
------                   -----                    -----
0                        `pw_name'                Login name
1                        `pw_passwd'              Optional encrypted
                                                  password
2                        `pw_uid'                 Numerical user ID
3                        `pw_gid'                 Numerical group ID
4                        `pw_gecos'               User name or comment
                                                  field
5                        `pw_dir'                 User home directory
6                        `pw_shell'               User command interpreter

   The uid and gid items are integers, all others are strings.
`KeyError' is raised if the entry asked for cannot be found.

   *Note:* In traditional UNIX the field `pw_passwd' usually contains a
password encrypted with a DES derived algorithm (see module `crypt').
However most modern unices use a so-called _shadow password_ system.
On those unices the field `pw_passwd' only contains a asterisk (`'*'')
or the letter `x' where the encrypted password is stored in a file
`/etc/shadow' which is not world readable.

   It defines the following items:

`getpwuid(uid)'
     Return the password database entry for the given numeric user ID.

`getpwnam(name)'
     Return the password database entry for the given user name.

`getpwall()'
     Return a list of all available password database entries, in
     arbitrary order.

   See also:

   *Note grp:: An interface to the group database, similar to this.


File: python-lib.info,  Node: grp,  Next: crypt,  Prev: pwd,  Up: Unix Specific Services

The group database
==================

   The group database (`getgrnam()' and friends).

   This module provides access to the UNIX group database.  It is
available on all UNIX versions.

   Group database entries are reported as 4-tuples containing the
following items from the group database (see `<grp.h>'), in order:

Index                    Field                    Meaning
------                   -----                    -----
0                        gr_name                  the name of the group
1                        gr_passwd                the (encrypted) group
                                                  password; often empty
2                        gr_gid                   the numerical group ID
3                        gr_mem                   all the group member's
                                                  user  names

   The gid is an integer, name and password are strings, and the member
list is a list of strings.  (Note that most users are not explicitly
listed as members of the group they are in according to the password
database.  Check both databases to get complete membership information.)

   It defines the following items:

`getgrgid(gid)'
     Return the group database entry for the given numeric group ID.
     `KeyError' is raised if the entry asked for cannot be found.

`getgrnam(name)'
     Return the group database entry for the given group name.
     `KeyError' is raised if the entry asked for cannot be found.

`getgrall()'
     Return a list of all available group entries, in arbitrary order.

   See also:

   *Note pwd:: An interface to the user database, similar to this.


File: python-lib.info,  Node: crypt,  Next: dl,  Prev: grp,  Up: Unix Specific Services

Function to check UNIX passwords
================================

   The `crypt()' function used to check UNIX passwords.  This module
was documented by Steven D. Majewski <sdm7g@virginia.edu>.
This section was written by Steven D. Majewski <sdm7g@virginia.edu>.
This section was written by Peter Funk <pf@artcom-gmbh.de>.
This module implements an interface to the `crypt(3)' routine, which is
a one-way hash function based upon a modified DES algorithm; see the
UNIX man page for further details.  Possible uses include allowing
Python scripts to accept typed passwords from the user, or attempting
to crack UNIX passwords with a dictionary.

`crypt(word, salt)'
     WORD will usually be a user's password as typed at a prompt or in
     a graphical interface.  SALT is usually a random two-character
     string which will be used to perturb the DES algorithm in one of
     4096 ways.  The characters in SALT must be in the set
     "[./a-zA-Z0-9]".  Returns the hashed password as a string, which
     will be composed of characters from the same alphabet as the salt
     (the first two characters represent the salt itself).

   A simple example illustrating typical use:

     import crypt, getpass, pwd
     
     def login():
         username = raw_input('Python login:')
         cryptedpasswd = pwd.getpwnam(username)[1]
         if cryptedpasswd:
             if cryptedpasswd == 'x' or cryptedpasswd == '*':
                 raise "Sorry, currently no support for shadow passwords"
             cleartext = getpass.getpass()
             return crypt.crypt(cleartext, cryptedpasswd[:2]) == cryptedpasswd
         else:
             return 1


File: python-lib.info,  Node: dl,  Next: dbm,  Prev: crypt,  Up: Unix Specific Services

Call C functions in shared objects
==================================

   This section was written by Moshe Zadka <moshez@zadka.site.co.il>.
Call C functions in shared objects.

   The `dl' module defines an interface to the `dlopen()' function,
which is the most common interface on UNIX platforms for handling
dynamically linked libraries. It allows the program to call arbitrary
functions in such a library.

   *Note:* This module will not work unless
     sizeof(int) == sizeof(long) == sizeof(char *)

   If this is not the case, `SystemError' will be raised on import.

   The `dl' module defines the following function:

`open(name[, mode` = RTLD_LAZY'])'
     Open a shared object file, and return a handle. Mode signifies
     late binding (`RTLD_LAZY') or immediate binding (`RTLD_NOW').
     Default is `RTLD_LAZY'. Note that some systems do not support
     `RTLD_NOW'.

     Return value is a `dlobject'.

   The `dl' module defines the following constants:

`RTLD_LAZY'
     Useful as an argument to `open()'.

`RTLD_NOW'
     Useful as an argument to `open()'.  Note that on systems which do
     not support immediate binding, this constant will not appear in
     the module. For maximum portability, use `hasattr()' to determine
     if the system supports immediate binding.

   The `dl' module defines the following exception:

`error'
     Exception raised when an error has occurred inside the dynamic
     loading and linking routines.

   Example:

     >>> import dl, time
     >>> a=dl.open('/lib/libc.so.6')
     >>> a.call('time'), time.time()
     (929723914, 929723914.498)

   This example was tried on a Debian GNU/Linux system, and is a good
example of the fact that using this module is usually a bad alternative.

* Menu:

* Dl Objects::


File: python-lib.info,  Node: Dl Objects,  Prev: dl,  Up: dl

Dl Objects
----------

   Dl objects, as returned by `open()' above, have the following
methods:

`close()'
     Free all resources, except the memory.

`sym(name)'
     Return the pointer for the function named NAME, as a number, if it
     exists in the referenced shared object, otherwise `None'. This is
     useful in code like:

          >>> if a.sym('time'):
          ...     a.call('time')
          ... else:
          ...     time.time()

     (Note that this function will return a non-zero number, as zero is
     the `NULL' pointer)

`call(name[, arg1[, arg2...]])'
     Call the function named NAME in the referenced shared object.  The
     arguments must be either Python integers, which will be passed as
     is, Python strings, to which a pointer will be passed, or `None',
     which will be passed as `NULL'. Note that strings should only be
     passed to functions as `const char*', as Python will not like its
     string mutated.

     There must be at most 10 arguments, and arguments not given will be
     treated as `None'. The function's return value must be a C `long',
     which is a Python integer.


File: python-lib.info,  Node: dbm,  Next: gdbm,  Prev: dl,  Up: Unix Specific Services

Simple "database" interface
===========================

   The standard "database" interface, based on ndbm.

   The `dbm' module provides an interface to the UNIX (`n')`dbm'
library.  Dbm objects behave like mappings (dictionaries), except that
keys and values are always strings.  Printing a dbm object doesn't
print the keys and values, and the `items()' and `values()' methods are
not supported.

   This module can be used with the "classic" ndbm interface, the BSD
DB compatibility interface, or the GNU GDBM compatibility interface.
On UNIX, the `configure' script will attempt to locate the appropriate
header file to simplify building this module.

   The module defines the following:

`error'
     Raised on dbm-specific errors, such as I/O errors.  `KeyError' is
     raised for general mapping errors like specifying an incorrect key.

`library'
     Name of the `ndbm' implementation library used.

`open(filename[, flag[, mode]])'
     Open a dbm database and return a dbm object.  The FILENAME
     argument is the name of the database file (without the `.dir' or
     `.pag' extensions; note that the BSD DB implementation of the
     interface will append the extension `.db' and only create one
     file).

     The optional FLAG argument must be one of these values:

     Value                              Meaning
     ------                             -----
     'r'                                Open existing database for
                                        reading only (default)
     'w'                                Open existing database for
                                        reading and writing
     'c'                                Open database for reading and
                                        writing, creating it if it
                                        doesn't exist
     'n'                                Always create a new, empty
                                        database, open for reading and
                                        writing

     The optional MODE argument is the UNIX mode of the file, used only
     when the database has to be created.  It defaults to octal `0666'.

   See also:

   *Note anydbm:: Generic interface to `dbm'-style databases.  *Note
gdbm:: Similar interface to the GNU GDBM library.  *Note whichdb::
Utility module used to determine the type of an existing database.


File: python-lib.info,  Node: gdbm,  Next: termios,  Prev: dbm,  Up: Unix Specific Services

GNU's reinterpretation of dbm
=============================

   GNU's reinterpretation of dbm.

   This module is quite similar to the `dbm'module, but uses `gdbm'
instead to provide some additional functionality.  Please note that the
file formats created by `gdbm' and `dbm' are incompatible.

   The `gdbm' module provides an interface to the GNU DBM library.
`gdbm' objects behave like mappings (dictionaries), except that keys
and values are always strings.  Printing a `gdbm' object doesn't print
the keys and values, and the `items()' and `values()' methods are not
supported.

   The module defines the following constant and functions:

`error'
     Raised on `gdbm'-specific errors, such as I/O errors.  `KeyError'
     is raised for general mapping errors like specifying an incorrect
     key.

`open(filename, [flag, [mode]])'
     Open a `gdbm' database and return a `gdbm' object.  The FILENAME
     argument is the name of the database file.

     The optional FLAG argument can be `'r'' (to open an existing
     database for reading only -- default), `'w'' (to open an existing
     database for reading and writing), `'c'' (which creates the
     database if it doesn't exist), or `'n'' (which always creates a
     new empty database).

     The following additional characters may be appended to the flag to
     control how the database is opened:

        * `'f'' -- Open the database in fast mode.  Writes to the
          database will not be syncronized.

        * `'s'' -- Synchronized mode. This will cause changes to the
          database will be immediately written to the file.

        * `'u'' -- Do not lock database.

     Not all flags are valid for all versions of `gdbm'.  The module
     constant `open_flags' is a string of supported flag characters.
     The exception `error' is raised if an invalid flag is specified.

     The optional MODE argument is the UNIX mode of the file, used only
     when the database has to be created.  It defaults to octal `0666'.

   In addition to the dictionary-like methods, `gdbm' objects have the
following methods:

`firstkey()'
     It's possible to loop over every key in the database using this
     method and the `nextkey()' method.  The traversal is ordered by
     `gdbm''s internal hash values, and won't be sorted by the key
     values.  This method returns the starting key.

`nextkey(key)'
     Returns the key that follows KEY in the traversal.  The following
     code prints every key in the database `db', without having to
     create a list in memory that contains them all:

          k = db.firstkey()
          while k != None:
              print k
              k = db.nextkey(k)

`reorganize()'
     If you have carried out a lot of deletions and would like to shrink
     the space used by the `gdbm' file, this routine will reorganize
     the database.  `gdbm' will not shorten the length of a database
     file except by using this reorganization; otherwise, deleted file
     space will be kept and reused as new (key, value) pairs are added.

`sync()'
     When the database has been opened in fast mode, this method forces
     any unwritten data to be written to the disk.

   See also:

   *Note anydbm:: Generic interface to `dbm'-style databases.  *Note
whichdb:: Utility module used to determine the type of an existing
database.


File: python-lib.info,  Node: termios,  Next: TERMIOS,  Prev: gdbm,  Up: Unix Specific Services

POSIX style tty control
=======================

   POSIX style tty control.

   This module provides an interface to the POSIX calls for tty I/O
control.  For a complete description of these calls, see the POSIX or
UNIX manual pages.  It is only available for those UNIX versions that
support POSIX _termios_ style tty I/O control (and then only if
configured at installation time).

   All functions in this module take a file descriptor FD as their
first argument.  This must be an integer file descriptor, such as
returned by `sys.stdin.fileno()'.

   This module also defines all the constants needed to work with the
functions provided here; these have the same name as their counterparts
in C.  Please refer to your system documentation for more information
on using these terminal control interfaces.

   The module defines the following functions:

`tcgetattr(fd)'
     Return a list containing the tty attributes for file descriptor
     FD, as follows: `['IFLAG, OFLAG, CFLAG, LFLAG, ISPEED, OSPEED,
     CC`]' where CC is a list of the tty special characters (each a
     string of length 1, except the items with indices `VMIN' and
     `VTIME', which are integers when these fields are defined).  The
     interpretation of the flags and the speeds as well as the indexing
     in the CC array must be done using the symbolic constants defined
     in the `termios' module.

`tcsetattr(fd, when, attributes)'
     Set the tty attributes for file descriptor FD from the ATTRIBUTES,
     which is a list like the one returned by `tcgetattr()'.  The WHEN
     argument determines when the attributes are changed: `TCSANOW' to
     change immediately, `TCSADRAIN' to change after transmitting all
     queued output, or `TCSAFLUSH' to change after transmitting all
     queued output and discarding all queued input.

`tcsendbreak(fd, duration)'
     Send a break on file descriptor FD.  A zero DURATION sends a break
     for 0.25-0.5 seconds; a nonzero DURATION has a system dependent
     meaning.

`tcdrain(fd)'
     Wait until all output written to file descriptor FD has been
     transmitted.

`tcflush(fd, queue)'
     Discard queued data on file descriptor FD.  The QUEUE selector
     specifies which queue: `TCIFLUSH' for the input queue, `TCOFLUSH'
     for the output queue, or `TCIOFLUSH' for both queues.

`tcflow(fd, action)'
     Suspend or resume input or output on file descriptor FD.  The
     ACTION argument can be `TCOOFF' to suspend output, `TCOON' to
     restart output, `TCIOFF' to suspend input, or `TCION' to restart
     input.

   See also:

   *Note tty:: Convenience functions for common terminal control
operations.

* Menu:

* termios Example::


File: python-lib.info,  Node: termios Example,  Prev: termios,  Up: termios

Example
-------

   Here's a function that prompts for a password with echoing turned
off.  Note the technique using a separate `tcgetattr()' call and a
`try' ... `finally' statement to ensure that the old tty attributes are
restored exactly no matter what happens:

     def getpass(prompt = "Password: "):
         import termios, sys
         fd = sys.stdin.fileno()
         old = termios.tcgetattr(fd)
         new = termios.tcgetattr(fd)
         new[3] = new[3] & ~termios.ECHO          # lflags
         try:
             termios.tcsetattr(fd, termios.TCSADRAIN, new)
             passwd = raw_input(prompt)
         finally:
             termios.tcsetattr(fd, termios.TCSADRAIN, old)
         return passwd


File: python-lib.info,  Node: TERMIOS,  Next: tty,  Prev: termios,  Up: Unix Specific Services

Constants used with the `termios' module
========================================

   Symbolic constants required to use the `termios' module.

   _This is deprecated in Python 2.1.  Import needed constants from
`termios' instead._

   This module defines the symbolic constants required to use the
`termios' module (see the previous section).  See the POSIX or UNIX
manual pages for a list of those constants.


File: python-lib.info,  Node: tty,  Next: pty,  Prev: TERMIOS,  Up: Unix Specific Services

Terminal control functions
==========================

   This module was documented by Steen Lumholt <>.
This section was written by Moshe Zadka <moshez@zadka.site.co.il>.
Utility functions that perform common terminal control operations.

   The `tty' module defines functions for putting the tty into cbreak
and raw modes.

   Because it requires the `termios' module, it will work only on UNIX.

   The `tty' module defines the following functions:

`setraw(fd[, when])'
     Change the mode of the file descriptor FD to raw. If WHEN is
     omitted, it defaults to `TERMIOS.TCAFLUSH', and is passed to
     `termios.tcsetattr()'.

`setcbreak(fd[, when])'
     Change the mode of file descriptor FD to cbreak. If WHEN is
     omitted, it defaults to `TERMIOS.TCAFLUSH', and is passed to
     `termios.tcsetattr()'.

   See also:

   *Note termios:: Low-level terminal control interface.  *Note
TERMIOS:: Constants useful for terminal control operations.


File: python-lib.info,  Node: pty,  Next: fcntl,  Prev: tty,  Up: Unix Specific Services

Pseudo-terminal utilities
=========================

   Pseudo-Terminal Handling for SGI and Linux.  This module was
documented by Steen Lumholt <>.
This section was written by Moshe Zadka <moshez@zadka.site.co.il>.
The `pty' module defines operations for handling the pseudo-terminal
concept: starting another process and being able to write to and read
from its controlling terminal programmatically.

   Because pseudo-terminal handling is highly platform dependant, there
is code to do it only for SGI and Linux. (The Linux code is supposed to
work on other platforms, but hasn't been tested yet.)

   The `pty' module defines the following functions:

`fork()'
     Fork. Connect the child's controlling terminal to a
     pseudo-terminal.  Return value is `(PID, FD)'. Note that the child
     gets PID 0, and the FD is _invalid_. The parent's return value is
     the PID of the child, and FD is a file descriptor connected to the
     child's controlling terminal (and also to the child's standard
     input and output.

`openpty()'
     Open a new pseudo-terminal pair, using `os.openpty()' if possible,
     or emulation code for SGI and generic UNIX systems.  Return a pair
     of file descriptors `(MASTER, SLAVE)', for the master and the
     slave end, respectively.

`spawn(argv[, master_read[, stdin_read]])'
     Spawn a process, and connect its controlling terminal with the
     current process's standard io. This is often used to baffle
     programs which insist on reading from the controlling terminal.

     The functions MASTER_READ and STDIN_READ should be functions which
     read from a file-descriptor. The defaults try to read 1024 bytes
     each time they are called.


File: python-lib.info,  Node: fcntl,  Next: pipes,  Prev: pty,  Up: Unix Specific Services

The `fcntl()' and `ioctl()' system calls
========================================

   The `fcntl()' and `ioctl()' system calls.

   This section was written by Jaap Vermeulen <>.
This module performs file control and I/O control on file descriptors.
It is an interface to the `fcntl()' and `ioctl()' UNIX routines.  File
descriptors can be obtained with the `fileno()' method of a file or
socket object.

   The module defines the following functions:

`fcntl(fd, op[, arg])'
     Perform the requested operation on file descriptor FD.  The
     operation is defined by OP and is operating system dependent.
     Typically these codes can be retrieved from the library module
     `FCNTL'. The argument ARG is optional, and defaults to the integer
     value `0'.  When present, it can either be an integer value, or a
     string.  With the argument missing or an integer value, the return
     value of this function is the integer return value of the C
     `fcntl()' call.  When the argument is a string it represents a
     binary structure, e.g. created by `struct.pack()'. The binary data
     is copied to a buffer whose address is passed to the C `fcntl()'
     call.  The return value after a successful call is the contents of
     the buffer, converted to a string object.  The length of the
     returned string will be the same as the length of the ARG
     argument.  This is limited to 1024 bytes.  If the information
     returned in the buffer by the operating system is larger than 1024
     bytes, this is most likely to result in a segmentation violation
     or a more subtle data corruption.

     If the `fcntl()' fails, an `IOError' is raised.

`ioctl(fd, op, arg)'
     This function is identical to the `fcntl()' function, except that
     the operations are typically defined in the library module `IOCTL'.

`flock(fd, op)'
     Perform the lock operation OP on file descriptor FD.  See the UNIX
     manual `flock(3)' for details.  (On some systems, this function is
     emulated using `fcntl()'.)

`lockf(fd, operation, [len, [start, [whence]]])'
     This is essentially a wrapper around the `fcntl()' locking calls.
     FD is the file descriptor of the file to lock or unlock, and
     OPERATION is one of the following values:

        * `LOCK_UN' - unlock

        * `LOCK_SH' - acquire a shared lock

        * `LOCK_EX' - acquire an exclusive lock

     When OPERATION is `LOCK_SH' or `LOCK_EX', it can also be bit-wise
     OR'd with `LOCK_NB' to avoid blocking on lock acquisition.  If
     `LOCK_NB' is used and the lock cannot be acquired, an `IOError'
     will be raised and the exception will have an ERRNO attribute set
     to `EACCES' or `EAGAIN' (depending on the operating system; for
     portability, check for both values).

     LENGTH is the number of bytes to lock, START is the byte offset at
     which the lock starts, relative to WHENCE, and WHENCE is as with
     `fileobj.seek()', specifically:

        * `0' - relative to the start of the file (`SEEK_SET')

        * `1' - relative to the current buffer position (`SEEK_CUR')

        * `2' - relative to the end of the file (`SEEK_END')

     The default for START is 0, which means to start at the beginning
     of the file.  The default for LENGTH is 0 which means to lock to
     the end of the file.  The default for WHENCE is also 0.

   If the library modules `FCNTL' or `IOCTL' are missing, you can find
the opcodes in the C include files `<sys/fcntl.h>' and `<sys/ioctl.h>'.
You can create the modules yourself with the `h2py' script, found in
the `Tools/scripts/' directory.

   Examples (all on a SVR4 compliant system):

     import struct, fcntl, FCNTL
     
     file = open(...)
     rv = fcntl(file.fileno(), FCNTL.F_SETFL, FCNTL.O_NDELAY)
     
     lockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0)
     rv = fcntl.fcntl(file.fileno(), FCNTL.F_SETLKW, lockdata)

   Note that in the first example the return value variable RV will
hold an integer value; in the second example it will hold a string
value.  The structure lay-out for the LOCKDATA variable is system
dependent -- therefore using the `flock()' call may be better.


File: python-lib.info,  Node: pipes,  Next: posixfile,  Prev: fcntl,  Up: Unix Specific Services

Interface to shell pipelines
============================

   This section was written by Moshe Zadka <moshez@zadka.site.co.il>.
A Python interface to UNIX shell pipelines.

   The `pipes' module defines a class to abstract the concept of a
_pipeline_ -- a sequence of convertors from one file to another.

   Because the module uses `/bin/sh' command lines, a POSIX or
compatible shell for `os.system()' and `os.popen()' is required.

   The `pipes' module defines the following class:

`Template()'
     An abstraction of a pipeline.

   Example:

     >>> import pipes
     >>> t=pipes.Template()
     >>> t.append('tr a-z A-Z', '--')
     >>> f=t.open('/tmp/1', 'w')
     >>> f.write('hello world')
     >>> f.close()
     >>> open('/tmp/1').read()
     'HELLO WORLD'

* Menu:

* Template Objects::


File: python-lib.info,  Node: Template Objects,  Prev: pipes,  Up: pipes

Template Objects
----------------

   Template objects following methods:

`reset()'
     Restore a pipeline template to its initial state.

`clone()'
     Return a new, equivalent, pipeline template.

`debug(flag)'
     If FLAG is true, turn debugging on. Otherwise, turn debugging off.
     When debugging is on, commands to be executed are printed, and the
     shell is given `set -x' command to be more verbose.

`append(cmd, kind)'
     Append a new action at the end. The CMD variable must be a valid
     bourne shell command. The KIND variable consists of two letters.

     The first letter can be either of `'-'' (which means the command
     reads its standard input), `'f'' (which means the commands reads a
     given file on the command line) or `'.'' (which means the commands
     reads no input, and hence must be first.)

     Similarly, the second letter can be either of `'-'' (which means
     the command writes to standard output), `'f'' (which means the
     command writes a file on the command line) or `'.'' (which means
     the command does not write anything, and hence must be last.)

`prepend(cmd, kind)'
     Add a new action at the beginning. See `append()' for explanations
     of the arguments.

`open(file, mode)'
     Return a file-like object, open to FILE, but read from or written
     to by the pipeline.  Note that only one of `'r'', `'w'' may be
     given.

`copy(infile, outfile)'
     Copy INFILE to OUTFILE through the pipe.


File: python-lib.info,  Node: posixfile,  Next: resource,  Prev: pipes,  Up: Unix Specific Services

File-like objects with locking support
======================================

   A file-like object with support for locking.  This module was
documented by Jaap Vermeulen <>.
This section was written by Jaap Vermeulen <>.
*Note:* This module will become obsolete in a future release.  The
locking operation that it provides is done better and more portably by
the `fcntl.lockf()' call.

   This module implements some additional functionality over the
built-in file objects.  In particular, it implements file locking,
control over the file flags, and an easy interface to duplicate the
file object.  The module defines a new file object, the posixfile
object.  It has all the standard file object methods and adds the
methods described below.  This module only works for certain flavors of
UNIX, since it uses `fcntl.fcntl()' for file locking.

   To instantiate a posixfile object, use the `open()' function in the
`posixfile' module.  The resulting object looks and feels roughly the
same as a standard file object.

   The `posixfile' module defines the following constants:

`SEEK_SET'
     Offset is calculated from the start of the file.

`SEEK_CUR'
     Offset is calculated from the current position in the file.

`SEEK_END'
     Offset is calculated from the end of the file.

   The `posixfile' module defines the following functions:

`open(filename[, mode[, bufsize]])'
     Create a new posixfile object with the given filename and mode.
     The FILENAME, MODE and BUFSIZE arguments are interpreted the same
     way as by the built-in `open()' function.

`fileopen(fileobject)'
     Create a new posixfile object with the given standard file object.
     The resulting object has the same filename and mode as the original
     file object.

   The posixfile object defines the following additional methods:

`lock(fmt, [len[, start[, whence]]])'
     Lock the specified section of the file that the file object is
     referring to.  The format is explained below in a table.  The LEN
     argument specifies the length of the section that should be
     locked. The default is `0'. START specifies the starting offset of
     the section, where the default is `0'.  The WHENCE argument
     specifies where the offset is relative to. It accepts one of the
     constants `SEEK_SET', `SEEK_CUR' or `SEEK_END'.  The default is
     `SEEK_SET'.  For more information about the arguments refer to the
     `fcntl(2)' manual page on your system.

`flags([flags])'
     Set the specified flags for the file that the file object is
     referring to.  The new flags are ORed with the old flags, unless
     specified otherwise.  The format is explained below in a table.
     Without the FLAGS argument a string indicating the current flags
     is returned (this is the same as the `?' modifier).  For more
     information about the flags refer to the `fcntl(2)' manual page on
     your system.

`dup()'
     Duplicate the file object and the underlying file pointer and file
     descriptor.  The resulting object behaves as if it were newly
     opened.

`dup2(fd)'
     Duplicate the file object and the underlying file pointer and file
     descriptor.  The new object will have the given file descriptor.
     Otherwise the resulting object behaves as if it were newly opened.

`file()'
     Return the standard file object that the posixfile object is based
     on.  This is sometimes necessary for functions that insist on a
     standard file object.

   All methods raise `IOError' when the request fails.

   Format characters for the `lock()' method have the following meaning:

Format                               Meaning
------                               -----
u                                    unlock the specified region
r                                    request a read lock for the
                                     specified section
w                                    request a write lock for the
                                     specified section

   In addition the following modifiers can be added to the format:

Modifier                 Meaning                  Notes
------                   -----                    -----
|                        wait until the lock has  
                         been granted             
?                        return the first lock    (1)
                         conflicting with the     
                         requested lock, or       
                         `None' if there is no    
                         conflict.                

Note:

`(1)'
     The lock returned is in the format `(MODE, LEN, START, WHENCE,
     PID)' where MODE is a character representing the type of lock ('r'
     or 'w').  This modifier prevents a request from being granted; it
     is for query purposes only.

   Format characters for the `flags()' method have the following
meanings:

Format                               Meaning
------                               -----
a                                    append only flag
c                                    close on exec flag
n                                    no delay flag (also called
                                     non-blocking flag)
s                                    synchronization flag

   In addition the following modifiers can be added to the format:

Modifier                 Meaning                  Notes
------                   -----                    -----
!                        turn the specified       (1)
                         flags 'off', instead of  
                         the default 'on'         
=                        replace the flags,       (1)
                         instead of the default   
                         'OR' operation           
?                        return a string in       (2)
                         which the characters     
                         represent the flags      
                         that are set.            

Notes:

`(1)'
     The `!' and `=' modifiers are mutually exclusive.

`(2)'
     This string represents the flags after they may have been altered
     by the same call.

   Examples:

     import posixfile
     
     file = posixfile.open('/tmp/test', 'w')
     file.lock('w|')
     ...
     file.lock('u')
     file.close()


File: python-lib.info,  Node: resource,  Next: nis,  Prev: posixfile,  Up: Unix Specific Services

Resource usage information
==========================

   An interface to provide resource usage information on the current
process.  This module was documented by Jeremy Hylton
<jhylton@cnri.reston.va.us>.
This section was written by Jeremy Hylton <jhylton@cnri.reston.va.us>.
This module provides basic mechanisms for measuring and controlling
system resources utilized by a program.

   Symbolic constants are used to specify particular system resources
and to request usage information about either the current process or its
children.

   A single exception is defined for errors:

`error'
     The functions described below may raise this error if the
     underlying system call failures unexpectedly.

* Menu:

* Resource Limits::
* Resource Usage::

