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: struct,  Next: fpformat,  Prev: regsub,  Up: String Services

Interpret strings as packed binary data.
========================================

   Interpret strings as packed binary data.

   This module performs conversions between Python values and C structs
represented as Python strings.  It uses "format strings" (explained
below) as compact descriptions of the lay-out of the C structs and the
intended conversion to/from Python values.

   The module defines the following exception and functions:

`error'
     Exception raised on various occasions; argument is a string
     describing what is wrong.

`pack(fmt, v1, v2, ...)'
     Return a string containing the values `V1, V2, ...' packed
     according to the given format.  The arguments must match the
     values required by the format exactly.

`unpack(fmt, string)'
     Unpack the string (presumably packed by `pack(FMT, ...)')
     according to the given format.  The result is a tuple even if it
     contains exactly one item.  The string must contain exactly the
     amount of data required by the format (i.e.  `len(STRING)' must
     equal `calcsize(FMT)').

`calcsize(fmt)'
     Return the size of the struct (and hence of the string)
     corresponding to the given format.

   Format characters have the following meaning; the conversion between
C and Python values should be obvious given their types:

Format                   C Type                   Python                   
------                   -----                    -----                    
x                        pad byte                 no value                 
c                        `char'                   string of length 1       
b                        `signed char'            integer                  
B                        `unsigned char'          integer                  
h                        `short'                  integer                  
H                        `unsigned short'         integer                  
i                        `int'                    integer                  
I                        `unsigned int'           integer                  
l                        `long'                   integer                  
L                        `unsigned long'          integer                  
f                        `float'                  float                    
d                        `double'                 float                    
s                        `char[]'                 string                   
p                        `char[]'                 string                   
P                        `void *'                 integer                  

   A format character may be preceded by an integral repeat count; e.g.
the format string `'4h'' means exactly the same as `'hhhh''.

   Whitespace characters between formats are ignored; a count and its
format must not contain whitespace though.

   For the `s' format character, the count is interpreted as the size
of the string, not a repeat count like for the other format characters;
e.g. `'10s'' means a single 10-byte string, while `'10c'' means 10
characters.  For packing, the string is truncated or padded with null
bytes as appropriate to make it fit.  For unpacking, the resulting
string always has exactly the specified number of bytes.  As a special
case, `'0s'' means a single, empty string (while `'0c'' means 0
characters).

   The `p' format character can be used to encode a Pascal string.  The
first byte is the length of the stored string, with the bytes of the
string following.  If count is given, it is used as the total number of
bytes used, including the length byte.  If the string passed in to
`pack()' is too long, the stored representation is truncated.  If the
string is too short, padding is used to ensure that exactly enough
bytes are used to satisfy the count.

   For the `I' and `L' format characters, the return value is a Python
long integer.

   For the `P' format character, the return value is a Python integer
or long integer, depending on the size needed to hold a pointer when it
has been cast to an integer type.  A `NULL' pointer will always be
returned as the Python integer `0'. When packing pointer-sized values,
Python integer or long integer objects may be used.  For example, the
Alpha and Merced processors use 64-bit pointer values, meaning a Python
long integer will be used to hold the pointer; other platforms use
32-bit pointers and will use a Python integer.

   By default, C numbers are represented in the machine's native format
and byte order, and properly aligned by skipping pad bytes if necessary
(according to the rules used by the C compiler).

   Alternatively, the first character of the format string can be used
to indicate the byte order, size and alignment of the packed data,
according to the following table:

Character                Byte order               Size and alignment       
------                   -----                    -----                    
@                        native                   native                   
=                        native                   standard                 
<                        little-endian            standard                 
>                        big-endian               standard                 
!                        network (= big-endian)   standard                 

   If the first character is not one of these, `@' is assumed.

   Native byte order is big-endian or little-endian, depending on the
host system (e.g. Motorola and Sun are big-endian; Intel and DEC are
little-endian).

   Native size and alignment are determined using the C compiler's
`sizeof' expression.  This is always combined with native byte order.

   Standard size and alignment are as follows: no alignment is required
for any type (so you have to use pad bytes); `short' is 2 bytes; `int'
and `long' are 4 bytes.  `float' and `double' are 32-bit and 64-bit
IEEE floating point numbers, respectively.

   Note the difference between `@' and `=': both use native byte order,
but the size and alignment of the latter is standardized.

   The form `!' is available for those poor souls who claim they can't
remember whether network byte order is big-endian or little-endian.

   There is no way to indicate non-native byte order (i.e. force
byte-swapping); use the appropriate choice of `<' or `>'.

   The `P' format character is only available for the native byte
ordering (selected as the default or with the `@' byte order
character). The byte order character `=' chooses to use little- or
big-endian ordering based on the host system. The struct module does
not interpret this as native ordering, so the `P' format is not
available.

   Examples (all using native byte order, size and alignment, on a
big-endian machine):

     >>> from struct import *
     >>> pack('hhl', 1, 2, 3)
     '\000\001\000\002\000\000\000\003'
     >>> unpack('hhl', '\000\001\000\002\000\000\000\003')
     (1, 2, 3)
     >>> calcsize('hhl')
     8

   Hint: to align the end of a structure to the alignment requirement of
a particular type, end the format with the code for that type with a
repeat count of zero, e.g. the format `'llh0l'' specifies two pad bytes
at the end, assuming longs are aligned on 4-byte boundaries.  This only
works when native size and alignment are in effect; standard size and
alignment does not enforce any alignment.

   See also:

   *Note array:: packed binary storage of homogeneous data *Note
xdrlib:: packing and unpacking of XDR data


File: python-lib.info,  Node: fpformat,  Next: StringIO,  Prev: struct,  Up: String Services

Floating point conversions
==========================

   This section was written by Moshe Zadka <mzadka@geocities.com>.
General floating point formatting functions.

   The `fpformat' module defines functions for dealing with floating
point numbers representations in 100% pure Python. *Note:*  This module
is unneeded: everything here could be done via the `%' string
interpolation operator.

   The `fpformat' module defines the following functions and an
exception:

`fix(x, digs)'
     Format X as `[-]ddd.ddd' with DIGS digits after the point and at
     least one digit before.  If `DIGS <= 0', the decimal point is
     suppressed.

     X can be either a number or a string that looks like one. DIGS is
     an integer.

     Return value is a string.

`sci(x, digs)'
     Format X as `[-]d.dddE[+-]ddd' with DIGS digits after the point
     and exactly one digit before.  If `DIGS <= 0', one digit is kept
     and the point is suppressed.

     X can be either a real number, or a string that looks like one.
     DIGS is an integer.

     Return value is a string.

`NotANumber'
     Exception raised when a string does not look like a number when the
     documentation says it should.

   Example:

     >>> import fpformat
     >>> fpformat.fix(1.23, 1)
     '1.2'


File: python-lib.info,  Node: StringIO,  Next: cStringIO,  Prev: fpformat,  Up: String Services

Read and write strings as files
===============================

   Read and write strings as if they were files.

   This module implements a file-like class, `StringIO', that reads and
writes a string buffer (also known as *memory files*). See the
description on file objects for operations (section *Note File
Objectsfile::).

`StringIO([buffer])'
     When a `StringIO' object is created, it can be initialized to an
     existing string by passing the string to the constructor.  If no
     string is given, the `StringIO' will start empty.

   The following methods of `StringIO' objects require special mention:

`getvalue()'
     Retrieve the entire contents of the "file" at any time before the
     `StringIO' object's `close()' method is called.

`close()'
     Free the memory buffer.


File: python-lib.info,  Node: cStringIO,  Prev: StringIO,  Up: String Services

Faster version of `StringIO'
============================

   Faster version of `StringIO', but not subclassable.  This module was
documented by Jim Fulton <jfulton@digicool.com>.
This section was written by Fred L. Drake, Jr. <fdrake@acm.org>.
The module `cStringIO' provides an interface similar to that of the
`StringIO' module.  Heavy use of `StringIO.StringIO' objects can be
made more efficient by using the function `StringIO()' from this module
instead.

   Since this module provides a factory function which returns objects
of built-in types, there's no way to build your own version using
subclassing.  Use the original `StringIO' module in that case.

   The following data objects are provided as well:

`InputType'
     The type object of the objects created by calling `StringIO' with
     a string parameter.

`OutputType'
     The type object of the objects returned by calling `StringIO' with
     no parameters.

   There is a C API to the module as well; refer to the module source
for more information.


File: python-lib.info,  Node: Miscellaneous Services,  Next: Generic Operating System Services,  Prev: String Services,  Up: Top

Miscellaneous Services
**********************

   The modules described in this chapter provide miscellaneous services
that are available in all Python versions.  Here's an overview:

* Menu:

* math::
* cmath::
* whrandom::
* random::
* bisect::
* array::
* ConfigParser::
* fileinput::
* calendar::
* cmd::
* shlex::


File: python-lib.info,  Node: math,  Next: cmath,  Prev: Miscellaneous Services,  Up: Miscellaneous Services

Mathematical functions
======================

   Mathematical functions (`sin()' etc.).

   This module is always available.  It provides access to the
mathematical functions defined by the C standard.  They are:

`acos(x)'
     Return the arc cosine of X.

`asin(x)'
     Return the arc sine of X.

`atan(x)'
     Return the arc tangent of X.

`atan2(y, x)'
     Return `atan(Y / X)'.

`ceil(x)'
     Return the ceiling of X as a real.

`cos(x)'
     Return the cosine of X.

`cosh(x)'
     Return the hyperbolic cosine of X.

`exp(x)'
     Return `e**X'.

`fabs(x)'
     Return the absolute value of the real X.

`floor(x)'
     Return the floor of X as a real.

`fmod(x, y)'
     Return `X % Y'.

`frexp(x)'
     Return the matissa and exponent for X.  The mantissa is positive.

`hypot(x, y)'
     Return the Euclidean distance, `sqrt(X*X + Y*Y)'.

`ldexp(x, i)'
     Return `X * (2**I)'.

`log(x)'
     Return the natural logarithm of X.

`log10(x)'
     Return the base-10 logarithm of X.

`modf(x)'
     Return the fractional and integer parts of X.  Both results carry
     the sign of X.  The integer part is returned as a real.

`pow(x, y)'
     Return `X**Y'.

`sin(x)'
     Return the sine of X.

`sinh(x)'
     Return the hyperbolic sine of X.

`sqrt(x)'
     Return the square root of X.

`tan(x)'
     Return the tangent of X.

`tanh(x)'
     Return the hyperbolic tangent of X.

   Note that `frexp()' and `modf()' have a different call/return
pattern than their C equivalents: they take a single argument and
return a pair of values, rather than returning their second return
value through an `output parameter' (there is no such thing in Python).

   The module also defines two mathematical constants:

`pi'
     The mathematical constant *pi*.

`e'
     The mathematical constant *e*.

   See also:

   *Note cmath:: Complex number versions of many of these functions.


File: python-lib.info,  Node: cmath,  Next: whrandom,  Prev: math,  Up: Miscellaneous Services

Mathematical functions for complex numbers
==========================================

   Mathematical functions for complex numbers.

   This module is always available.  It provides access to mathematical
functions for complex numbers.  The functions are:

`acos(x)'
     Return the arc cosine of X.

`acosh(x)'
     Return the hyperbolic arc cosine of X.

`asin(x)'
     Return the arc sine of X.

`asinh(x)'
     Return the hyperbolic arc sine of X.

`atan(x)'
     Return the arc tangent of X.

`atanh(x)'
     Return the hyperbolic arc tangent of X.

`cos(x)'
     Return the cosine of X.

`cosh(x)'
     Return the hyperbolic cosine of X.

`exp(x)'
     Return the exponential value `e**X'.

`log(x)'
     Return the natural logarithm of X.

`log10(x)'
     Return the base-10 logarithm of X.

`sin(x)'
     Return the sine of X.

`sinh(x)'
     Return the hyperbolic sine of X.

`sqrt(x)'
     Return the square root of X.

`tan(x)'
     Return the tangent of X.

`tanh(x)'
     Return the hyperbolic tangent of X.

   The module also defines two mathematical constants:

`pi'
     The mathematical constant *pi*, as a real.

`e'
     The mathematical constant *e*, as a real.

   Note that the selection of functions is similar, but not identical,
to that in module `math'.  The reason for having two modules is that
some users aren't interested in complex numbers, and perhaps don't even
know what they are.  They would rather have `math.sqrt(-1)' raise an
exception than return a complex number.  Also note that the functions
defined in `cmath' always return a complex number, even if the answer
can be expressed as a real number (in which case the complex number has
an imaginary part of zero).


File: python-lib.info,  Node: whrandom,  Next: random,  Prev: cmath,  Up: Miscellaneous Services

Floating point pseudo-random number generator.
==============================================

   Floating point pseudo-random number generator.

   This module implements a Wichmann-Hill pseudo-random number generator
class that is also named `whrandom'.  Instances of the `whrandom' class
have the following methods:

`choice(seq)'
     Chooses a random element from the non-empty sequence SEQ and
     returns it.

`randint(a, b)'
     Returns a random integer N such that `A<=N<=B'.

`random()'
     Returns the next random floating point number in the range [0.0
     ... 1.0).

`seed(x, y, z)'
     Initializes the random number generator from the integers X, Y and
     Z.  When the module is first imported, the random number is
     initialized using values derived from the current time.

`uniform(a, b)'
     Returns a random real number N such that `A<=N<B'.

   When imported, the `whrandom' module also creates an instance of the
`whrandom' class, and makes the methods of that instance available at
the module level.  Therefore one can write either `N =
whrandom.random()' or:
     generator = whrandom.whrandom()
     N = generator.random()

   See also:

   *Note random:: generators for various random distributions Wichmann,
B. A. & Hill, I. D., "Algorithm AS 183:  An efficient and portable
pseudo-random number generator",  *Applied Statistics* 31 (1982) 188-190


File: python-lib.info,  Node: random,  Next: bisect,  Prev: whrandom,  Up: Miscellaneous Services

Generate pseudo-random numbers
==============================

   Generate pseudo-random numbers with various common distributions.

   This module implements pseudo-random number generators for various
distributions: on the real line, there are functions to compute normal
or Gaussian, lognormal, negative exponential, gamma, and beta
distributions.  For generating distribution of angles, the circular
uniform and von Mises distributions are available.

   The module exports the following functions, which are exactly
equivalent to those in the `whrandom' module: `choice()', `randint()',
`random()' and `uniform()'.  See the documentation for the `whrandom'
module for these functions.

   The following functions specific to the `random' module are also
defined, and all return real values.  Function parameters are named
after the corresponding variables in the distribution's equation, as
used in common mathematical practice; most of these equations can be
found in any statistics text.

`betavariate(alpha, beta)'
     Beta distribution.  Conditions on the parameters are `ALPHA >- 1'
     and `BETA > -1'.  Returned values will range between 0 and 1.

`cunifvariate(mean, arc)'
     Circular uniform distribution.  MEAN is the mean angle, and ARC is
     the range of the distribution, centered around the mean angle.
     Both values must be expressed in radians, and can range between 0
     and *pi*.  Returned values will range between `MEAN - ARC/2' and
     `MEAN + ARC/2'.

`expovariate(lambd)'
     Exponential distribution.  LAMBD is 1.0 divided by the desired
     mean.  (The parameter would be called "lambda", but that is a
     reserved word in Python.)  Returned values will range from 0 to
     positive infinity.

`gamma(alpha, beta)'
     Gamma distribution.  (*Not* the gamma function!)  Conditions on
     the parameters are `ALPHA > -1' and `BETA > 0'.

`gauss(mu, sigma)'
     Gaussian distribution.  MU is the mean, and SIGMA is the standard
     deviation.  This is slightly faster than the `normalvariate()'
     function defined below.

`lognormvariate(mu, sigma)'
     Log normal distribution.  If you take the natural logarithm of this
     distribution, you'll get a normal distribution with mean MU and
     standard deviation SIGMA.  MU can have any value, and SIGMA must
     be greater than zero.

`normalvariate(mu, sigma)'
     Normal distribution.  MU is the mean, and SIGMA is the standard
     deviation.

`vonmisesvariate(mu, kappa)'
     MU is the mean angle, expressed in radians between 0 and 2**pi*,
     and KAPPA is the concentration parameter, which must be greater
     than or equal to zero.  If KAPPA is equal to zero, this
     distribution reduces to a uniform random angle over the range 0 to
     2**pi*.

`paretovariate(alpha)'
     Pareto distribution.  ALPHA is the shape parameter.

`weibullvariate(alpha, beta)'
     Weibull distribution.  ALPHA is the scale parameter and BETA is
     the shape parameter.

   See also:

   *Note whrandom:: the standard Python random number generator


File: python-lib.info,  Node: bisect,  Next: array,  Prev: random,  Up: Miscellaneous Services

Array bisection algorithm
=========================

   Array bisection algorithms for binary searching.

   This module provides support for maintaining a list in sorted order
without having to sort the list after each insertion.  For long lists
of items with expensive comparison operations, this can be an
improvement over the more common approach.  The module is called
`bisect' because it uses a basic bisection algorithm to do its work.
The source code may be most useful as a working example of the
algorithm (i.e., the boundary conditions are already right!).

   The following functions are provided:

`bisect(list, item[, lo[, hi]])'
     Locate the proper insertion point for ITEM in LIST to maintain
     sorted order.  The parameters LO and HI may be used to specify a
     subset of the list which should be considered.  The return value
     is suitable for use as the first parameter to `LIST.insert()'.

`insort(list, item[, lo[, hi]])'
     Insert ITEM in LIST in sorted order.  This is equivalent to
     `LIST.insert(bisect.bisect(LIST, ITEM, LO, HI), ITEM)'.

* Menu:

* bisect-example::


File: python-lib.info,  Node: bisect-example,  Prev: bisect,  Up: bisect

Example
-------

   The `bisect()' function is generally useful for categorizing numeric
data.  This example uses `bisect()' to look up a letter grade for an
exam total (say) based on a set of ordered numeric breakpoints: 85 and
up is an `A', 75..84 is a `B', etc.

     >>> grades = "FEDCBA"
     >>> breakpoints = [30, 44, 66, 75, 85]
     >>> from bisect import bisect
     >>> def grade(total):
     ...           return grades[bisect(breakpoints, total)]
     ...
     >>> grade(66)
     'C'
     >>> map(grade, [33, 99, 77, 44, 12, 88])
     ['E', 'A', 'B', 'D', 'F', 'A']


File: python-lib.info,  Node: array,  Next: ConfigParser,  Prev: bisect,  Up: Miscellaneous Services

Efficient arrays of numeric values
==================================

   Efficient arrays of uniformly typed numeric values.

   This module defines a new object type which can efficiently represent
an array of basic values: characters, integers, floating point numbers.
Arrays are sequence types and behave very much like lists, except that
the type of objects stored in them is constrained.  The type is
specified at object creation time by using a "type code", which is a
single character.  The following type codes are defined:

Type code                C Type                   Minimum size in bytes    
------                   -----                    -----                    
'c'                      character                1                        
'b'                      signed int               1                        
'B'                      unsigned int             1                        
'h'                      signed int               2                        
'H'                      unsigned int             2                        
'i'                      signed int               2                        
'I'                      unsigned int             2                        
'l'                      signed int               4                        
'L'                      unsigned int             4                        
'f'                      float                    4                        
'd'                      double                   8                        

   The actual representation of values is determined by the machine
architecture (strictly speaking, by the C implementation).  The actual
size can be accessed through the `itemsize' attribute.  The values
stored  for `'L'' and `'I'' items will be represented as Python long
integers when retrieved, because Python's plain integer type cannot
represent the full range of C's unsigned (long) integers.

   The module defines the following function and type object:

`array(typecode[, initializer])'
     Return a new array whose items are restricted by TYPECODE, and
     initialized from the optional INITIALIZER value, which must be a
     list or a string.  The list or string is passed to the new array's
     `fromlist()' or `fromstring()' method (see below) to add initial
     items to the array.

`ArrayType'
     Type object corresponding to the objects returned by `array()'.

   Array objects support the following data items and methods:

`typecode'
     The typecode character used to create the array.

`itemsize'
     The length in bytes of one array item in the internal
     representation.

`append(x)'
     Append a new item with value X to the end of the array.

`buffer_info()'
     Return a tuple `(ADDRESS, LENGTH)' giving the current memory
     address and the length in bytes of the buffer used to hold array's
     contents.  This is occasionally useful when working with low-level
     (and inherently unsafe) I/O interfaces that require memory
     addresses, such as certain `ioctl()' operations.  The returned
     numbers are valid as long as the array exists and no
     length-changing operations are applied to it.

`byteswap(x)'
     "Byteswap" all items of the array.  This is only supported for
     integer values; for other types of values, `RuntimeError' is
     raised.  It is useful when reading data from a file written on a
     machine with a different byte order.

`fromfile(f, n)'
     Read N items (as machine values) from the file object F and append
     them to the end of the array.  If less than N items are available,
     `EOFError' is raised, but the items that were available are still
     inserted into the array.  F must be a real built-in file object;
     something else with a `read()' method won't do.

`fromlist(list)'
     Append items from the list.  This is equivalent to `for x in LIST:
     a.append(x)' except that if there is a type error, the array is
     unchanged.

`fromstring(s)'
     Appends items from the string, interpreting the string as an array
     of machine values (i.e. as if it had been read from a file using
     the `fromfile()' method).

`insert(i, x)'
     Insert a new item with value X in the array before position I.

`read(f, n)'
     *This is deprecated in Python 1.5.1.  Use the `fromfile()' method.*
     Read N items (as machine values) from the file object F and append
     them to the end of the array.  If less than N items are available,
     `EOFError' is raised, but the items that were available are still
     inserted into the array.  F must be a real built-in file object;
     something else with a `read()' method won't do.

`reverse()'
     Reverse the order of the items in the array.

`tofile(f)'
     Write all items (as machine values) to the file object F.

`tolist()'
     Convert the array to an ordinary list with the same items.

`tostring()'
     Convert the array to an array of machine values and return the
     string representation (the same sequence of bytes that would be
     written to a file by the `tofile()' method.)

`write(f)'
     *This is deprecated in Python 1.5.1.  Use the `tofile()' method.*
     Write all items (as machine values) to the file object F.

   When an array object is printed or converted to a string, it is
represented as `array(TYPECODE, INITIALIZER)'.  The INITIALIZER is
omitted if the array is empty, otherwise it is a string if the TYPECODE
is `'c'', otherwise it is a list of numbers.  The string is guaranteed
to be able to be converted back to an array with the same type and
value using reverse quotes (```').  Examples:

     array('l')
     array('c', 'hello world')
     array('l', [1, 2, 3, 4, 5])
     array('d', [1.0, 2.0, 3.14])

   See also:

   *Note struct:: packing and unpacking of heterogeneous binary data
*Note xdrlib:: packing and unpacking of XDR data


File: python-lib.info,  Node: ConfigParser,  Next: fileinput,  Prev: array,  Up: Miscellaneous Services

Configuration file parser
=========================

   Configuration file parser.

   This section was written by Christopher G. Petrilli
<petrilli@amber.org>.
This module defines the class `ConfigParser'.  The `ConfigParser' class
implements a basic configuration file parser language which provides a
structure similar to what you would find on Microsoft Windows INI
files.  You can use this to write Python programs which can be
customized by end users easily.

   The configuration file consists of sections, lead by a `[section]'
header and followed by `name: value' entries, with continuations in the
style of RFC 822; `name=value' is also accepted.  The optional values
can contain format strings which refer to other values in the same
section, or values in a special `DEFAULT' section.  Additional defaults
can be provided upon initialization and retrieval.  Lines beginning
with `#' are ignored and may be used to provide comments.

   For example:

     foodir: %(dir)s/whatever

   would resolve the `%(dir)s' to the value of dir. All reference
expansions are done late, on demand.

   Intrinsic defaults can be specified by passing them into the
`ConfigParser' constructor as a dictionary.  Additional defaults may be
passed into the `get' method which will override all others.

`ConfigParser([defaults])'
     Return a new instance of the `ConfigParser' class.  When DEFAULTS
     is given, it is initialized into the dictionairy of intrinsic
     defaults.  They keys must be strings, and the values must be
     appropriate for the `%()s' string interpolation.  Note that
     __NAME__ is always an intrinsic default; its value is the section
     name.

`NoSectionError'
     Exception raised when a specified section is not found.

`DuplicateSectionError'
     Exception raised when mutliple sections with the same name are
     found.

`NoOptionError'
     Exception raised when a specified option is not found in the
     specified section.

`InterpolationError'
     Exception raised when problems occur performing string
     interpolation.

`MissingSectionHeaderError'
     Exception raised when attempting to parse a file which has no
     section headers.

`ParsingError'
     Exception raised when errors occur attempting to parse a file.

   See also:

   *Note shlex:: Support for a creating UNIX shell-like minilanguages
which can be used as an alternate format for application configuration
files.

* Menu:

* ConfigParser Objects::

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

ConfigParser Objects
--------------------

   `ConfigParser' instances have the following methods:

`defaults()'
     Return a dictionairy containing the instance-wide defaults.

`sections()'
     Return a list of the sections available.

`has_section(section)'
     Indicates whether the named section is present in the
     configuration. The `DEFAULT' section is not acknowledged.

`options(section)'
     Returns a list of options available in the specified SECTION.

`read(filenames)'
     Read and parse a list of filenames.

`get(section, option[, raw[, vars]])'
     Get an OPTION value for the provided SECTION.  All the `%'
     interpolations are expanded in the return values, based on the
     defaults passed into the constructor, as well as the options VARS
     provided, unless the RAW argument is true.

`getint(section, option)'
     A convenience method which coerces the OPTION in the specified
     SECTION to an integer.

`getfloat(section, option)'
     A convenience method which coerces the OPTION in the specified
     SECTION to a floating point number.

`getboolean(section, option)'
     A convenience method which coerces the OPTION in the specified
     SECTION to a boolean value.  Note that the only accepted values
     for the option are `0' and `1', any others will raise `ValueError'.


File: python-lib.info,  Node: fileinput,  Next: calendar,  Prev: ConfigParser,  Up: Miscellaneous Services

Iterate over lines from multiple input streams
==============================================

   This module was documented by Guido van Rossum <guido@python.org>.
This section was written by Fred L. Drake, Jr. <fdrake@acm.org>.
Perl-like iteration over lines from multiple input streams, with "save
in place" capability.

   This module implements a helper class and functions to quickly write
a loop over standard input or a list of files.

   The typical use is:

     import fileinput
     for line in fileinput.input():
         process(line)

   This iterates over the lines of all files listed in `sys.argv[1:]',
defaulting to `sys.stdin' if the list is empty.  If a filename is
`'-'', it is also replaced by `sys.stdin'.  To specify an alternative
list of filenames, pass it as the first argument to `input()'.  A
single file name is also allowed.

   All files are opened in text mode.  If an I/O error occurs during
opening or reading a file, `IOError' is raised.

   If `sys.stdin' is used more than once, the second and further use
will return no lines, except perhaps for interactive use, or if it has
been explicitly reset (e.g. using `sys.stdin.seek(0)').

   Empty files are opened and immediately closed; the only time their
presence in the list of filenames is noticeable at all is when the last
file opened is empty.

   It is possible that the last line of a file does not end in a newline
character; lines are returned including the trailing newline when it is
present.

   The following function is the primary interface of this module:

`input([files[, inplace[, backup]]])'
     Create an instance of the `FileInput' class.  The instance will be
     used as global state for the functions of this module, and is also
     returned to use during iteration.

   The following functions use the global state created by `input()';
if there is no active state, `RuntimeError' is raised.

`filename()'
     Return the name of the file currently being read.  Before the first
     line has been read, returns `None'.

`lineno()'
     Return the cumulative line number of the line that has just been
     read.  Before the first line has been read, returns `0'.  After
     the last line of the last file has been read, returns the line
     number of that line.

`filelineno()'
     Return the line number in the current file.  Before the first line
     has been read, returns `0'.  After the last line of the last file
     has been read, returns the line number of that line within the
     file.

`isfirstline()'
     Return true iff the line just read is the first line of its file.

`isstdin()'
     Returns true iff the last line was read from `sys.stdin'.

`nextfile()'
     Close the current file so that the next iteration will read the
     first line from the next file (if any); lines not read from the
     file will not count towards the cumulative line count.  The
     filename is not changed until after the first line of the next
     file has been read.  Before the first line has been read, this
     function has no effect; it cannot be used to skip the first file.
     After the last line of the last file has been read, this function
     has no effect.

`close()'
     Close the sequence.

   The class which implements the sequence behavior provided by the
module is available for subclassing as well:

`FileInput([files[, inplace[, backup]]])'
     Class `FileInput' is the implementation; its methods `filename()',
     `lineno()', `fileline()', `isfirstline()', `isstdin()',
     `nextfile()' and `close()' correspond to the functions of the same
     name in the module.  In addition it has a `readline()' method which
     returns the next input line, and a `__getitem__()' method which
     implements the sequence behavior.  The sequence must be accessed
     in strictly sequential order; random access and `readline()'
     cannot be mixed.

   *Optional in-place filtering:* if the keyword argument `INPLACE=1'
is passed to `input()' or to the `FileInput' constructor, the file is
moved to a backup file and standard output is directed to the input
file.  This makes it possible to write a filter that rewrites its input
file in place.  If the keyword argument `BACKUP='.<some extension>'' is
also given, it specifies the extension for the backup file, and the
backup file remains around; by default, the extension is `'.bak'' and
it is deleted when the output file is closed.  In-place filtering is
disabled when standard input is read.

   *Caveat:* The current implementation does not work for MS-DOS 8+3
filesystems.


File: python-lib.info,  Node: calendar,  Next: cmd,  Prev: fileinput,  Up: Miscellaneous Services

Functions that emulate the UNIX `cal' program.
==============================================

   Functions that emulate the UNIX `cal' program.

   This module allows you to output calendars like the UNIX `cal(1)'
program.

`isleap(year)'
     Returns `1' if YEAR is a leap year.

`leapdays(year1, year2)'
     Return the number of leap years in the range [YEAR1...YEAR2].

`weekday(year, month, day)'
     Returns the day of the week (`0' is Monday) for YEAR (`1970'-...),
     MONTH (`1'-`12'), DAY (`1'-`31').

`monthrange(year, month)'
     Returns weekday of first day of the month and number of days in
     month, for the specified YEAR and MONTH.

`monthcalendar(year, month)'
     Returns a matrix representing a month's calendar.  Each row
     represents a week; days outside of the month a represented by
     zeros.

`prmonth(year, month[, width[, length]])'
     Prints a month's calendar.  If WIDTH is provided, it specifies the
     width of the columns that the numbers are centered in.  If LENGTH
     is given, it specifies the number of lines that each week will use.

`prcal(year)'
     Prints the calendar for the year YEAR.

`timegm(tuple)'
     An unrelated but handy function that takes a time tuple such are
     returned by the `gmtime()' function in the `time' module, and
     returns the corresponding Unix timestamp value, assuming an epoch
     of 1970, and the POSIX encoding.  In fact, `gmtime()' and
     `timegm()' are each others inverse.


File: python-lib.info,  Node: cmd,  Next: shlex,  Prev: calendar,  Up: Miscellaneous Services

Build line-oriented command interpreters.
=========================================

   This section was written by Eric S. Raymond <esr@snark.thyrsus.com>.
Build line-oriented command interpreters; this is used by module `pdb'.

   The `Cmd' class provides a simple framework for writing
line-oriented command interpreters.  These are often useful for test
harnesses, administrative tools, and prototypes that will later be
wrapped in a more sophisticated interface.

`Cmd()'
     A `Cmd' instance or subclass instance is a line-oriented
     interpreter framework.  There is no good reason to instantiate
     `Cmd' itself; rather, it's useful as a superclass of an
     interpreter class you define yourself in order to inherit `Cmd''s
     methods and encapsulate action methods.

* Menu:

* Cmd Objects::


File: python-lib.info,  Node: Cmd Objects,  Prev: cmd,  Up: cmd

Cmd Objects
-----------

   A `Cmd' instance has the following methods:

`cmdloop([intro])'
     Repeatedly issue a prompt, accept input, parse an initial prefix
     off the received input, and dispatch to action methods, passing
     them the remainder of the line as argument.

     The optional argument is a banner or intro string to be issued
     before the first prompt (this overrides the `intro' class member).

     If the `readline' module is loaded, input will automatically
     inherit `bash'-like history-list editing (e.g. <Ctrl-P> scrolls
     back to the last command, <Ctrl-N> forward to the next one,
     <Ctrl-F> moves the cursor to the right non-destructively, <Ctrl-B>
     moves the cursor to the left non-destructively, etc.).

     An end-of-file on input is passed back as the string `'EOF''.

     An interpreter instance will recognize a command name `foo' if and
     only if it has a method `do_foo()'.  As a special case, a line
     containing only the character `?' is dispatched to the method
     `do_help()'.  As another special case, a line containing only the
     character `!' is dispatched to the method `do_shell' (if such a
     method is defined).

     All subclasses of `Cmd' inherit a predefined `do_help'.  This
     method, called with an argument `bar', invokes the corresponding
     method `help_bar()'.  With no argument, `do_help()' lists all
     available help topics (that is, all commands with corresponding
     `help_*()' methods), and also lists any undocumented commands.

`onecmd(str)'
     Interpret the argument as though it had been typed in in response
     to the prompt.

`emptyline()'
     Method called when an empty line is entered in response to the
     prompt.  If this method is not overridden, it repeats the last
     nonempty command entered.

`default(line)'
     Method called on an input line when the command prefix is not
     recognized. If this method is not overridden, it prints an error
     message and returns.

`precmd()'
     Hook method executed just before the input prompt is issued.  This
     method is a stub in `Cmd'; it exists to be overridden by
     subclasses.

`postcmd()'
     Hook method executed just after a command dispatch is finished.
     This method is a stub in `Cmd'; it exists to be overridden by
     subclasses.

`preloop()'
     Hook method executed once when `cmdloop()' is called.  This method
     is a stub in `Cmd'; it exists to be overridden by subclasses.

`postloop()'
     Hook method executed once when `cmdloop()' is about to return.
     This method is a stub in `Cmd'; it exists to be overridden by
     subclasses.

   Instances of `Cmd' subclasses have some public instance variables:

`prompt'
     The prompt issued to solicit input.

`identchars'
     The string of characters accepted for the command prefix.

`lastcmd'
     The last nonempty command prefix seen.

`intro'
     A string to issue as an intro or banner.  May be overridden by
     giving the `cmdloop()' method an argument.

`doc_header'
     The header to issue if the help output has a section for documented
     commands.

`misc_header'
     The header to issue if the help output has a section for
     miscellaneous help topics (that is, there are `help_*()' methods
     without corresponding `do_*()' methods).

`undoc_header'
     The header to issue if the help output has a section for
     undocumented commands (that is, there are `do_*()' methods without
     corresponding `help_*()' methods).

`ruler'
     The character used to draw separator lines under the help-message
     headers.  If empty, no ruler line is drawn.  It defaults to `='.


File: python-lib.info,  Node: shlex,  Prev: cmd,  Up: Miscellaneous Services

Simple lexical analysis
=======================

   Simple lexical analysis for UNIX shell-like languages.  This module
was documented by Eric S. Raymond <esr@snark.thyrsus.com>.
This section was written by Eric S. Raymond <esr@snark.thyrsus.com>.
*Added in Python version 1.5.2*

   The `shlex' class makes it easy to write lexical analyzers for
simple syntaxes resembling that of the UNIX shell.  This will often be
useful for writing minilanguages, e.g. in run control files for Python
applications.

`shlex([stream])'
     A `shlex' instance or subclass instance is a lexical analyzer
     object.  The initialization argument, if present, specifies where
     to read characters from. It must be a file- or stream-like object
     with `read()' and `readline()' methods.  If no argument is given,
     input will be taken from `sys.stdin'.

   See also:

   *Note ConfigParser:: Parser for configuration files similar to the
Windows `.ini' files.

* Menu:

* shlex Objects::

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

shlex Objects
-------------

   A `shlex' instance has the following methods:

`get_token()'
     Return a token.  If tokens have been stacked using `push_token()',
     pop a token off the stack.  Otherwise, read one from the input
     stream.  If reading encounters an immediate end-of-file, an empty
     string is returned.

`push_token(str)'
     Push the argument onto the token stack.

   Instances of `shlex' subclasses have some public instance variables
which either control lexical analysis or can be used for debugging:

`commenters'
     The string of characters that are recognized as comment beginners.
     All characters from the comment beginner to end of line are
     ignored.  Includes just `#' by default.

`wordchars'
     The string of characters that will accumulate into multi-character
     tokens. By default, includes all ASCII alphanumerics and
     underscore.

`whitespace'
     Characters that will be considered whitespace and skipped.
     Whitespace bounds tokens.  By default, includes space, tab,
     linefeed and carriage-return.

`quotes'
     Characters that will be considered string quotes.  The token
     accumulates until the same quote is encountered again (thus,
     different quote types protect each other as in the shell.)  By
     default, includes ASCII single and double quotes.

   Note that any character not declared to be a word character,
whitespace, or a quote will be returned as a single-character token.

   Quote and comment characters are not recognized within words.  Thus,
the bare words `ain't' and `ain#t' would be returned as single tokens
by the default parser.

`lineno'
     Source line number (count of newlines seen so far plus one).

`token'
     The token buffer.  It may be useful to examine this when catching
     exceptions.


File: python-lib.info,  Node: Generic Operating System Services,  Next: Optional Operating System Services,  Prev: Miscellaneous Services,  Up: Top

Generic Operating System Services
*********************************

   The modules described in this chapter provide interfaces to operating
system features that are available on (almost) all operating systems,
such as files and a clock.  The interfaces are generally modelled after
the UNIX or C interfaces, but they are available on most other systems
as well.  Here's an overview:

* Menu:

* os::
* os.path::
* dircache::
* stat::
* statcache::
* statvfs::
* cmp::
* cmpcache::
* time::
* sched::
* getpass::
* curses::
* getopt::
* tempfile::
* errno::
* glob::
* fnmatch::
* shutil::
* locale::
* mutex::


File: python-lib.info,  Node: os,  Next: os.path,  Prev: Generic Operating System Services,  Up: Generic Operating System Services

Miscellaneous OS interfaces
===========================

   Miscellaneous OS interfaces.

   This module provides a more portable way of using operating system
(OS) dependent functionality than importing an OS dependent built-in
module like `posix' or `nt'.

   This module searches for an OS dependent built-in module like `mac'
or `posix' and exports the same functions and data as found there.  The
design of all Python's built-in OS dependent modules is such that as
long as the same functionality is available, it uses the same
interface; e.g., the function `os.stat(PATH)' returns stat information
about PATH in the same format (which happens to have originated with the
POSIX interface).

   Extensions peculiar to a particular OS are also available through the
`os' module, but using them is of course a threat to portability!

   Note that after the first time `os' is imported, there is *no*
performance penalty in using functions from `os' instead of directly
from the OS dependent built-in module, so there should be *no* reason
not to use `os'!

   The `os' module contains many functions and data values.  The items
below and in the following sub-sections are all available directly from
the `os' module.

`error'
     This exception is raised when a function returns a system-related
     error (e.g., not for illegal argument types).  This is also known
     as the built-in exception `OSError'.  The accompanying value is a
     pair containing the numeric error code from `errno' and the
     corresponding string, as would be printed by the C function
     `perror()'.  See the module `errno', which contains names for the
     error codes defined by the underlying operating system.

     When exceptions are classes, this exception carries two attributes,
     `errno' and `strerror'.  The first holds the value of the C
     `errno' variable, and the latter holds the corresponding error
     message from `strerror()'.  For exceptions that involve a file
     system path (e.g. `chdir()' or `unlink()'), the exception instance
     will contain a third attribute, `filename', which is the file name
     passed to the function.

     When exceptions are strings, the string for the exception is
     `'OSError''.

`name'
     The name of the OS dependent module imported.  The following names
     have currently been registered: `'posix'', `'nt'', `'dos'',
     `'mac'', `'os2'', `'ce''.

`path'
     The corresponding OS dependent standard module for pathname
     operations, e.g., `posixpath' or `macpath'.  Thus, given the
     proper imports, `os.path.split(FILE)' is equivalent to but more
     portable than `posixpath.split(FILE)'.  Note that this is also a
     valid module: it may be imported directly as `os.path'.

* Menu:

* Process Parameters::
* File Object Creation::
* File Descriptor Operations::
* Files and Directories::
* Process Management::
* Miscellanenous System Data::

