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: time,  Next: sched,  Prev: cmpcache,  Up: Generic Operating System Services

Time access and conversions.
============================

   Time access and conversions.

   This module provides various time-related functions.  It is always
available.

   An explanation of some terminology and conventions is in order.

   * The "epoch" is the point where the time starts.  On January 1st of
     that year, at 0 hours, the "time since the epoch" is zero.  For
     UNIX, the epoch is 1970.  To find out what the epoch is, look at
     `gmtime(0)'.

   * The functions in this module do not handle dates and times before
     the epoch or far in the future.  The cut-off point in the future is
     determined by the C library; for UNIX, it is typically in 2038.

   * *Year 2000 (Y2K) issues*:  Python depends on the platform's C
     library, which generally doesn't have year 2000 issues, since all
     dates and times are represented internally as seconds since the
     epoch.  Functions accepting a time tuple (see below) generally
     require a 4-digit year.  For backward compatibility, 2-digit years
     are supported if the module variable `accept2dyear' is a non-zero
     integer; this variable is initialized to `1' unless the
     environment variable `PYTHONY2K' is set to a non-empty string, in
     which case it is initialized to `0'.  Thus, you can set
     `PYTHONY2K' to a non-empty string in the environment to require
     4-digit years for all year input.  When 2-digit years are
     accepted, they are converted according to the POSIX or X/Open
     standard: values 69-99 are mapped to 1969-1999, and values 0-68
     are mapped to 2000-2068.  Values 100-1899 are always illegal.
     Note that this is new as of Python 1.5.2(a2); earlier versions, up
     to Python 1.5.1 and 1.5.2a1, would add 1900 to year values below
     1900.

   * UTC is Coordinated Universal Time (formerly known as Greenwich Mean
     Time, or GMT).  The acronym UTC is not a mistake but a compromise
     between English and French.

   * DST is Daylight Saving Time, an adjustment of the timezone by
     (usually) one hour during part of the year.  DST rules are magic
     (determined by local law) and can change from year to year.  The C
     library has a table containing the local rules (often it is read
     from a system file for flexibility) and is the only source of True
     Wisdom in this respect.

   * The precision of the various real-time functions may be less than
     suggested by the units in which their value or argument is
     expressed.  E.g. on most UNIX systems, the clock "ticks" only 50
     or 100 times a second, and on the Mac, times are only accurate to
     whole seconds.

   * On the other hand, the precision of `time()' and `sleep()' is
     better than their UNIX equivalents: times are expressed as
     floating point numbers, `time()' returns the most accurate time
     available (using UNIX `gettimeofday()' where available), and
     `sleep()' will accept a time with a nonzero fraction (UNIX
     `select()' is used to implement this, where available).

   * The time tuple as returned by `gmtime()', `localtime()', and
     `strptime()', and accepted by `asctime()', `mktime()' and
     `strftime()', is a tuple of 9 integers: year (e.g. 1993), month
     (1-12), day (1-31), hour (0-23), minute (0-59), second (0-59),
     weekday (0-6, monday is 0), Julian day (1-366) and daylight
     savings flag (-1, 0 or 1).  Note that unlike the C structure, the
     month value is a range of 1-12, not 0-11.  A year value will be
     handled as descibed under "Year 2000 (Y2K) issues" above.  A `-1'
     argument as daylight savings flag, passed to `mktime()' will
     usually result in the correct daylight savings state to be filled
     in.

   The module defines the following functions and data items:

`accept2dyear'
     Boolean value indicating whether two-digit year values will be
     accepted.  This is true by default, but will be set to false if the
     environment variable `PYTHONY2K' has been set to a non-empty
     string.  It may also be modified at run time.

`altzone'
     The offset of the local DST timezone, in seconds west of the 0th
     meridian, if one is defined.  Negative if the local DST timezone is
     east of the 0th meridian (as in Western Europe, including the UK).
     Only use this if `daylight' is nonzero.

`asctime(tuple)'
     Convert a tuple representing a time as returned by `gmtime()' or
     `localtime()' to a 24-character string of the following form:
     `'Sun Jun 20 23:21:05 1993''.  Note: unlike the C function of the
     same name, there is no trailing newline.

`clock()'
     Return the current CPU time as a floating point number expressed in
     seconds.  The precision, and in fact the very definiton of the
     meaning of "CPU time", depends on that of the C function of the
     same name, but in any case, this is the function to use for
     benchmarking Python or timing algorithms.

`ctime(secs)'
     Convert a time expressed in seconds since the epoch to a string
     representing local time.  `ctime(SECS)' is equivalent to
     `asctime(localtime(SECS))'.

`daylight'
     Nonzero if a DST timezone is defined.

`gmtime(secs)'
     Convert a time expressed in seconds since the epoch to a time tuple
     in UTC in which the dst flag is always zero.  Fractions of a
     second are ignored.  See above for a description of the tuple
     lay-out.

`localtime(secs)'
     Like `gmtime()' but converts to local time.  The dst flag is set
     to `1' when DST applies to the given time.

`mktime(tuple)'
     This is the inverse function of `localtime()'.  Its argument is
     the full 9-tuple (since the dst flag is needed -- pass `-1' as the
     dst flag if it is unknown) which expresses the time in *local*
     time, not UTC.  It returns a floating point number, for
     compatibility with `time()'.  If the input value cannot be
     represented as a valid time, `OverflowError' is raised.

`sleep(secs)'
     Suspend execution for the given number of seconds.  The argument
     may be a floating point number to indicate a more precise sleep
     time.

`strftime(format, tuple)'
     Convert a tuple representing a time as returned by `gmtime()' or
     `localtime()' to a string as specified by the FORMAT argument.
     FORMAT must be a string.

     The following directives can be embedded in the FORMAT string.
     They are shown without the optional field width and precision
     specification, and are replaced by the indicated characters in the
     `strftime()' result:

     Directive                          Meaning                            
     ------                             -----                              
     %a                                 Locale's abbreviated weekday name. 
     %A                                 Locale's full weekday name.        
     %b                                 Locale's abbreviated month name.   
     %B                                 Locale's full month name.          
     %c                                 Locale's appropriate date and      
                                        time representation.               
     %d                                 Day of the month as a decimal      
                                        number [01,31].                    
     %H                                 Hour (24-hour clock) as a decimal  
                                        number [00,23].                    
     %I                                 Hour (12-hour clock) as a decimal  
                                        number [01,12].                    
     %j                                 Day of the year as a decimal       
                                        number [001,366].                  
     %m                                 Month as a decimal number [01,12]. 
     %M                                 Minute as a decimal number         
                                        [00,59].                           
     %p                                 Locale's equivalent of either AM   
                                        or PM.                             
     %S                                 Second as a decimal number         
                                        [00,61].                           
     %U                                 Week number of the year (Sunday    
                                        as the first day of the week) as   
                                        a decimal number [00,53].  All     
                                        days in a new year preceding the   
                                        first Sunday are considered to be  
                                        in week 0.                         
     %w                                 Weekday as a decimal number        
                                        [0(Sunday),6].                     
     %W                                 Week number of the year (Monday    
                                        as the first day of the week) as   
                                        a decimal number [00,53].  All     
                                        days in a new year preceding the   
                                        first Sunday are considered to be  
                                        in week 0.                         
     %x                                 Locale's appropriate date          
                                        representation.                    
     %X                                 Locale's appropriate time          
                                        representation.                    
     %y                                 Year without century as a decimal  
                                        number [00,99].                    
     %Y                                 Year with century as a decimal     
                                        number.                            
     %Z                                 Time zone name (or by no           
                                        characters if no time zone         
                                        exists).                           
     %%                                 %                                  

     Additional directives may be supported on certain platforms, but
     only the ones listed here have a meaning standardized by ANSI C.

     On some platforms, an optional field width and precision
     specification can immediately follow the initial `%' of a
     directive in the following order; this is also not portable.  The
     field width is normally 2 except for `%j' where it is 3.

`strptime(string[, format])'
     Parse a string representing a time according to a format.  The
     return value is a tuple as returned by `gmtime()' or
     `localtime()'.  The FORMAT parameter uses the same directives as
     those used by `strftime()'; it defaults to `"%a %b %d %H:%M:%S
     %Y"' which matches the formatting returned by `ctime()'.  The same
     platform caveats apply; see the local UNIX documentation for
     restrictions or additional supported directives.  If STRING cannot
     be parsed according to FORMAT, `ValueError' is raised.  This
     function may not be defined on all platforms.

`time()'
     Return the time as a floating point number expressed in seconds
     since the epoch, in UTC.  Note that even though the time is always
     returned as a floating point number, not all systems provide time
     with a better precision than 1 second.

`timezone'
     The offset of the local (non-DST) timezone, in seconds west of the
     0th meridian (i.e. negative in most of Western Europe, positive in
     the US, zero in the UK).

`tzname'
     A tuple of two strings: the first is the name of the local non-DST
     timezone, the second is the name of the local DST timezone.  If no
     DST timezone is defined, the second string should not be used.


File: python-lib.info,  Node: sched,  Next: getpass,  Prev: time,  Up: Generic Operating System Services

Event scheduler
===============

   This section was written by Moshe Zadka <mzadka@geocities.com>.
General purpose event scheduler.

   The `sched' module defines a class which implements a general
purpose event scheduler:

`scheduler(timefunc, delayfunc)'
     The `scheduler' class defines a generic interface to scheduling
     events. It needs two functions to actually deal with the "outside
     world" -- TIMEFUNC should be callable without arguments, and return
     a number (the "time", in any units whatsoever).  The DELAYFUNC
     function should be callable with one argument, compatible with the
     output of TIMEFUNC, and should delay that many time units.
     DELAYFUNC will also be called with the argument `0' after each
     event is run to allow other threads an opportunity to run in
     multi-threaded applications.

   Example:

     >>> import sched, time
     >>> s=sched.scheduler(time.time, time.sleep)
     >>> def print_time(): print "From print_time", time.time()
     ...
     >>> def print_some_times():
     ...     print time.time()
     ...     s.enter(5, 1, print_time, ())
     ...     s.enter(10, 1, print_time, ())
     ...     s.run()
     ...     print time.time()
     ...
     >>> print_some_times()
     930343690.257
     From print_time 930343695.274
     From print_time 930343700.273
     930343700.276

* Menu:

* Scheduler Objects::

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

Scheduler Objects
-----------------

   `scheduler' instances have the following methods:

`enterabs(time, priority, action, argument)'
     Schedule a new event. The TIME argument should be a numeric type
     compatible to the return value of TIMEFUNC. Events scheduled for
     the same TIME will be executed in the order of their PRIORITY.

     Executing the event means executing `apply(ACTION, ARGUMENT)'.
     ARGUMENT must be a tuple holding the parameters for ACTION.

     Return value is an event which may be used for later cancellation
     of the event (see `cancel()').

`enter(delay, priority, action, argument)'
     Schedule an event for DELAY more time units. Other then the
     relative time, the other arguments, the effect and the return value
     are the same as those for `enterabs()'.

`cancel(event)'
     Remove the event from the queue. If EVENT is not an event
     currently in the queue, this method will raise a `RuntimeError'.

`empty()'
     Return true if the event queue is empty.

`run()'
     Run all scheduled events. This function will wait (using the
     `delayfunc' function passed to the constructor) for the next
     event, then execute it and so on until there are no more scheduled
     events.

     Either ACTION or DELAYFUNC can raise an exception.  In either
     case, the scheduler will maintain a consistent state and propagate
     the exception.  If an exception is raised by ACTION, the event
     will not be attempted in future calls to `run()'.

     If a sequence of events takes longer to run than the time available
     before the next event, the scheduler will simply fall behind.  No
     events will be dropped; the calling code is responsible for
     cancelling events which are no longer pertinent.


File: python-lib.info,  Node: getpass,  Next: curses,  Prev: sched,  Up: Generic Operating System Services

Portable password input
=======================

   Portable reading of passwords and retrieval of the userid.  This
module was documented by Piers Lauder <piers@cs.su.oz.au>.
This section was written by Fred L. Drake, Jr. <fdrake@acm.org>.
The `getpass' module provides two functions:

`getpass([prompt])'
     Prompt the user for a password without echoing.  The user is
     prompted using the string PROMPT, which defaults to `'Password: ''.
     Availability: Macintosh, UNIX, Windows.

`getuser()'
     Return the "login name" of the user.  Availability: UNIX, Windows.

     This function checks the environment variables `LOGNAME', `USER',
     `LNAME' and `USERNAME', in order, and returns the value of the
     first one which is set to a non-empty string.  If none are set,
     the login name from the password database is returned on systems
     which support the `pwd' module, otherwise, an exception is raised.


File: python-lib.info,  Node: curses,  Next: getopt,  Prev: getpass,  Up: Generic Operating System Services

Terminal independant console handling
=====================================

   This section was written by Moshe Zadka <mzadka@geocities.com>.
An interface to the curses library.

   The `curses' module provides an interface to the curses UNIX
library, the de-facto standard for portable advanced terminal handling.

   While curses is most widely used in the UNIX environment, versions
are available for DOS, OS/2, and possibly other systems as well.  The
extension module has not been tested with all available versions of
curses.

   See also:

   Tutorial material on using curses with Python is available on the
Python Web site as Andrew Kuchling's *Curses Programming with Python*,
at `http://www.python.org/doc/howto/curses/curses.html'.

* Menu:

* Constants and Functions::
* Window Objects::


File: python-lib.info,  Node: Constants and Functions,  Next: Window Objects,  Prev: curses,  Up: curses

Constants and Functions
-----------------------

   The `curses' module defines the following data members:

`version'
     A string representing the current version of the module.

`A_NORMAL'
     Normal attribute.

`A_STANDOUT'
     Standout mode.

`A_UNDERLINE'
     Underline mode.

`A_BLINK'
     Blink mode.

`A_DIM'
     Dim mode.

`A_BOLD'
     Bold mode.

`A_ALTCHARSET'
     Alternate character set mode.

`KEY_*'
     Names for various keys. The exact names available are system
     dependant.

`ACS_*'
     Names for various characters: `ACS_ULCORNER', `ACS_LLCORNER',
     `ACS_URCORNER', `ACS_LRCORNER', `ACS_RTEE', `ACS_LTEE',
     `ACS_BTEE', `ACS_TTEE', `ACS_HLINE', `ACS_VLINE', `ACS_PLUS',
     `ACS_S1', `ACS_S9', `ACS_DIAMOND', `ACS_CKBOARD', `ACS_DEGREE',
     `ACS_PLMINUS', `ACS_BULLET', `ACS_LARROW', `ACS_RARROW',
     `ACS_DARROW'.

     *Note:* These are available only after `initscr()' has been called.

   The module `curses' defines the following exception:

`error'
     Curses function returned an error status.

   *Note:* Whenever X or Y arguments to a function or a method are
optional, they default to the current cursor location.  Whenever ATTR
is optional, it defaults to `A_NORMAL'.

   The module `curses' defines the following functions:

`initscr()'
     Initialize the library. Returns a `WindowObject' which represents
     the whole screen.

`endwin()'
     De-initialize the library, and return terminal to normal status.

`isendwin()'
     Returns true if `endwin()' has been called.

`doupdate()'
     Update the screen.

`newwin([nlines, ncols,] begin_y, begin_x)'
     Return a new window, whose left-upper corner is at `(BEGIN_Y,
     BEGIN_X)', and whose height/width is NLINES/NCOLS.

     By default, the window will extend from the specified position to
     the lower right corner of the screen.

`beep()'
     Emit a short sound.

`flash()'
     Flash the screen.

`ungetch(ch)'
     Push CH so the next `getch()' will return it; CH is an integer
     specifying the character to be pushed.  *Note:* only one CH can be
     pushed before `getch()' is called.

`flushinp()'
     Flush all input buffers.

`cbreak()'
     Enter cbreak mode.

`nocbreak()'
     Leave cbreak mode.

`echo()'
     Enter echo mode.

`noecho()'
     Leave echo mode.

`nl()'
     Enter nl mode.

`nonl()'
     Leave nl mode.

`raw()'
     Enter raw mode.

`noraw()'
     Leave raw mode.

`meta(yes)'
     If YES is 1, allow 8-bit characters. If YES is 0, allow only 7-bit
     chars.

`keyname(k)'
     Return the name of the key numbered K.


File: python-lib.info,  Node: Window Objects,  Prev: Constants and Functions,  Up: curses

Window Objects
--------------

   Window objects, as returned by `initscr()' and `newwin()' above,
have the following methods:

`refresh()'
     Update the display immediately (sync actual screen with previous
     drawing/deleting methods).

`nooutrefresh()'
     Mark for refresh but wait.

`mvwin(new_y, new_x)'
     Move the window so its upper-left corner is at `(NEW_Y, NEW_X)'.

`move(new_y, new_x)'
     Move cursor to `(NEW_Y, NEW_X)'.

`subwin([nlines, ncols,] begin_y, begin_y)'
     Return a sub-window, whose upper-left corner is at `(BEGIN_Y,
     BEGIN_X)', and whose width/height is NCOLS/NLINES.

     By default, the sub-window will extend from the specified position
     to the lower right corner of the window.

`addch([y, x,] ch[, attr])'
     *Note:* A *character* means a C character (i.e., an ASCII code),
     rather then a Python character (a string of length 1).  (This note
     is true whenever the documentation mentions a character.)

     Paint character CH at `(Y, X)' with attributes ATTR, overwriting
     any character previously painter at that location.  By default,
     the character position and attributes are the current settings for
     the window object.

`insch([y, x,] ch[, attr])'
     Paint character CH at `(Y, X)' with attributes ATTR, moving the
     line from position X right by one character.

`delch([x, y])'
     Delete any character at `(Y, X)'.

`echochar(ch[, attr])'
     Add character CH with attribute ATTR, and immediately call
     `refresh'.

`addstr([y, x,] str[, attr])'
     Paint string STR at `(Y, X)' with attributes ATTR, overwriting
     anything previously on the display.

`attron(attr)'
     Turn on attribute ATTR.

`attroff(attr)'
     Turn off attribute ATTR.

`setattr(attr)'
     Set the current attributes to ATTR.

`standend()'
     Turn off all attributes.

`standout()'
     Turn on attribute A_STANDOUT.

`border([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])'
     Draw a border around the edges of the window. Each parameter
     specifies the character to use for a specific part of the border;
     see the table below for more details.  The characters must be
     specified as integers; using one-character strings will cause
     `TypeError' to be raised.

     *Note:* A `0' value for any parameter will cause the default
     character to be used for that parameter.  Keyword parameters can
     *not* be used.  The defaults are listed in this table:

     Parameter              Description            Default value          
     ------                 -----                  -----                  
     ls                     Left side              `ACS_VLINE'            
     rs                     Right side             `ACS_VLINE'            
     ts                     Top                    `ACS_HLINE'            
     bs                     Bottom                 `ACS_HLINE'            
     tl                     Upper-left corner      `ACS_ULCORNER'         
     tr                     Upper-right corner     `ACS_URCORNER'         
     bl                     Bottom-left corner     `ACS_BLCORNER'         
     br                     Bottom-right corner    `ACS_BRCORNER'         

`box([vertch, horch])'
     Similar to `border()', but both LS and RS are VERTCH and both TS
     and {bs} are HORCH.  The default corner characters are always used
     by this function.

`hline([y, x,] ch, n)'
     Display a horizontal line starting at `(Y, X)' with length N
     consisting of the character CH.

`vline([y, x,] ch, n)'
     Display a vertical line starting at `(Y, X)' with length N
     consisting of the character CH.

`erase()'
     Clear the screen.

`deletln()'
     Delete the line under the cursor. All following lines are moved up
     by 1 line.

`insertln()'
     Insert a blank line under the cursor. All following lines are moved
     down by 1 line.

`getyx()'
     Return a tuple `(Y, X)' of current cursor position.

`getbegyx()'
     Return a tuple `(Y, X)' of co-ordinates of upper-left corner.

`getmaxyx()'
     Return a tuple `(Y, X)' of the height and width of the window.

`clear()'
     Like `erase()', but also causes the whole screen to be repainted
     upon next call to `refresh()'.

`clrtobot()'
     Erase from cursor to the end of the screen: all lines below the
     cursor are deleted, and then the equivalent of `clrtoeol()' is
     performed.

`clrtoeol()'
     Erase from cursor to the end of the line.

`scroll([lines` = 1'])'
     Scroll the screen upward by LINES lines.

`touchwin()'
     Pretend the whole window has been changed, for purposes of drawing
     optimizations.

`touchline(start, count)'
     Pretend COUNT lines have been changed, starting with line START.

`getch([x, y])'
     Get a character. Note that the integer returned does *not* have to
     be in ASCII range: function keys, keypad keys and so on return
     numbers higher then 256. In no-delay mode, an exception is raised
     if there is no input.

`getstr([x, y])'
     Read a string from the user, with primitive line editing capacity.

`inch([x, y])'
     Return the character at the given position in the window. The
     bottom 8 bits are the character proper, and upper bits are the
     attributes.

`clearok(yes)'
     If YES is 1, the next call to `refresh()' will clear the screen
     completely.

`idlok(yes)'
     If called with YES equal to 1, `curses' will try and use hardware
     line editing facilities. Otherwise, line insertion/deletion are
     disabled.

`leaveok(yes)'
     If YES is 1, cursor is left where it is, instead of being at
     "cursor position."  This reduces cursor movement where possible.
     If possible it will be made invisible.

     If YES is 0, cursor will always be at "cursor position" after an
     update.

`setscrreg(top, bottom)'
     Set the scrolling region from line TOP to line BOTTOM. All
     scrolling actions will take place in this region.

`keypad(yes)'
     If YES is 1, escape sequences generated by some keys (keypad,
     function keys) will be interpreted by `curses'.

     If YES is 0, escape sequences will be left as is in the input
     stream.

`nodelay(yes)'
     If YES is 1, `getch()' will be non-blocking.

`notimeout(yes)'
     If YES is 1, escape sequences will not be timed out.

     If YES is 0, after a few milliseconds, an escape sequence will not
     be interpreted, and will be left in the input stream as is.


File: python-lib.info,  Node: getopt,  Next: tempfile,  Prev: curses,  Up: Generic Operating System Services

Parser for command line options.
================================

   Parser for command line options.

   This module helps scripts to parse the command line arguments in
`sys.argv'.  It supports the same conventions as the UNIX `getopt()'
function (including the special meanings of arguments of the form ``-''
and ``-'`-'').  Long options similar to those supported by GNU software
may be used as well via an optional third argument.  This module
provides a single function and an exception:

`getopt(args, options[, long_options])'
     Parses command line options and parameter list.  ARGS is the
     argument list to be parsed, without the leading reference to the
     running program. Typically, this means `sys.argv[1:]'.  OPTIONS is
     the string of option letters that the script wants to recognize,
     with options that require an argument followed by a colon (i.e.,
     the same format that UNIX `getopt()' uses).  If specified,
     LONG_OPTIONS is a list of strings with the names of the long
     options which should be supported.  The leading `'-'`-''
     characters should not be included in the option name.  Options
     which require an argument should be followed by an equal sign
     (`'='').

     The return value consists of two elements: the first is a list of
     `(OPTION, VALUE)' pairs; the second is the list of program
     arguments left after the option list was stripped (this is a
     trailing slice of the first argument).  Each option-and-value pair
     returned has the option as its first element, prefixed with a
     hyphen (e.g., `'-x''), and the option argument as its second
     element, or an empty string if the option has no argument.  The
     options occur in the list in the same order in which they were
     found, thus allowing multiple occurrences.  Long and short options
     may be mixed.

`error'
     This is raised when an unrecognized option is found in the argument
     list or when an option requiring an argument is given none.  The
     argument to the exception is a string indicating the cause of the
     error.  For long options, an argument given to an option which does
     not require one will also cause this exception to be raised.

   An example using only UNIX style options:

     >>> import getopt, string
     >>> args = string.split('-a -b -cfoo -d bar a1 a2')
     >>> args
     ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
     >>> optlist, args = getopt.getopt(args, 'abc:d:')
     >>> optlist
     [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
     >>> args
     ['a1', 'a2']
     >>>

   Using long option names is equally easy:

     >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
     >>> args = string.split(s)
     >>> args
     ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
     >>> optlist, args = getopt.getopt(args, 'x', [
     ...     'condition=', 'output-file=', 'testing'])
     >>> optlist
     [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x',
      '')]
     >>> args
     ['a1', 'a2']
     >>>


File: python-lib.info,  Node: tempfile,  Next: errno,  Prev: getopt,  Up: Generic Operating System Services

Generate temporary file names
=============================

   Generate temporary file names.

   This module generates temporary file names.  It is not UNIX specific,
but it may require some help on non-UNIX systems.

   Note: the modules does not create temporary files, nor does it
automatically remove them when the current process exits or dies.

   The module defines a single user-callable function:

`mktemp()'
     Return a unique temporary filename.  This is an absolute pathname
     of a file that does not exist at the time the call is made.  No
     two calls will return the same filename.

   The module uses two global variables that tell it how to construct a
temporary name.  The caller may assign values to them; by default they
are initialized at the first call to `mktemp()'.

`tempdir'
     When set to a value other than `None', this variable defines the
     directory in which filenames returned by `mktemp()' reside.  The
     default is taken from the environment variable `TMPDIR'; if this
     is not set, either `/usr/tmp' is used (on UNIX), or the current
     working directory (all other systems).  No check is made to see
     whether its value is valid.

`template'
     When set to a value other than `None', this variable defines the
     prefix of the final component of the filenames returned by
     `mktemp()'.  A string of decimal digits is added to generate
     unique filenames.  The default is either `@PID.' where PID is the
     current process ID (on UNIX), or `tmp' (all other systems).

   *Warning:* if a UNIX process uses `mktemp()', then calls `fork()'
and both parent and child continue to use `mktemp()', the processes
will generate conflicting temporary names.  To resolve this, the child
process should assign `None' to `template', to force recomputing the
default on the next call to `mktemp()'.


File: python-lib.info,  Node: errno,  Next: glob,  Prev: tempfile,  Up: Generic Operating System Services

Standard errno system symbols.
==============================

   Standard errno system symbols.

   This module makes available standard errno system symbols.  The
value of each symbol is the corresponding integer value.  The names and
descriptions are borrowed from `linux/include/errno.h', which should be
pretty all-inclusive.

`errorcode'
     Dictionary providing a mapping from the errno value to the string
     name in the underlying system.  For instance,
     `errno.errorcode[errno.EPERM]' maps to `'EPERM''.

   To translate a numeric error code to an error message, use
`os.strerror()'.

   Of the following list, symbols that are not used on the current
platform are not defined by the module.  Symbols available can include:

`EPERM'
     Operation not permitted
`ENOENT'
     No such file or directory
`ESRCH'
     No such process
`EINTR'
     Interrupted system call
`EIO'
     I/O error
`ENXIO'
     No such device or address
`E2BIG'
     Arg list too long
`ENOEXEC'
     Exec format error
`EBADF'
     Bad file number
`ECHILD'
     No child processes
`EAGAIN'
     Try again
`ENOMEM'
     Out of memory
`EACCES'
     Permission denied
`EFAULT'
     Bad address
`ENOTBLK'
     Block device required
`EBUSY'
     Device or resource busy
`EEXIST'
     File exists
`EXDEV'
     Cross-device link
`ENODEV'
     No such device
`ENOTDIR'
     Not a directory
`EISDIR'
     Is a directory
`EINVAL'
     Invalid argument
`ENFILE'
     File table overflow
`EMFILE'
     Too many open files
`ENOTTY'
     Not a typewriter
`ETXTBSY'
     Text file busy
`EFBIG'
     File too large
`ENOSPC'
     No space left on device
`ESPIPE'
     Illegal seek
`EROFS'
     Read-only file system
`EMLINK'
     Too many links
`EPIPE'
     Broken pipe
`EDOM'
     Math argument out of domain of func
`ERANGE'
     Math result not representable
`EDEADLK'
     Resource deadlock would occur
`ENAMETOOLONG'
     File name too long
`ENOLCK'
     No record locks available
`ENOSYS'
     Function not implemented
`ENOTEMPTY'
     Directory not empty
`ELOOP'
     Too many symbolic links encountered
`EWOULDBLOCK'
     Operation would block
`ENOMSG'
     No message of desired type
`EIDRM'
     Identifier removed
`ECHRNG'
     Channel number out of range
`EL2NSYNC'
     Level 2 not synchronized
`EL3HLT'
     Level 3 halted
`EL3RST'
     Level 3 reset
`ELNRNG'
     Link number out of range
`EUNATCH'
     Protocol driver not attached
`ENOCSI'
     No CSI structure available
`EL2HLT'
     Level 2 halted
`EBADE'
     Invalid exchange
`EBADR'
     Invalid request descriptor
`EXFULL'
     Exchange full
`ENOANO'
     No anode
`EBADRQC'
     Invalid request code
`EBADSLT'
     Invalid slot
`EDEADLOCK'
     File locking deadlock error
`EBFONT'
     Bad font file format
`ENOSTR'
     Device not a stream
`ENODATA'
     No data available
`ETIME'
     Timer expired
`ENOSR'
     Out of streams resources
`ENONET'
     Machine is not on the network
`ENOPKG'
     Package not installed
`EREMOTE'
     Object is remote
`ENOLINK'
     Link has been severed
`EADV'
     Advertise error
`ESRMNT'
     Srmount error
`ECOMM'
     Communication error on send
`EPROTO'
     Protocol error
`EMULTIHOP'
     Multihop attempted
`EDOTDOT'
     RFS specific error
`EBADMSG'
     Not a data message
`EOVERFLOW'
     Value too large for defined data type
`ENOTUNIQ'
     Name not unique on network
`EBADFD'
     File descriptor in bad state
`EREMCHG'
     Remote address changed
`ELIBACC'
     Can not access a needed shared library
`ELIBBAD'
     Accessing a corrupted shared library
`ELIBSCN'
     .lib section in a.out corrupted
`ELIBMAX'
     Attempting to link in too many shared libraries
`ELIBEXEC'
     Cannot exec a shared library directly
`EILSEQ'
     Illegal byte sequence
`ERESTART'
     Interrupted system call should be restarted
`ESTRPIPE'
     Streams pipe error
`EUSERS'
     Too many users
`ENOTSOCK'
     Socket operation on non-socket
`EDESTADDRREQ'
     Destination address required
`EMSGSIZE'
     Message too long
`EPROTOTYPE'
     Protocol wrong type for socket
`ENOPROTOOPT'
     Protocol not available
`EPROTONOSUPPORT'
     Protocol not supported
`ESOCKTNOSUPPORT'
     Socket type not supported
`EOPNOTSUPP'
     Operation not supported on transport endpoint
`EPFNOSUPPORT'
     Protocol family not supported
`EAFNOSUPPORT'
     Address family not supported by protocol
`EADDRINUSE'
     Address already in use
`EADDRNOTAVAIL'
     Cannot assign requested address
`ENETDOWN'
     Network is down
`ENETUNREACH'
     Network is unreachable
`ENETRESET'
     Network dropped connection because of reset
`ECONNABORTED'
     Software caused connection abort
`ECONNRESET'
     Connection reset by peer
`ENOBUFS'
     No buffer space available
`EISCONN'
     Transport endpoint is already connected
`ENOTCONN'
     Transport endpoint is not connected
`ESHUTDOWN'
     Cannot send after transport endpoint shutdown
`ETOOMANYREFS'
     Too many references: cannot splice
`ETIMEDOUT'
     Connection timed out
`ECONNREFUSED'
     Connection refused
`EHOSTDOWN'
     Host is down
`EHOSTUNREACH'
     No route to host
`EALREADY'
     Operation already in progress
`EINPROGRESS'
     Operation now in progress
`ESTALE'
     Stale NFS file handle
`EUCLEAN'
     Structure needs cleaning
`ENOTNAM'
     Not a XENIX named type file
`ENAVAIL'
     No XENIX semaphores available
`EISNAM'
     Is a named type file
`EREMOTEIO'
     Remote I/O error
`EDQUOT'
     Quota exceeded


File: python-lib.info,  Node: glob,  Next: fnmatch,  Prev: errno,  Up: Generic Operating System Services

UNIX style pathname pattern expansion
=====================================

   UNIX shell style pathname pattern expansion.

   The `glob' module finds all the pathnames matching a specified
pattern according to the rules used by the UNIX shell.  No tilde
expansion is done, but `*', `?', and character ranges expressed with
`[]' will be correctly matched.  This is done by using the
`os.listdir()' and `fnmatch.fnmatch()' functions in concert, and not by
actually invoking a subshell.  (For tilde and shell variable expansion,
use `os.path.expanduser()' and `os.path.expandvars()'.)

`glob(pathname)'
     Returns a possibly-empty list of path names that match PATHNAME,
     which must be a string containing a path specification.  PATHNAME
     can be either absolute (like `/usr/src/Python-1.5/Makefile') or
     relative (like `../../Tools/*/*.gif'), and can contain shell-style
     wildcards.

   For example, consider a directory containing only the following
files: `1.gif', `2.txt', and `card.gif'.  `glob()' will produce the
following results.  Notice how any leading components of the path are
preserved.

     >>> import glob
     >>> glob.glob('./[0-9].*')
     ['./1.gif', './2.txt']
     >>> glob.glob('*.gif')
     ['1.gif', 'card.gif']
     >>> glob.glob('?.gif')
     ['1.gif']

   See also:

   *Note fnmatch:: Shell-style filename (not path) expansion


File: python-lib.info,  Node: fnmatch,  Next: shutil,  Prev: glob,  Up: Generic Operating System Services

UNIX filename pattern matching
==============================

   UNIX shell style filename pattern matching.

   This module provides support for UNIX shell-style wildcards, which
are *not* the same as regular expressions (which are documented in the
`re' module).  The special characters used in shell-style wildcards are:

``*''
     matches everything

``?''
     matches any single character

``['SEQ` '] matches any character in SEQ'

``[!'SEQ` '] matches any character not in SEQ'
   Note that the filename separator (`'/'' on UNIX) is *not* special to
this module.  See module `glob' for pathname expansion (`glob' uses
`fnmatch()' to match filename segments).

`fnmatch(filename, pattern)'
     Test whether the FILENAME string matches the PATTERN string,
     returning true or false.  If the operating system is
     case-insensitive, then both parameters will be normalized to all
     lower- or upper-case before the comparision is performed.  If you
     require a case-sensitive comparision regardless of whether that's
     standard for your operating system, use `fnmatchcase()' instead.

`fnmatchcase(filename, pattern)'
     Test whether FILENAME matches PATTERN, returning true or false;
     the comparision is case-sensitive.

   See also:

   *Note glob:: Shell-style path expansion


File: python-lib.info,  Node: shutil,  Next: locale,  Prev: fnmatch,  Up: Generic Operating System Services

High-level file operations
==========================

   High-level file operations, including copying.

   This section was written by Fred L. Drake, Jr. <fdrake@acm.org>.
The `shutil' module offers a number of high-level operations on files
and collections of files.  In particular, functions are provided which
support file copying and removal.

   *Caveat:*  On MacOS, the resource fork and other metadata are not
used.  For file copies, this means that resources will be lost and file
type and creator codes will not be correct.

`copyfile(src, dst)'
     Copy the contents of SRC to DST.  If DST exists, it will be
     replaced, otherwise it will be created.

`copymode(src, dst)'
     Copy the permission bits from SRC to DST.  The file contents,
     owner, and group are unaffected.

`copystat(src, dst)'
     Copy the permission bits, last access time, and last modification
     time from SRC to DST.  The file contents, owner, and group are
     unaffected.

`copy(src, dst)'
     Copy the file SRC to the file or directory DST.  If DST is a
     directory, a file with the same basename as SRC is created (or
     overwritten) in the directory specified.  Permission bits are
     copied.

`copy2(src, dst)'
     Similar to `copy()', but last access time and last modification
     time are copied as well.  This is similar to the UNIX command `cp
     -p'.

`copytree(src, dst[, symlinks])'
     Recursively copy an entire directory tree rooted at SRC.  The
     destination directory, named by DST, must not already exist; it
     will be created.  Individual files are copied using `copy2()'.  If
     SYMLINKS is true, symbolic links in the source tree are
     represented as symbolic links in the new tree; if false or
     omitted, the contents of the linked files are copied to the new
     tree.  Errors are reported to standard output.

     The source code for this should be considered an example rather
     than a tool.

`rmtree(path[, ignore_errors[, onerror]])'
     Delete an entire directory tree.  If IGNORE_ERRORS is true, errors
     will be ignored; if false or omitted, errors are handled by
     calling a handler specified by ONERROR or raise an exception.

     If ONERROR is provided, it must be a callable that accepts three
     parameters: FUNCTION, PATH, and EXCINFO.  The first parameter,
     FUNCTION, is the function which raised the exception; it will be
     `os.remove()' or `os.rmdir()'.  The second parameter, PATH, will be
     the path name passed to FUNCTION.  The third parameter, EXCINFO,
     will be the exception information return by `sys.exc_info()'.
     Exceptions raised by ONERROR will not be caught.

* Menu:

* Example::

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

Example
-------

   This example is the implementation of the `copytree()' function,
described above, with the docstring omitted.  It demonstrates many of
the other functions provided by this module.

     def copytree(src, dst, symlinks=0):
         names = os.listdir(src)
         os.mkdir(dst)
         for name in names:
             srcname = os.path.join(src, name)
             dstname = os.path.join(dst, name)
             try:
                 if symlinks and os.path.islink(srcname):
                     linkto = os.readlink(srcname)
                     os.symlink(linkto, dstname)
                 elif os.path.isdir(srcname):
                     copytree(srcname, dstname)
                 else:
                     copy2(srcname, dstname)
                 # XXX What about devices, sockets etc.?
             except (IOError, os.error), why:
                 print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))

