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

   April 15, 2001		2.1


File: python-lib.info,  Node: 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.

   The module defines the following user-callable functions:

`mktemp([suffix])'
     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.  SUFFIX, if provided, is
     used as the last part of the generated file name.  This can be
     used to provide a filename extension or other identifying
     information that may be useful on some platforms.

`TemporaryFile([mode[, bufsize[, suffix]]])'
     Return a file (or file-like) object that can be used as a temporary
     storage area.  The file is created in the most secure manner
     available in the appropriate temporary directory for the host
     platform.  Under UNIX, the directory entry to the file is removed
     so that it is secure against attacks which involve creating
     symbolic links to the file or replacing the file with a symbolic
     link to some other file.  For other platforms, which don't allow
     removing the directory entry while the file is in use, the file is
     automatically deleted as soon as it is closed (including an
     implicit close when it is garbage-collected).

     The MODE parameter defaults to `'w+b'' so that the file created
     can be read and written without being closed.  Binary mode is used
     so that it behaves consistently on all platforms without regard
     for the data that is stored.  BUFSIZE defaults to `-1', meaning
     that the operating system default is used.  SUFFIX is passed to
     `mktemp()'.

   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.

`gettempprefix()'
     Return the filename prefix used to create temporary files.  This
     does not contain the directory component.  Using this function is
     preferred over using the `template' variable directly.  _Added in
     Python version 1.5.2_

`template'
     _This is deprecated in Python 2.0.  Use `gettempprefix()' instead._
     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), `~PID-' on Windows NT, `Python-Tmp-'
     on MacOS, or `tmp' (all other systems).

     Older versions of this module used to require that `template' be
     set to `None' after a call to `os.fork()'; this has not been
     necessary since version 1.5.2.


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.  The specific list of defined
symbols is available as `errno.errorcode.keys()'.  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:

Pattern                              Meaning
------                               -----
*                                    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 pathname segments).  Similarly, filenames starting
with a period are not special for this module, and are matched by the
`*' and `?' patterns.

`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 comparison is performed.  If you
     require a case-sensitive comparison 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 comparison is case-sensitive.

   See also:

   *Note glob:: UNIX 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 the file named SRC to a file named DST.  If
     DST exists, it will be replaced, otherwise it will be created.

`copyfileobj(fsrc, fdst[, length])'
     Copy the contents of the file-like object FSRC to the file-like
     object FDST.  The integer LENGTH, if given, is the buffer size. In
     particular, a negative LENGTH value means to copy the data without
     looping over the source data in chunks; by default the data is
     read in chunks to avoid uncontrolled memory consumption.

`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 4::


File: python-lib.info,  Node: Example 4,  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))

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

Internationalization services
=============================

   Internationalization services.  This module was documented by Martin
von L"owis <loewis@informatik.hu-berlin.de>.
This section was written by Martin von L"owis
<loewis@informatik.hu-berlin.de>.
The `locale' module opens access to the POSIX locale database and
functionality. The POSIX locale mechanism allows programmers to deal
with certain cultural issues in an application, without requiring the
programmer to know all the specifics of each country where the software
is executed.

   The `locale' module is implemented on top of the `_locale' module,
which in turn uses an ANSI C locale implementation if available.

   The `locale' module defines the following exception and functions:

`Error'
     Exception raised when `setlocale()' fails.

`setlocale(category[, locale])'
     If LOCALE is specified, it may be a string, a tuple of the form
     `(LANGUAGE CODE, ENCODING)', or `None'.  If it is a tuple, it is
     converted to a string using the locale aliasing engine.  If LOCALE
     is given and not `None', `setlocale()' modifies the locale setting
     for the CATEGORY.  The available categories are listed in the data
     description below.  The value is the name of a locale.  An empty
     string specifies the user's default settings. If the modification
     of the locale fails, the exception `Error' is raised.  If
     successful, the new locale setting is returned.

     If LOCALE is omitted or `None', the current setting for CATEGORY
     is returned.

     `setlocale()' is not thread safe on most systems.  Applications
     typically start with a call of

          import locale
          locale.setlocale(locale.LC_ALL, '')

     This sets the locale for all categories to the user's default
     setting (typically specified in the `LANG' environment variable).
     If the locale is not changed thereafter, using multithreading
     should not cause problems.

     _Changed in Python version 2.0_

`localeconv()'
     Returns the database of of the local conventions as a dictionary.
     This dictionary has the following strings as keys:

     Key                    Category               Meaning
     ------                 -----                  -----
     LC_NUMERIC             `'decimal_point''      Decimal point
                                                   character.
                            `'grouping''           Sequence of numbers
                                                   specifying which
                                                   relative positions
                                                   the `'thousands_sep''
                                                   is expected.  If the
                                                   sequence is
                                                   terminated with
                                                   `CHAR_MAX', no
                                                   further grouping is
                                                   performed. If the
                                                   sequence terminates
                                                   with a `0',  the last
                                                   group size is
                                                   repeatedly used.
                            `'thousands_sep''      Character used
                                                   between groups.
     LC_MONETARY            `'int_curr_symbol''    International
                                                   currency symbol.
                            `'currency_symbol''    Local currency symbol.
                            `'mon_decimal_point''  Decimal point used
                                                   for monetary values.
                            `'mon_thousands_sep''  Group separator used
                                                   for monetary values.
                            `'mon_grouping''       Equivalent to
                                                   `'grouping'', used
                                                   for monetary values.
                            `'positive_sign''      Symbol used to
                                                   annotate a positive
                                                   monetary value.
                            `'negative_sign''      Symbol used to
                                                   annotate a nnegative
                                                   monetary value.
                            `'frac_digits''        Number of fractional
                                                   digits used in local
                                                   formatting of
                                                   monetary values.
                            `'int_frac_digits''    Number of fractional
                                                   digits used in
                                                   international
                                                   formatting of
                                                   monetary values.

     The possible values for `'p_sign_posn'' and `'n_sign_posn'' are
     given below.

     Value                              Explanation
     ------                             -----
     0                                  Currency and value are surrounded
                                        by parentheses.
     1                                  The sign should precede the value
                                        and currency symbol.
     2                                  The sign should follow the value
                                        and currency symbol.
     3                                  The sign should immediately
                                        precede the value.
     4                                  The sign should immediately
                                        follow the value.
     `LC_MAX'                           Nothing is specified in this
                                        locale.

`getdefaultlocale([envvars])'
     Tries to determine the default locale settings and returns them as
     a tuple of the form `(LANGUAGE CODE, ENCODING)'.

     According to POSIX, a program which has not called
     `setlocale(LC_ALL, '')' runs using the portable `'C'' locale.
     Calling `setlocale(LC_ALL, '')' lets it use the default locale as
     defined by the `LANG' variable.  Since we do not want to interfere
     with the current locale setting we thus emulate the behavior in
     the way described above.

     To maintain compatibility with other platforms, not only the
     `LANG' variable is tested, but a list of variables given as
     envvars parameter.  The first found to be defined will be used.
     ENVVARS defaults to the search path used in GNU gettext; it must
     always contain the variable name `LANG'.  The GNU gettext search
     path contains `'LANGUAGE'', `'LC_ALL'', code{'LC_CTYPE'}, and
     `'LANG'', in that order.

     Except for the code `'C'', the language code corresponds to RFC
     1766.  LANGUAGE CODE and ENCODING may be `None' if their values
     cannot be determined.  _Added in Python version 2.0_

`getlocale([category])'
     Returns the current setting for the given locale category as tuple
     (language code, encoding).  CATEGORY may be one of the `LC_*'
     values except `LC_ALL'.  It defaults to `LC_CTYPE'.

     Except for the code `'C'', the language code corresponds to RFC
     1766.  LANGUAGE CODE and ENCODING may be `None' if their values
     cannot be determined.  _Added in Python version 2.0_

`normalize(localename)'
     Returns a normalized locale code for the given locale name.  The
     returned locale code is formatted for use with `setlocale()'.  If
     normalization fails, the original name is returned unchanged.

     If the given encoding is not known, the function defaults to the
     default encoding for the locale code just like `setlocale()'.
     _Added in Python version 2.0_

`resetlocale([category])'
     Sets the locale for CATEGORY to the default setting.

     The default setting is determined by calling `getdefaultlocale()'.
     CATEGORY defaults to `LC_ALL'.  _Added in Python version 2.0_

`strcoll(string1, string2)'
     Compares two strings according to the current `LC_COLLATE'
     setting. As any other compare function, returns a negative, or a
     positive value, or `0', depending on whether STRING1 collates
     before or after STRING2 or is equal to it.

`strxfrm(string)'
     Transforms a string to one that can be used for the built-in
     function `cmp()', and still returns locale-aware results.  This
     function can be used when the same string is compared repeatedly,
     e.g. when collating a sequence of strings.

`format(format, val[, grouping])'
     Formats a number VAL according to the current `LC_NUMERIC'
     setting.  The format follows the conventions of the `%' operator.
     For floating point values, the decimal point is modified if
     appropriate.  If GROUPING is true, also takes the grouping into
     account.

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

`atof(string)'
     Converts a string to a floating point number, following the
     `LC_NUMERIC' settings.

`atoi(string)'
     Converts a string to an integer, following the `LC_NUMERIC'
     conventions.

`LC_CTYPE'
     Locale category for the character type functions.  Depending on the
     settings of this category, the functions of module `string'
     dealing with case change their behaviour.

`LC_COLLATE'
     Locale category for sorting strings.  The functions `strcoll()'
     and `strxfrm()' of the `locale' module are affected.

`LC_TIME'
     Locale category for the formatting of time.  The function
     `time.strftime()' follows these conventions.

`LC_MONETARY'
     Locale category for formatting of monetary values.  The available
     options are available from the `localeconv()' function.

`LC_MESSAGES'
     Locale category for message display. Python currently does not
     support application specific locale-aware messages.  Messages
     displayed by the operating system, like those returned by
     `os.strerror()' might be affected by this category.

`LC_NUMERIC'
     Locale category for formatting numbers.  The functions `format()',
     `atoi()', `atof()' and `str()' of the `locale' module are affected
     by that category.  All other numeric formatting operations are not
     affected.

`LC_ALL'
     Combination of all locale settings.  If this flag is used when the
     locale is changed, setting the locale for all categories is
     attempted. If that fails for any category, no category is changed
     at all.  When the locale is retrieved using this flag, a string
     indicating the setting for all categories is returned. This string
     can be later used to restore the settings.

`CHAR_MAX'
     This is a symbolic constant used for different values returned by
     `localeconv()'.

   Example:

     >>> import locale
     >>> loc = locale.setlocale(locale.LC_ALL) # get current locale
     >>> locale.setlocale(locale.LC_ALL, 'de') # use German locale
     >>> locale.strcoll('f\xe4n', 'foo') # compare a string containing an umlaut
     >>> locale.setlocale(locale.LC_ALL, '') # use user's preferred locale
     >>> locale.setlocale(locale.LC_ALL, 'C') # use default (C) locale
     >>> locale.setlocale(locale.LC_ALL, loc) # restore saved locale

* Menu:

* Background::
* For extension writers and programs that embed Python::


File: python-lib.info,  Node: Background,  Next: For extension writers and programs that embed Python,  Prev: locale,  Up: locale

Background, details, hints, tips and caveats
--------------------------------------------

   The C standard defines the locale as a program-wide property that may
be relatively expensive to change.  On top of that, some implementation
are broken in such a way that frequent locale changes may cause core
dumps.  This makes the locale somewhat painful to use correctly.

   Initially, when a program is started, the locale is the `C' locale,
no matter what the user's preferred locale is.  The program must
explicitly say that it wants the user's preferred locale settings by
calling `setlocale(LC_ALL, '')'.

   It is generally a bad idea to call `setlocale()' in some library
routine, since as a side effect it affects the entire program.  Saving
and restoring it is almost as bad: it is expensive and affects other
threads that happen to run before the settings have been restored.

   If, when coding a module for general use, you need a locale
independent version of an operation that is affected by the locale
(e.g. `string.lower()', or certain formats used with
`time.strftime()')), you will have to find a way to do it without using
the standard library routine.  Even better is convincing yourself that
using locale settings is okay.  Only as a last resort should you
document that your module is not compatible with non-`C' locale
settings.

   The case conversion functions in the `string' and `strop' modules
are affected by the locale settings.  When a call to the `setlocale()'
function changes the `LC_CTYPE' settings, the variables
`string.lowercase', `string.uppercase' and `string.letters' (and their
counterparts in `strop') are recalculated.  Note that this code that
uses these variable through ``from' ... `import' ...', e.g. `from
string import letters', is not affected by subsequent `setlocale()'
calls.

   The only way to perform numeric operations according to the locale
is to use the special functions defined by this module: `atof()',
`atoi()', `format()', `str()'.


File: python-lib.info,  Node: For extension writers and programs that embed Python,  Prev: Background,  Up: locale

For extension writers and programs that embed Python
----------------------------------------------------

   Extension modules should never call `setlocale()', except to find
out what the current locale is.  But since the return value can only be
used portably to restore it, that is not very useful (except perhaps to
find out whether or not the locale is `C').

   When Python is embedded in an application, if the application sets
the locale to something specific before initializing Python, that is
generally okay, and Python will use whatever locale is set, _except_
that the `LC_NUMERIC' locale should always be `C'.

   The `setlocale()' function in the `locale' module gives the Python
programmer the impression that you can manipulate the `LC_NUMERIC'
locale setting, but this not the case at the C level: C code will
always find that the `LC_NUMERIC' locale setting is `C'.  This is
because too much would break when the decimal point character is set to
something else than a period (e.g. the Python parser would break).
Caveat: threads that run without holding Python's global interpreter
lock may occasionally find that the numeric locale setting differs;
this is because the only portable way to implement this feature is to
set the numeric locale settings to what the user requests, extract the
relevant characteristics, and then restore the `C' numeric locale.

   When Python code uses the `locale' module to change the locale, this
also affects the embedding application.  If the embedding application
doesn't want this to happen, it should remove the `_locale' extension
module (which does all the work) from the table of built-in modules in
the `config.c' file, and make sure that the `_locale' module is not
accessible as a shared library.

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

Multilingual internationalization services
==========================================

   Multilingual internationalization services.  This module was
documented by Barry A. Warsaw <barry@digicool.com>.
This section was written by Barry A. Warsaw <barry@digicool.com>.
The `gettext' module provides internationalization (I18N) and
localization (L10N) services for your Python modules and applications.
It supports both the GNU `gettext' message catalog API and a higher
level, class-based API that may be more appropriate for Python files.
The interface described below allows you to write your module and
application messages in one natural language, and provide a catalog of
translated messages for running under different natural languages.

   Some hints on localizing your Python modules and applications are
also given.

* Menu:

* GNU gettext API::
* Class-based API::
* Internationalizing your programs and modules::
* Acknowledgements::


File: python-lib.info,  Node: GNU gettext API,  Next: Class-based API,  Prev: gettext,  Up: gettext

GNU `gettext' API
-----------------

   The `gettext' module defines the following API, which is very
similar to the GNU `gettext' API.  If you use this API you will affect
the translation of your entire application globally.  Often this is
what you want if your application is monolingual, with the choice of
language dependent on the locale of your user.  If you are localizing a
Python module, or if your application needs to switch languages on the
fly, you probably want to use the class-based API instead.

`bindtextdomain(domain[, localedir])'
     Bind the DOMAIN to the locale directory LOCALEDIR.  More
     concretely, `gettext' will look for binary `.mo' files for the
     given domain using the path (on UNIX):
     `LOCALEDIR/LANGUAGE/LC_MESSAGES/DOMAIN.mo', where LANGUAGES is
     searched for in the environment variables `LANGUAGE', `LC_ALL',
     `LC_MESSAGES', and `LANG' respectively.

     If LOCALEDIR is omitted or `None', then the current binding for
     DOMAIN is returned.(1)

`textdomain([domain])'
     Change or query the current global domain.  If DOMAIN is `None',
     then the current global domain is returned, otherwise the global
     domain is set to DOMAIN, which is returned.

`gettext(message)'
     Return the localized translation of MESSAGE, based on the current
     global domain, language, and locale directory.  This function is
     usually aliased as `_' in the local namespace (see examples below).

`dgettext(domain, message)'
     Like `gettext()', but look the message up in the specified DOMAIN.

   Note that GNU `gettext' also defines a `dcgettext()' method, but
this was deemed not useful and so it is currently unimplemented.

   Here's an example of typical usage for this API:

     import gettext
     gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
     gettext.textdomain('myapplication')
     _ = gettext.gettext
     # ...
     print _('This is a translatable string.')

   ---------- Footnotes ----------

   (1)  The default locale directory is system dependent; e.g. on
RedHat Linux it is `/usr/share/locale', but on Solaris it is
`/usr/lib/locale'.  The `gettext' module does not try to support these
system dependent defaults; instead its default is
``sys.prefix'/share/locale'.  For this reason, it is always best to
call `bindtextdomain()' with an explicit absolute path at the start of
your application.


File: python-lib.info,  Node: Class-based API,  Next: Internationalizing your programs and modules,  Prev: GNU gettext API,  Up: gettext

Class-based API
---------------

   The class-based API of the `gettext' module gives you more
flexibility and greater convenience than the GNU `gettext' API.  It is
the recommended way of localizing your Python applications and modules.
`gettext' defines a "translations" class which implements the parsing
of GNU `.mo' format files, and has methods for returning either
standard 8-bit strings or Unicode strings.  Translations instances can
also install themselves in the built-in namespace as the function `_()'.

`find(domain[, localedir[, languages]])'
     This function implements the standard `.mo' file search algorithm.
     It takes a DOMAIN, identical to what `textdomain()' takes, and
     optionally a LOCALEDIR (as in `bindtextdomain()'), and a list of
     languages.  All arguments are strings.

     If LOCALEDIR is not given, then the default system locale
     directory is used.(1)  If LANGUAGES is not given, then the
     following environment variables are searched: `LANGUAGE',
     `LC_ALL', `LC_MESSAGES', and `LANG'.  The first one returning a
     non-empty value is used for the LANGUAGES variable.  The
     environment variables can contain a colon separated list of
     languages, which will be split.

     `find()' then expands and normalizes the languages, and then
     iterates through them, searching for an existing file built of
     these components:

     `LOCALEDIR/LANGUAGE/LC_MESSAGES/DOMAIN.mo'

     The first such file name that exists is returned by `find()'.  If
     no such file is found, then `None' is returned.

`translation(domain[, localedir[, languages[, class_]]])'
     Return a `Translations' instance based on the DOMAIN, LOCALEDIR,
     and LANGUAGES, which are first passed to `find()' to get the
     associated `.mo' file path.  Instances with identical `.mo' file
     names are cached.  The actual class instantiated is either CLASS_
     if provided, otherwise `GNUTranslations'.  The class's constructor
     must take a single file object argument.  If no `.mo' file is
     found, this function raises `IOError'.

`install(domain[, localedir[, unicode]])'
     This installs the function `_' in Python's builtin namespace,
     based on DOMAIN, and LOCALEDIR which are passed to the function
     `translation()'.  The UNICODE flag is passed to the resulting
     translation object's `install' method.

     As seen below, you usually mark the strings in your application
     that are candidates for translation, by wrapping them in a call to
     the function `_()', e.g.

          print _('This string will be translated.')

     For convenience, you want the `_()' function to be installed in
     Python's builtin namespace, so it is easily accessible in all
     modules of your application.

* Menu:

* NullTranslations class::
* GNUTranslations class::
* Solaris message catalog support::
* Catalog constructor::

   ---------- Footnotes ----------

   (1) See the footnote for `bindtextdomain()' above.


File: python-lib.info,  Node: NullTranslations class,  Next: GNUTranslations class,  Prev: Class-based API,  Up: Class-based API

The `NullTranslations' class
............................

   Translation classes are what actually implement the translation of
original source file message strings to translated message strings.
The base class used by all translation classes is `NullTranslations';
this provides the basic interface you can use to write your own
specialized translation classes.  Here are the methods of
`NullTranslations':

`__init__([fp])'
     Takes an optional file object FP, which is ignored by the base
     class.  Initializes "protected" instance variables _INFO and
     _CHARSET which are set by derived classes.  It then calls
     `self._parse(fp)' if FP is not `None'.

`_parse(fp)'
     No-op'd in the base class, this method takes file object FP, and
     reads the data from the file, initializing its message catalog.  If
     you have an unsupported message catalog file format, you should
     override this method to parse your format.

`gettext(message)'
     Return the translated message.  Overridden in derived classes.

`ugettext(message)'
     Return the translated message as a Unicode string.  Overridden in
     derived classes.

`info()'
     Return the "protected" `_info' variable.

`charset()'
     Return the "protected" `_charset' variable.

`install([unicode])'
     If the UNICODE flag is false, this method installs
     `self.gettext()' into the built-in namespace, binding it to `_'.
     If UNICODE is true, it binds `self.ugettext()' instead.  By
     default, UNICODE is false.

     Note that this is only one way, albeit the most convenient way, to
     make the `_' function available to your application.  Because it
     affects the entire application globally, and specifically the
     built-in namespace, localized modules should never install `_'.
     Instead, they should use this code to make `_' available to their
     module:

          import gettext
          t = gettext.translation('mymodule', ...)
          _ = t.gettext

     This puts `_' only in the module's global namespace and so only
     affects calls within this module.


File: python-lib.info,  Node: GNUTranslations class,  Next: Solaris message catalog support,  Prev: NullTranslations class,  Up: Class-based API

The `GNUTranslations' class
...........................

   The `gettext' module provides one additional class derived from
`NullTranslations': `GNUTranslations'.  This class overrides `_parse()'
to enable reading GNU `gettext' format `.mo' files in both big-endian
and little-endian format.

   It also parses optional meta-data out of the translation catalog.  It
is convention with GNU `gettext' to include meta-data as the
translation for the empty string.  This meta-data is in RFC 822-style
`key: value' pairs.  If the key `Content-Type' is found, then the
`charset' property is used to initialize the "protected" `_charset'
instance variable.  The entire set of key/value pairs are placed into a
dictionary and set as the "protected" `_info' instance variable.

   If the `.mo' file's magic number is invalid, or if other problems
occur while reading the file, instantiating a `GNUTranslations' class
can raise `IOError'.

   The other usefully overridden method is `ugettext()', which returns
a Unicode string by passing both the translated message string and the
value of the "protected" `_charset' variable to the builtin `unicode()'
function.


File: python-lib.info,  Node: Solaris message catalog support,  Next: Catalog constructor,  Prev: GNUTranslations class,  Up: Class-based API

Solaris message catalog support
...............................

   The Solaris operating system defines its own binary `.mo' file
format, but since no documentation can be found on this format, it is
not supported at this time.


File: python-lib.info,  Node: Catalog constructor,  Prev: Solaris message catalog support,  Up: Class-based API

The Catalog constructor
.......................

   GNOME uses a version of the `gettext' module by James Henstridge,
but this version has a slightly different API.  Its documented usage
was:

     import gettext
     cat = gettext.Catalog(domain, localedir)
     _ = cat.gettext
     print _('hello world')

   For compatibility with this older module, the function `Catalog()'
is an alias for the the `translation()' function described above.

   One difference between this module and Henstridge's: his catalog
objects supported access through a mapping API, but this appears to be
unused and so is not currently supported.


File: python-lib.info,  Node: Internationalizing your programs and modules,  Next: Acknowledgements,  Prev: Class-based API,  Up: gettext

Internationalizing your programs and modules
--------------------------------------------

   Internationalization (I18N) refers to the operation by which a
program is made aware of multiple languages.  Localization (L10N)
refers to the adaptation of your program, once internationalized, to
the local language and cultural habits.  In order to provide
multilingual messages for your Python programs, you need to take the
following steps:

  1. prepare your program or module by specially marking translatable
     strings

  2. run a suite of tools over your marked files to generate raw
     messages catalogs

  3. create language specific translations of the message catalogs

  4. use the `gettext' module so that message strings are properly
     translated

   In order to prepare your code for I18N, you need to look at all the
strings in your files.  Any string that needs to be translated should
be marked by wrapping it in `_('...')' - i.e. a call to the function
`_()'.  For example:

     filename = 'mylog.txt'
     message = _('writing a log message')
     fp = open(filename, 'w')
     fp.write(message)
     fp.close()

   In this example, the string `'writing a log message'' is marked as a
candidate for translation, while the strings `'mylog.txt'' and `'w''
are not.

   The Python distribution comes with two tools which help you generate
the message catalogs once you've prepared your source code.  These may
or may not be available from a binary distribution, but they can be
found in a source distribution, in the `Tools/i18n' directory.

   The `pygettext'(1) program scans all your Python source code looking
for the strings you previously marked as translatable.  It is similar
to the GNU `gettext' program except that it understands all the
intricacies of Python source code, but knows nothing about C or C++
source code.  You don't need GNU `gettext' unless you're also going to
be translating C code (e.g. C extension modules).

   `pygettext' generates textual Uniforum-style human readable message
catalog `.pot' files, essentially structured human readable files which
contain every marked string in the source code, along with a
placeholder for the translation strings.  `pygettext' is a command line
script that supports a similar command line interface as `xgettext';
for details on its use, run:

     pygettext.py --help

   Copies of these `.pot' files are then handed over to the individual
human translators who write language-specific versions for every
supported natural language.  They send you back the filled in
language-specific versions as a `.po' file.  Using the `msgfmt.py'(2)
program (in the `Tools/i18n' directory), you take the `.po' files from
your translators and generate the machine-readable `.mo' binary catalog
files.  The `.mo' files are what the `gettext' module uses for the
actual translation processing during run-time.

   How you use the `gettext' module in your code depends on whether you
are internationalizing your entire application or a single module.

* Menu:

* Localizing your module::
* Localizing your application::
* Changing languages on the fly::
* Deferred translations::

   ---------- Footnotes ----------

   (1) Franc,ois Pinard has written a program called `xpot' which does
a similar job.  It is available as part of his `po-utils' package at
<http://www.iro.umontreal.ca/contrib/po-utils/HTML>.

   (2) `msgfmt.py' is binary compatible with GNU `msgfmt' except that
it provides a simpler, all-Python implementation.  With this and
`pygettext.py', you generally won't need to install the GNU `gettext'
package to internationalize your Python applications.


File: python-lib.info,  Node: Localizing your module,  Next: Localizing your application,  Prev: Internationalizing your programs and modules,  Up: Internationalizing your programs and modules

Localizing your module
......................

   If you are localizing your module, you must take care not to make
global changes, e.g. to the built-in namespace.  You should not use the
GNU `gettext' API but instead the class-based API.

   Let's say your module is called "spam" and the module's various
natural language translation `.mo' files reside in `/usr/share/locale'
in GNU `gettext' format.  Here's what you would put at the top of your
module:

     import gettext
     t = gettext.translation('spam', '/usr/share/locale')
     _ = t.gettext

   If your translators were providing you with Unicode strings in their
`.po' files, you'd instead do:

     import gettext
     t = gettext.translation('spam', '/usr/share/locale')
     _ = t.ugettext


File: python-lib.info,  Node: Localizing your application,  Next: Changing languages on the fly,  Prev: Localizing your module,  Up: Internationalizing your programs and modules

Localizing your application
...........................

   If you are localizing your application, you can install the `_()'
function globally into the built-in namespace, usually in the main
driver file of your application.  This will let all your
application-specific files just use `_('...')' without having to
explicitly install it in each file.

   In the simple case then, you need only add the following bit of code
to the main driver file of your application:

     import gettext
     gettext.install('myapplication')

   If you need to set the locale directory or the UNICODE flag, you can
pass these into the `install()' function:

     import gettext
     gettext.install('myapplication', '/usr/share/locale', unicode=1)

