This is Info file /home/pdm/tmp/Python-1.5.2p1/Doc/lib/python-lib.info,
produced by Makeinfo version 1.68 from the input file lib.texi.

   July 6, 1999			1.5.2


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 <mzadka@geocities.com>.
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 arbitary
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 sytems 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 occured 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.

   See also the `gdbm' module, which provides a similar interface using
the GNU GDBM library.

   The module defines the following constant and functions:

`error'
     Raised on dbm-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 dbm database and return a dbm object.  The FILENAME
     argument is the name of the database file (without the `.dir' or
     `.pag' extensions).

     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 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
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).

     Appending `f' to the flag opens the database in fast mode; altered
     data will not automatically be written to the disk after every
     change.  This results in faster writes to the database, but may
     result in an inconsistent database if the program crashes while
     the database is still open.  Use the `sync()' method to force any
     unwritten data to be written to the disk.

     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 should be used in conjunction with the `TERMIOS' module,
which defines the relevant symbolic constants (see the next section).

   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 `TERMIOS.VMIN'
     and `TERMIOS.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:
     `TERMIOS.TCSANOW' to change immediately, `TERMIOS.TCSADRAIN' to
     change after transmitting all queued output, or
     `TERMIOS.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: `TERMIOS.TCIFLUSH' for the input queue,
     `TERMIOS.TCOFLUSH' for the output queue, or `TERMIOS.TCIOFLUSH'
     for both queues.

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

   See also:

   *Note TERMIOS:: Constants for use with `termios'.  *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, 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 module defines the symbolic constants required to use the
`termios' module (see the previous section).  See the POSIX or UNIX
manual pages (or the source) for a list of those constants.

   Note: this module resides in a system-dependent subdirectory of the
Python library directory.  You may have to generate it for your
particular system using the script `Tools/scripts/h2py.py'.


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 <mzadka@geocities.com>.
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 <mzadka@geocities.com>.
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.

`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 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.  In case 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, code, [len, [start, [whence]]])'
     This is a wrapper around the `FCNTL.F_SETLK' and `FCNTL.F_SETLKW'
     `fcntl()' calls.  See the UNIX manual for details.

   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.O_NDELAY, 1)
     
     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 <mzadka@geocities.com>.
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.)

     Similarily, 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::


File: python-lib.info,  Node: Resource Limits,  Next: Resource Usage,  Prev: resource,  Up: resource

Resource Limits
---------------

   Resources usage can be limited using the `setrlimit()' function
described below. Each resource is controlled by a pair of limits: 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 soft limit can
never exceed the hard limit. The hard limit can be lowered to any value
greater than the soft limit, but not raised. (Only processes with the
effective UID of the super-user can raise a hard limit.)

   The specific resources that can be limited are system dependent. They
are described in the `getrlimit(2)' man page.  The resources listed
below are supported when the underlying operating system supports them;
resources which cannot be checked or controlled by the operating system
are not defined in this module for those platforms.

`getrlimit(resource)'
     Returns a tuple `(SOFT, HARD)' with the current soft and hard
     limits of RESOURCE. Raises `ValueError' if an invalid resource is
     specified, or `error' if the underyling system call fails
     unexpectedly.

`setrlimit(resource, limits)'
     Sets new limits of consumption of RESOURCE. The LIMITS argument
     must be 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.

     Raises `ValueError' if an invalid resource is specified, if the
     new soft limit exceeds the hard limit, or if a process tries to
     raise its hard limit (unless the process has an effective UID of
     super-user).  Can also raise `error' if the underyling system call
     fails.

   These symbols define resources whose consumption can be controlled
using the `setrlimit()' and `getrlimit()' functions described below.
The values of these symbols are exactly the constants used by C
programs.

   The UNIX man page for `getrlimit(2)' lists the available resources.
Note that not all systems use the same symbol or same value to denote
the same resource.

`RLIMIT_CORE'
     The maximum size (in bytes) of a core file that the current process
     can create.  This may result in the creation of a partial core file
     if a larger core would be required to contain the entire process
     image.

`RLIMIT_CPU'
     The maximum amount of CPU time (in seconds) that a process can
     use. If this limit is exceeded, a `SIGXCPU' signal is sent to the
     process. (See the `signal' module documentation for information
     about how to catch this signal and do something useful, e.g. flush
     open files to disk.)

`RLIMIT_FSIZE'
     The maximum size of a file which the process may create.  This only
     affects the stack of the main thread in a multi-threaded process.

`RLIMIT_DATA'
     The maximum size (in bytes) of the process's heap.

`RLIMIT_STACK'
     The maximum size (in bytes) of the call stack for the current
     process.

`RLIMIT_RSS'
     The maximum resident set size that should be made available to the
     process.

`RLIMIT_NPROC'
     The maximum number of processes the current process may create.

`RLIMIT_NOFILE'
     The maximum number of open file descriptors for the current
     process.

`RLIMIT_OFILE'
     The BSD name for `RLIMIT_NOFILE'.

`RLIMIT_MEMLOC'
     The maximm address space which may be locked in memory.

`RLIMIT_VMEM'
     The largest area of mapped memory which the process may occupy.

`RLIMIT_AS'
     The maximum area (in bytes) of address space which may be taken by
     the process.


File: python-lib.info,  Node: Resource Usage,  Prev: Resource Limits,  Up: resource

Resource Usage
--------------

   These functiona are used to retrieve resource usage information:

`getrusage(who)'
     This function returns a large tuple that describes the resources
     consumed by either the current process or its children, as
     specified by the WHO parameter.  The WHO parameter should be
     specified using one of the `RUSAGE_*' constants described below.

     The elements of the return value each describe how a particular
     system resource has been used, e.g. amount of time spent running
     is user mode or number of times the process was swapped out of
     main memory. Some values are dependent on the clock tick internal,
     e.g. the amount of memory the process is using.

     The first two elements of the return value are floating point
     values representing the amount of time spent executing in user
     mode and the amount of time spent executing in system mode,
     respectively. The remaining values are integers. Consult the
     `getrusage(2)' man page for detailed information about these
     values. A brief summary is presented here:

     Offset                             Resource                           
     ------                             -----                              
     0                                  time in user mode (float)          
     1                                  time in system mode (float)        
     2                                  maximum resident set size          
     3                                  shared memory size                 
     4                                  unshared memory size               
     5                                  unshared stack size                
     6                                  page faults not requiring I/O      
     7                                  page faults requiring I/O          
     8                                  number of swap outs                
     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       

     This function will raise a `ValueError' if an invalid WHO
     parameter is specified. It may also raise `error' exception in
     unusual circumstances.

`getpagesize()'
     Returns the number of bytes in a system page. (This need not be the
     same as the hardware page size.) This function is useful for
     determining the number of bytes of memory a process is using. The
     third element of the tuple returned by `getrusage()' describes
     memory usage in pages; multiplying by page size produces number of
     bytes.

   The following `RUSAGE_*' symbols are passed to the `getrusage()'
function to specify which processes information should be provided for.

`RUSAGE_SELF'
     `RUSAGE_SELF' should be used to request information pertaining
     only to the process itself.

`RUSAGE_CHILDREN'
     Pass to `getrusage()' to request resource information for child
     processes of the calling process.

`RUSAGE_BOTH'
     Pass to `getrusage()' to request resources consumed by both the
     current process and child processes.  May not be available on all
     systems.

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

Interface to Sun's NIS (Yello Pages)
====================================

   This module was documented by Fred Gansevles
<Fred.Gansevles@cs.utwente.nl>.
This section was written by Moshe Zadka <mzadka@geocities.com>.
Interface to Sun's N.I.S. (a.k.a. Yellow Pages) library.

   The `nis' module gives a thin wrapper around the NIS library, useful
for central administration of several hosts.

   Because NIS exists only on UNIX systems, this module is only
available for UNIX.

   The `nis' module defines the following functions:

`match(key, mapname)'
     Return the match for KEY in map MAPNAME, or raise an error
     (`nis.error') if there is none.  Both should be strings, KEY is
     8-bit clean.  Return value is an arbitary array of bytes (i.e.,
     may contain `NULL' and other joys).

     Note that MAPNAME is first checked if it is an alias to another
     name.  XXX Describe list of all aliases? Internal for the C code,
     so I'm not sure it's a good idea.

`cat(mapname)'
     Return a dictionary mapping KEY to VALUE such that `match(KEY,
     MAPNAME)==VALUE'.  Note that both keys and values of the
     dictionary are arbitary arrays of bytes.

     Note that MAPNAME is first checked if it is an alias to another
     name.

`maps()'
     Return a list of all valid maps.

   The `nis' module defines the following exception:

`error'
     An error raised when a NIS function returns an error code.

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

UNIX syslog library routines
============================

   An interface to the UNIX syslog library routines.

   This module provides an interface to the UNIX `syslog' library
routines.  Refer to the UNIX manual pages for a detailed description of
the `syslog' facility.

   The module defines the following functions:

`syslog([priority,] message)'
     Send the string MESSAGE to the system logger.  A trailing newline
     is added if necessary.  Each message is tagged with a priority
     composed of a FACILITY and a LEVEL.  The optional PRIORITY
     argument, which defaults to `LOG_INFO', determines the message
     priority.  If the facility is not encoded in PRIORITY using
     logical-or (`LOG_INFO | LOG_USER'), the value given in the
     `openlog()' call is used.

`openlog(ident[, logopt[, facility]])'
     Logging options other than the defaults can be set by explicitly
     opening the log file with `openlog()' prior to calling `syslog()'.
     The defaults are (usually) IDENT = `'syslog'', LOGOPT = `0',
     FACILITY = `LOG_USER'.  The IDENT argument is a string which is
     prepended to every message.  The optional LOGOPT argument is a bit
     field - see below for possible values to combine.  The optional
     FACILITY argument sets the default facility for messages which do
     not have a facility explicitly encoded.

`closelog()'
     Close the log file.

`setlogmask(maskpri)'
     Set the priority mask to MASKPRI and return the previous mask
     value.  Calls to `syslog()' with a priority level not set in
     MASKPRI are ignored.  The default is to log all priorities.  The
     function `LOG_MASK(PRI)' calculates the mask for the individual
     priority PRI.  The function `LOG_UPTO(PRI)' calculates the mask
     for all priorities up to and including PRI.

   The module defines the following constants:

`Priority levels (high to low):'
     `LOG_EMERG', `LOG_ALERT', `LOG_CRIT', `LOG_ERR', `LOG_WARNING',
     `LOG_NOTICE', `LOG_INFO', `LOG_DEBUG'.

`Facilities:'
     `LOG_KERN', `LOG_USER', `LOG_MAIL', `LOG_DAEMON', `LOG_AUTH',
     `LOG_LPR', `LOG_NEWS', `LOG_UUCP', `LOG_CRON' and `LOG_LOCAL0' to
     `LOG_LOCAL7'.

`Log options:'
     `LOG_PID', `LOG_CONS', `LOG_NDELAY', `LOG_NOWAIT' and `LOG_PERROR'
     if defined in `<syslog.h>'.


File: python-lib.info,  Node: popen2,  Next: commands,  Prev: syslog,  Up: Unix Specific Services

Subprocesses with accessible I/O streams
========================================

   Subprocesses with accessible standard I/O streams.

   This section was written by Drew Csillag
<drew_csillag@geocities.com>.
This module allows you to spawn processes and connect their
input/output/error pipes and obtain their return codes under UNIX.
Similar functionality exists for Windows platforms using the
`win32pipe' module provided as part of Mark Hammond's Windows
extensions.

   The primary interface offered by this module is a pair of factory
functions:

`popen2(cmd[, bufsize])'
     Executes CMD as a sub-process.  If BUFSIZE is specified, it
     specifies the buffer size for the I/O pipes.  Returns
     `(CHILD_STDOUT, CHILD_STDIN)'.

`popen3(cmd[, bufsize])'
     Executes CMD as a sub-process.  If BUFSIZE is specified, it
     specifies the buffer size for the I/O pipes.  Returns
     `(CHILD_STDOUT, CHILD_STDIN, CHILD_STDERR)'.

   The class defining the objects returned by the factory functions is
also available:

`Popen3(cmd[, capturestderr[, bufsize]])'
     This class represents a child process.  Normally, `Popen3'
     instances are created using the factory functions described above.

     If not using one off the helper functions to create `Popen3'
     objects, the parameter CMD is the shell command to execute in a
     sub-process.  The CAPTURESTDERR flag, if true, specifies that the
     object should capture standard error output of the child process.
     The default is false.  If the BUFSIZE parameter is specified, it
     specifies the size of the I/O buffers to/from the child process.

* Menu:

* Popen3 Objects::


File: python-lib.info,  Node: Popen3 Objects,  Prev: popen2,  Up: popen2

Popen3 Objects
--------------

   Instances of the `Popen3' class have the following methods:

`poll()'
     Returns `-1' if child process hasn't completed yet, or its return
     code otherwise.

`wait()'
     Waits for and returns the return code of the child process.

   The following attributes of `Popen3' objects are also available:

`fromchild'
     A file object that provides output from the child process.

`tochild'
     A file object that provides input to the child process.

`childerr'
     Where the standard error from the child process goes is
     CAPTURESTDERR was true for the constructor, or `None'.

`pid'
     The process ID of the child process.


File: python-lib.info,  Node: commands,  Prev: popen2,  Up: Unix Specific Services

Utilities for running commands
==============================

   Utility functions for running external commands.

   This section was written by Sue Williams <sbw@provis.com>.
The `commands' module contains wrapper functions for `os.popen()' which
take a system command as a string and return any output generated by
the command and, optionally, the exit status.

   The `commands' module defines the following functions:

`getstatusoutput(cmd)'
     Execute the string CMD in a shell with `os.popen()' and return a
     2-tuple `(STATUS, OUTPUT)'.  CMD is actually run as `{ CMD ; }
     2>&1', so that the returned output will contain output or error
     messages. A trailing newline is stripped from the output. The exit
     status for the command can be interpreted according to the rules
     for the C function `wait()'.

`getoutput(cmd)'
     Like `getstatusoutput()', except the exit status is ignored and
     the return value is a string containing the command's output.

`getstatus(file)'
     Return the output of `ls -ld FILE' as a string.  This function
     uses the `getoutput()' function, and properly escapes backslashes
     and dollar signs in the argument.

   Example:

     >>> import commands
     >>> commands.getstatusoutput('ls /bin/ls')
     (0, '/bin/ls')
     >>> commands.getstatusoutput('cat /bin/junk')
     (256, 'cat: /bin/junk: No such file or directory')
     >>> commands.getstatusoutput('/bin/junk')
     (256, 'sh: /bin/junk: not found')
     >>> commands.getoutput('ls /bin/ls')
     '/bin/ls'
     >>> commands.getstatus('/bin/ls')
     '-rwxr-xr-x  1 root        13352 Oct 14  1994 /bin/ls'

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

The Python Debugger
*******************

   The Python debugger for interactive interpreters.

   The module `pdb' defines an interactive source code debugger for
Python programs.  It supports setting (conditional) breakpoints and
single stepping at the source line level, inspection of stack frames,
source code listing, and evaluation of arbitrary Python code in the
context of any stack frame.  It also supports post-mortem debugging and
can be called under program control.

   The debugger is extensible -- it is actually defined as the class
`Pdb'.  This is currently undocumented but easily understood by reading
the source.  The extension interface uses the modules `bdb'
(undocumented) and `cmd'.

   A primitive windowing version of the debugger also exists -- this is
module `wdb', which requires `stdwin'.

   The debugger's prompt is `(Pdb) '.  Typical usage to run a program
under control of the debugger is:

     >>> import pdb
     >>> import mymodule
     >>> pdb.run('mymodule.test()')
     > <string>(0)?()
     (Pdb) continue
     > <string>(1)?()
     (Pdb) continue
     NameError: 'spam'
     > <string>(1)?()
     (Pdb)

   `pdb.py' can also be invoked as a script to debug other scripts.
For example:

     python /usr/local/lib/python1.5/pdb.py myscript.py

   Typical usage to inspect a crashed program is:

     >>> import pdb
     >>> import mymodule
     >>> mymodule.test()
     Traceback (innermost last):
       File "<stdin>", line 1, in ?
       File "./mymodule.py", line 4, in test
         test2()
       File "./mymodule.py", line 3, in test2
         print spam
     NameError: spam
     >>> pdb.pm()
     > ./mymodule.py(3)test2()
     -> print spam
     (Pdb)

   The module defines the following functions; each enters the debugger
in a slightly different way:

`run(statement[, globals[, locals]])'
     Execute the STATEMENT (given as a string) under debugger control.
     The debugger prompt appears before any code is executed; you can
     set breakpoints and type `continue', or you can step through the
     statement using `step' or `next' (all these commands are explained
     below).  The optional GLOBALS and LOCALS arguments specify the
     environment in which the code is executed; by default the
     dictionary of the module `__main__' is used.  (See the explanation
     of the `exec' statement or the `eval()' built-in function.)

`runeval(expression[, globals[, locals]])'
     Evaluate the EXPRESSION (given as a a string) under debugger
     control.  When `runeval()' returns, it returns the value of the
     expression.  Otherwise this function is similar to `run()'.

`runcall(function[, argument, ...])'
     Call the FUNCTION (a function or method object, not a string) with
     the given arguments.  When `runcall()' returns, it returns
     whatever the function call returned.  The debugger prompt appears
     as soon as the function is entered.

`set_trace()'
     Enter the debugger at the calling stack frame.  This is useful to
     hard-code a breakpoint at a given point in a program, even if the
     code is not otherwise being debugged (e.g. when an assertion
     fails).

`post_mortem(traceback)'
     Enter post-mortem debugging of the given TRACEBACK object.

`pm()'
     Enter post-mortem debugging of the traceback found in
     `sys.last_traceback'.

* Menu:

* Debugger Commands::
* How It Works::

