Python Programming on Win32: Appendix A - Key Python Modules and Functions


The Python library is huge (231 files in the latest Windows distribution), but a full library reference in HTML format is included with every Python installation. You may also download printable versions in PostScript or PDF formats from www.python.org and circulate copies without restriction: the document is a similar size to this book.

As a convenience to the armchair reader we have included the key functions and modules that are likely to be used by most nontrivial programs. These are nearly direct reproductions from the Python Library. The Python Library is also Open Source, but we are required to include this copyright notice:

The Python Library Reference is Copyright © 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. All Rights Reserved.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI or Corporation for National Research Initiatives or CNRI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.

This appendix covers:

Methods of built-in types such as lists, dictionaries, and files

Built-in functions

The sys module

The os and os.path modules

The string module

Built-in Types

The following sections describe the standard types that are built into the interpreter. These are the numeric types, sequence types, and several others, including types themselves. There is no explicit boolean type; use integers instead.

Some operations are supported by several object types; in particular, all objects can be compared, tested for truth value, and converted to a string (with the notation ' '). The latter conversion is implicitly used when an object is written by the print statement.

Truth Value Testing

Any object can be tested for truth value, to use in an if or while condition or as operand of the boolean operations below. The following values are considered false:

None

Zero of any numeric type, e.g., 0, 0L, 0.0

Any empty sequence, e.g., '', (), []

Any empty mapping, e.g., {}

Instances of user-defined classes, if the class defines a __nonzero__() or __len__()- method, when that method returns zero.

All other values are considered true, so objects of many types are always true.

Operations and built-in functions that have a boolean result always return 0 for false and 1 for true, unless otherwise stated. Important exceptions are the boolean operations or and and, which always return one of their operands.

Boolean Operations

The following table depicts the boolean operations, ordered by ascending priority.

OperationResultNotes
x or yIf x is false, then y, else x1
x and yIf x is false, then x, else y1
not xIf x is false, then 1, else 02

Notes

1. These evaluate their second argument only if needed for their outcome.

2. ''Not" has a lower priority than non-boolean operators, e.g., not a == b is interpreted as not(a == b), and a == not b is a syntax error.

Comparisons

Comparison operations are supported by all objects. They have the same priority (which is higher than that of the boolean operations). Comparisons can be chained arbitrarily. e.g., x < y <=z is equivalent to x < y and y <=z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

The following table summarizes the comparison operations.

OperationMeaningNotes
<Strictly less than 
<=Less than or equal 
>Strictly greater than 
>=Greater than or equal 
==Equal 
<>Not equal1
!=Not equal1
IsObject identity 
is notNegated object identity 

Notes

1. <> and != are alternate spellings for the same operator. (We couldn't choose between ABC and C!)

Objects of different types, except different numeric types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (e.g., windows) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently.

Implementation note: objects of different types except numbers are ordered by their type names; objects of the same types that don't support proper comparison are ordered by their address.

Two more operations with the same syntactic priority, in and not in , are supported only by sequence types, see the later section "Sequence Types".

Numeric Types

There are four numeric types: plain integers, long integers, floating-point numbers, and complex numbers. Plain integers (also just called integers) are implemented using long in C. which gives them at least 32 bits of precision. Long integers have unlimited precision. Floating-point numbers are implemented using double in C. All bets on their precision are off unless you happen to know the machine you are working with.

Complex numbers have a real and imaginary part, which are both implemented using double in C. To extract these parts from a complex number z, use z.real and z.imag.

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex and octal numbers) yield plain integers. Integer literals with an L or l suffix yield long integers (L is preferred because 11 looks too much like eleven!). Numeric literals containing a decimal point or an exponent sign yield floating-point numbers. Appending j or J to a numeric literal yields a complex number.

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the "smaller" type is converted to that of the other, where a plain integer is smaller than a long integer is smaller than a floating point is smaller than a complex. Comparisons between number of mixed type use the same rule.* The functions int(), long(), float(), and complex() can force numbers to a specific type.

All numeric types support the operations in the following table, sorted by ascending priority (operations in the same box have the same priority; all numeric operations have a higher priority than comparison operations).

OperationResultNotes
x + ySum of x and y 
x - yDifference of x and y 
x * yProduct of x and y 
x / yQuotient of x and y1
x % yRemainder of x / y 
-xx negated 
+xx unchanged 
abs(x)Absolute value or magnitude of x 
int(x)x converted to integer2
long(x)x converted to long integer2
float(x)x converted to floating point 
complex(re,im)A complex number with real part re, imaginary part im; im defaults to zero 
c.conjugate()Conjugate of the complex number c 

* As a consequence, the list [1,2] is considered equal to [1.0,2.0] and similar for tuples.
OperationResultNotes
divmond(x, y)The pair (x / y, x % y)3
pow(x, y)x to the power y 
x ** yx to the power y 

Notes

1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0.

2. Conversion from floating-point to (long or plain) integer may round or truncate as in C; see functions floor() and ceil() in the math module for well-defined conversions.

3. See the section "Built-in Functions" for an exact definition.

Bit-String Operations on Integer Types

Plain and long integer types support additional operations that make sense only for bit strings. Negative numbers are treated as their 2's complement value (for long integers, this assumes a sufficiently large number of bits so that no overflow occurs during the operation).

The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ has the same priority as the other unary numeric operations (+ and -).

The following table lists the bit-string operations sorted in ascending priority (operations in the same box have the same priority).

OperationResultNotes
x ¦ yBitwise or of x and y 
x   yBitwise exclusive or of x and y 
x & yBitwise and of x and y 
x < nx shifted left by n bits1,2
x >> nx shifted right by n bits1,3
~xThe bits of x inverted 

Notes

1. Negative shift counts are illegal and cause a ValueError to be raised.

2. A left shift by n bits is equivalent to multiplication by pow(2, n) without over-flow check.

3. A right shift by n bits is equivalent to division by pow(2, n) without overflow check.

Sequence Types

There are three sequence types: strings, lists, and tuples. String literals are written in single or double quotes: 'xyzzy', "frobozz". See Chapter 2 of the Python reference manual for more about string literals. Lists are constructed with square brackets, separating items with commas: [a, b, c]. Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, e.g., a, b, c or (). A single item tuple must have a trailing comma, e.g., (d,)

Sequence types support the following operations. The in and not in operations have the same priorities as the comparison operations. The + and * operations have the same priority as the corresponding numeric operations.*

The following table lists the sequence operations sorted in ascending priority (operations in the same box have the same priority). s and t are sequences of the same type; n, i, and j are integers.

OperationResultNotes
x in s1 if an item of s is equal to x, else 0 
x not in s0 if an item of s is equal to x, else 1 
s + tThe concatenation of s and t 
s * n , n * sn copies of s concatenated3
s[i]i'th item of s, origin 01
s[i:j]Slice of s from i to j1,2
len(s)Length of s 
min(s)Smallest item of s 
max(s)Largest item of s 

Notes

1. If i or j is negative, the index is relative to the end of the string; i.e., len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

2. The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted, use 0. If j is omitted, use len(s). If i is greater than or equal to j, the slice is empty.

* They must have since the parser can't tell the type of the operands

3. Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s).

More String Operations

String objects have one unique built-in operation: the %operator (modulo) with a string left argument interprets this string as a C sprintf() format string to be applied to the right argument and returns the string resulting from this formatting operation.

The right argument should be a tuple with one item for each argument required by the format string; if the string requires a single argument, the right argument may also be a single nontuple object.* The following format characters are understood: %, c, s, i, d, u, o, x, X, e, E, f, g, G. Width and precision may be a * to specify that an integer argument specifies the actual width or precision. The flag characters -, +, blank, #, and 0 are understood. The size specifiers h, l, or L may be present but are ignored. The %s conversion takes any Python object and converts it to a string using str() before formatting it. The ANSI features %p and %n aren't supported. Since Python strings have an explicit length, %s conversions don't assume that \0 is the end of the string.

For safety reasons, floating-point precisions are clipped to 50; %f conversions for numbers whose absolute value is over le25 are replaced by %g conversions.' All other errors raise exceptions.

If the right argument is a dictionary (or any kind of mapping), the formats in the string must have a parenthesized key into that dictionary inserted immediately after the % character, and each format then formats the corresponding entry from the mapping. For example:

>>> count = 2
>>> language = 'Python'
>>> print'%(language)s has %(count)03d quote types.' % vars()
Python has 002 quote types.
>>>

In this case no * specifiers may occur in a format (since they require a sequential parameter list).

Additional string operations are defined in standard module string and in built-in module re.

* A tuple object in this case should be a singleton.
** These numbers are fairly arbitrary. They are intended to avoid printing endless strings of meaningless digits without hampering correct use and without having to know the exact precision of floating-point values on a particular machine.

Mutable Sequence Types

List objects support additional operations that allow in-place modification of the object. These operations would be supported by other mutable sequence types (when added to the language) as well. Strings and tuples are immutable sequence types, and such objects can't be modified once created. The operations in the following table are defined on mutable sequence types (where x is an arbitrary object).

OperationResultNotes
s[i] = xItem i of s is replaced by x 
s[i:j] = tSlice of s from i to j is replaced by t 
del s[i:j]Same as s[i:j] = [] 
s.append(x)Same as s[len(s) :len(s)] = [x] 
s.extend(x)Same as s[len(s) :len(s)] = x5
s.count(x)Return number of i's for which s[i] == x 
s.index(x)Return smallest i such that s[i] == x1
s.insert(i, x)Same as s[i:i] = [x] if i >= 0 
s.pop([i])Same as x = s[i]; del s [i]; return x4
s.remove(x)Same as del s[s.index(x)]1
s.reverse()Reverses the items of s in place3
s.sort ([cmpfunc])Sort the items of s in place2,3

Notes

1. This raises an exception when x is not found in s.

2. The sort() method takes an optional argument specifying a comparison function of two arguments (list items) that should return -1, 0, or 1 depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. Note that this slows the sorting process considerably; e.g., to sort a list in reverse order, it's much faster to use calls to the methods sort() and reverse() than to use the built-in function sort() with a comparison function that reverses the ordering of the elements.

3. The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. They don't return the sorted or reversed list to remind you of this side effect.

4. The pop() method is experimental and not supported by other mutable sequence types than lists. The optional argument i defaults to -1, so that by default, the last item is removed and returned.

5. This raises an exception when x is not a list object. The extend() method is experimental and not supported by mutable types other than lists.

Mapping Types

A mapping object maps values of one type (the key type) to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. A dictionary's keys are almost arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.

Dictionaries are created by placing a comma-separated list of key: value pairs within braces, for example: { jack : 4098, sjoerd : 4127} or {4098: jack , 4127: sjoerd'}.

The operations in the following table are defined on mappings (where a is a mapping, k is a key and x is an arbitrary object).

OperationResultNotes
len (a)The number of items in a 
a[k]The item of a with key k1
a[k] = xSet a[k] to x 
del a[k]Remove a[k] from a (1) 
a.clear()Remove all items from a 
a.copy()A (shallow) copy of a 
a.has_key(k)1 if a has a key k, else 0 
a.items()A copy of a's list of (key, value) pairs2
a.keys()A copy of a's list of keys2
a.update(b)For k, v in b.items() : a[k] = v3
a.values()A copy of a's list of values2
a.get(k[, f])The value of a with key k4

Notes

1. This raises an exception if k is not in the map.

2. Keys and values are listed in random order.

3. b must be the same type as a

4. This never raises an exception if k is not in the map, instead it returns f. f is optional; when not provided and k is not in the map, None is returned.

Other Built-in Types

The interpreter supports several other kinds of objects. Most of these support only one or two operations.

Modules

The only special operation on a module is attribute access: m.name, where m is a module and name accesses a name defined in m's symbol table. The import statement is not, strictly speaking, an operation on a module object; import foo doesn't require a module object named foo to exist, rather it requires an (external) definition for a module named foo somewhere.

A special member of every module is __dict__. This is the dictionary containing the module's symbol table. Modifying this dictionary changes the module's symbol table, but direct assignment to the __dict__ attribute isn't possible (i.e., you can write m.__dict__[ a ] =1, which defines m.a to be 1, but you can't write m.__dict__= {}.

Modules built into the interpreter are written like this: <module sys (built-in)>. If loaded from a file, they are written as <module os from /usr/local/lib/python1.5/os.pyc >.

Classes and Class Instances

See Chapters 3 and 7 of the Python reference manual.

Functions

Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list).

There are really two flavors of function objects, built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.

The implementation adds two special read-only attributes: f.func_code is a function's code object (see the section "Code objects"), and f.func_globals is the dictionary used as the function's global namespace (this is the same as m.__dict__ where m is the module in which the function f was defined).

Methods

Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as append() on lists) and class instance methods. Built-in methods are described with the types that support them.

The implementation adds two special read-only attributes to class instance methods: m.im_self is the object on which the method operates, and m.im_func is the function implementing the method. Calling m(arg-1, arg-2, , arg-n) is equivalent to calling m.im_func(m.im_self, arg-1, arg-2, , arg-n). See the Python reference manual for more information.

Code Objects

Code objects are used by the implementation to represent "pseudo-compiled" executable Python code such as a function body. They differ from function objects because they don't contain a reference to their global execution environment. Code objects are returned by the built-in compile() function and can be extracted from function objects through their func_code attribute.

A code object can be executed or evaluated by passing it (instead of a source string) to the exec statement or the built-in eval() function. See the Python reference manual for more information.

Type Objects

Type objects represent the various object types. An object's type is accessed by the built-in function type(). There are no special operations on types. The standard module type defines names for all standard built-in types. Types are written like this: <type  int >.

The Null Object

This object is returned by functions that don't explicitly return a value. It supports no special operations. There is exactly one null object, named None (a built-in name); it's written as None.

The Ellipsis Object

This object is used by extended slice notation (see the Python reference manual). It supports no special operations. There is one ellipsis object, named Ellipsis (a built-in name); it's written as Ellipsis.

File Objects

File objects are implemented using C's stdio package and can be created with the built-in function open() (described in the section "Built-in Functions"). They are also returned by some other built-in functions and methods, e.g., posix.popen() and posix.fdopen(), and the makefile() method of socket objects.

When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation isn't defined for some reason, such as seek() on a tty device or writing a file opened for reading. Files have the following methods:

close()
Closes the file. A closed file can't be read or written.

flush()
Flushes the internal buffer; like stdio's fflush().

isatty()
Returns 1 if the file is connected to a tty (-like) device, else 0.

fileno()
Returns the integer ''file descriptor'' that's used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower-level interfaces that use file descriptors, e.g., module fcntl or os.read() and friends.

read([size])
Reads at most size bytes from the file (less if the read hits EOF or no more data is immediately available on a pipe, tty, or similar device). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.)

readline([size])
Reads one entire line from the file. A trailing newline character is kept in the string* (but may be absent when a file ends with an incomplete line). If the size argument is present and nonnegative, it's a maximum byte count (including the trailing newline), and an incomplete line may be returned. An empty string is returned when EOF is hit immediately. Unlike stdio's fgets(), the returned string contains null characters (\0) if they occurred in the input.

readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totaling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.

seek(offset[, whence])
Sets the file's current position; like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There's no return value.

* The advantage of leaving the newline on is that an empty string can be returned to mean EOF without being ambiguous. Another advantage is that (in cases where it might matter, e.g., if you want to make an exact copy of a file while scanning its lines) you can tell whether the last line of a file ended in a newline or not (yes, this happens!).

tell()
Returns the file's current position; like stdio's ftell().

truncate([size])
Truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. Availability of this function depends on the operating-system version (e.g., not all Unix versions support this operation).

write(str)
Writes a string to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

writelines(list)
Writes a list of strings to the file. There is no return value. (The name is intended to match readlines(); writelines() doesn't add line separators.)

File objects also offer the following attributes:

closed
Boolean indicating the current state of the file object. This is a read-only attribute; the close() method changes the value.

mode
The I/O mode for the file. If the file is created using the open() built-in function, this is the value of the mode parameter. This is a read-only attribute.

name
If the file object was created using open(), this is the name of the file. Otherwise, it's some string that indicates the source of the file object, of the form < >. This is a read-only attribute.

softspace
Boolean that indicates whether a space character needs to be printed before another value when using the print statement. Classes that are trying to simulate a file object should also have a writable softspace attribute, which should be initialized to zero. This is automatic for classes implemented in Python; types implemented in C have to provide a writable softspace attribute.

Internal Objects

See the Python reference manual for this information. It describes code objects, stack frame objects, traceback objects, and slice objects.

Special Attributes

The implementation adds a few special read-only attributes to several object types, where they are relevant:

__dict__
A dictionary of some sort that stores an object's (writable) attributes

__methods__
List of the methods of many built-in object types, e.g., [].__methods__ yields ['append', 'count', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

__members__
Similar to __methods__, but lists data attributes

__class__
The class to which a class instance belongs

__bases__
The tuple of base classes of a class object

Built-in Exceptions

Exceptions can be class or string objects. While most exceptions have traditionally been string objects, in Python 1.5 all standard exceptions have been converted to class objects, and users are encouraged to do the same. The source code for those exceptions is present in the standard library-module exceptions; this module never needs to be imported explicitly.

For backward compatibility, when Python is invoked with the -X option, most standard exceptions are strings.* This option can run code that breaks because of the different semantics of class-based exceptions. The -X option will become obsolete in future Python versions, so the recommended solution is to fix the code.

Two distinct string objects with the same value are considered different exceptions. This forces programmers to use exception names rather than their string value when specifying exception handlers. The string value of all built-in exceptions is their name, but this isn't a requirement for user-defined exceptions or exceptions defined by library modules.

For class exceptions, in a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that

* For forward-compatibility the new exceptions Exception, LookupError, ArithmeticError, EnvironmentError, and StandardError are tuples.

aren't related via subclassing are never equivalent, even if they have the same name.

The built-in exceptions in the following list can be generated by the interpreter or built-in functions. Except where mentioned, they have an "associated value" indicating the detailed cause of the error. This may be a string or a tuple containing several items of information (e.g., an error code and a string explaining the code). The associated value is the second argument to the raise statement. For string exceptions, the associated value itself is stored in the variable named as the second argument of the except clause (if any). For class exceptions, that variable receives the exception instance. If the exception class is derived from the standard root class Exception, the associated value is present as the exception instance's args attribute, and possibly on other attributes as well.

User code can raise built-in exceptions. This code can test an exception handler or report an error condition "just like" the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error.

The following exceptions are used only as base classes for other exceptions. When string-based standard exceptions are used, they are tuples containing the directly derived classes:

Exception
The root class for exceptions. All built-in exceptions are derived from this class. All user-defined exceptions should also be derived from this class, but this isn't (yet) enforced. The str() function, when applied to an instance of this class (or most derived classes) returns the string value of the argument or arguments, or an empty string if no arguments were given to the constructor. When used as a sequence, this accesses the arguments given to the constructor (handy for backward compatibility with old code). The arguments are also available on the instance's args attribute, as a tuple.

StandardError
The base class for all built-in exception except SystemExit. StandardError itself is derived from the root class Exception.

ArithmeticError
The base class for those built-in exceptions that are raised for various arithmetic error: OverflowError, ZeroDivisionError, FloatingPointError.

LookupError
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid: IndexError, KeyError.

EnvironmentError
The base class for exceptions that can occur outside the Python system: IOError, OSError. When exceptions of this type are created with a two-tuple, the first item is available on the instance's errno attribute (it's assumed to be an error number), and the second item is available on the strerror attribute (it's usually the associated error message). The tuple itself is also available on the args attribute. New in Version 1.5.2.

When an EnvironmentError exception is instantiated with a three-tuple, the first two items are available as above, while the third item is available on the filename attribute. However, for backward-compatibility, the args attribute contains only a two-tuple of the first two constructor arguments.
The filename attribute is None when this exception is created with other than three arguments. The errno and strerror attributes are also None if the instance was created with other than two or three arguments. In this last case, args contains the verbatim constructor arguments as a tuple.

The following exceptions are those actually raised. They are class objects, except when the -X option is used to revert back to string-based standard exceptions:

AssertionError
Raised when an assert statement fails.

AttributeError
Raised when an attribute reference or assignment fails. (When an object doesn't support attribute references or attribute assignments at all, TypeError is raised.)

EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data. (Note that the read() and readline() methods of file objects return an empty string when they hit EOF.)

FloatingPointError
Raised when a floating-point operation fails. This exception is always defined, but can be raised only when Python is configured with the -with-fpectl option or the WANT_SIGFPE_HANDLER symbol is defined in the config.h file.

IOError
Raised when an I/O operation (such as a print statement, the built-in open() function, or a method of a file object) fails for an I/O-related reason, e.g., file not found or disk full.

This class is derived from EnvironmentError. See its previous discussion for more information on exception-instance attributes.

ImportError
Raised when an import statement fails to find the module definition or when a from   import fails to find a name that's to be imported.

IndexError
Raised when a sequence subscript is out of range. (Slice indexes are silently truncated to fall in the allowed range; if an index isn't a plain integer, TypeError is raised.)

KeyError
Raised when a mapping (dictionary) key is not found in the set of existing keys.

KeyboardInterrupt
Raised when the user hits the interrupt key (normally Ctrl-C or Del). During execution, a check for interrupts is made regularly. Interrupts typed when a built-in function input() or raw_input()) is waiting for input also raise this exception.

MemoryError
Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory-management architecture (C's malloc() function), the interpreter may not always completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a runaway program was the cause.

NameError
Raised when a local or global name is not found. Applies only to unqualified names. The associated value is the name that can't be found.

NotImplementedError
Derived from RuntimeError. In user-defined base classes, abstract methods should raise this exception when they require derived classes to override the method. New in Version 1.5.2.

OSError
Derived from EnvironmentError and is used primarily as the os module's os.error exception. See EnvironmentError in the first exception list for a description of the possible associated values. New in Version 1.5.2.

OverflowError
Raised when the result of an arithmetic operation is too large to be represented. This can't occur for long integers (which would rather raise MemoryError than give up). Because of the lack of standardization of floating-point exception handling in C, most floating-point operations also aren't

checked. For plain integers, all operations that can overflow are checked except left shift, where typical applications prefer to drop bits than raise an exception.

RuntimeError
Raised when an error is detected that doesn't fall in any of the other categories. The associated value is a string indicating what precisely went wrong. (This exception is mostly a relic from a previous version of the interpreter; it isn't used much any more.)

SyntaxError
Raised when the parser encounters a syntax error. This may occur in an import statement, in an exec statement, in a call to the built-in function eval() or input(), or when reading the initial script or standard input (also interactively).

When class exceptions are used, instances of this class have attributes filename, lineno, offset, and text for easier access to the details; for string exceptions, the associated value is usually a tuple of the form (message, (filename, lineno, offset, text). For class exceptions, str() returns only the message.

SystemError
Raised when the interpreter finds an internal error, but the situation doesn't look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms). You should report this to the author or maintainer of your Python interpreter. Be sure to report the version string of the Python interpreter (sys.version, also printed at the start of an interactive Python session), the exact error message (the exception's associated value), and, if possible, the source of the program that triggered the error.

SystemExit
Raised by the sys.exit() function. When it's not handled, the Python interpreter exits; no stack traceback is printed. If the associated value is a plain integer, it specifies the system exit status (passed to C's exit() function); if it's None, the exit status is zero; if it has another type (such as a string), the object's value is printed, and the exit status is one.

When class exceptions are used, the instance has an attribute code that is set to the proposed exit status or error message (defaulting to None). Also, this exception derives directly from Exception and not StandardError, since it isn't technically an error. A call to sys.exit() is translated into an exception so that clean-up handlers (finally clauses of try statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. The os._exit() function can be used if it's absolutely necessary to exit immediately (e.g., after a fork() in the child process).

TypeError
Raised when a built-in operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

ValueError
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError

ZeroDivisionError
Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation

Built-in Functions

The Python interpreter has a number of built-in functions that are always available. They are listed here in alphabetical order:

__import__(name[, globals[, locals[, fromlist]]])
This function is invoked by the import statement. It exists so that you can replace it with another function that has a compatible interface, in order to change the semantics of the import statement. For examples of why and how you'd do this, see the standard library modules ihooks and rexec. See also the built-in module imp that defines some useful operations from which you can build your own __import__() function.

For example, the statement import spam results in the call __import__ ( spam , globals(), locals(), []); the statement from spam.ham import eggs results in __import__ ( spam.ham , globals () , locals(), [ eggs ]). Even though locals() and [ eggs ] are passed in as arguments, the __import__() function doesn't set the local variable named eggs; this is done by subsequent code that's generated for the import statement. (In fact, the standard implementation doesn't use its locals argument at all, and uses its globals only to determine the package context of the import statement.)
When the name variable is of the form package.module, normally, the top-level package (the name up to the first dot) is returned, not the module named by name. However, when a nonempty fromlist argument is given, the module named by name is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using import spam.ham.eggs, the top-level package spam must be placed in the importing namespace, but when using from spam.ham import eggs, the
spam.ham subpackage must find the eggs variable. As a workaround for this behavior, use getattr() to extract the desired components. For example, you could define the following helper:
import string
def my_import(name):
    mod = __import__(name)
    components = string.split(name, '.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
return mod

abs(x)
Returns the absolute value of a number. The argument may be a plain or long integer or a floating-point number. If the argument is a complex number, its magnitude is returned.

apply(function, args[, keywords])
The function argument must be a callable object (a user-defined or built-in function or method, or a class object), and the args argument must be a sequence (if it's not a tuple, the sequence is first converted to a tuple). The function is called with args as the argument list; the number of arguments is the length of the tuple. (This is different from just calling func(args), since in that case, there's always exactly one argument.) If the optional keywords argument is present, it must be a dictionary whose keys are strings. It specifies keyword arguments to be added to the end of the argument list.

buffer(object[, offset[, size]])
The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object is created that references the object argument; that buffer object is a slice from the beginning of object (or from the specified offset). The slice extends to the end of object (or has a length given by the size argument).

callable(object)
Returns true if the object argument appears callable, false if not. If it returns true, it's still possible that a call fails, but if it's false, the calling object never succeeds. Note that classes are callable (calling a class returns a new instance); class instances are callable if they have a __call__() method.

chr(i)
Returns a string of one character whose ASCII code is the integer i, e.g., chr(97) returns the string a. This is the inverse of ord(). The argument must be in the range [0 255], inclusive.

cmp(x, y)
Compares the two objects x and y and returns an integer according to the outcome. The return value is negative if x < y, zero if x == y, and strictly positive if x > y.

coerce(x, y)
Returns a tuple consisting of the two numeric arguments converted to a common type, using the same rules used by arithmetic operations.

compile(string, filename, kind)
Compiles the string into a code object. Code objects can be executed by an exec statement or evaluated by a call to eval(). The filename argument should give the file from which the code was read; pass string if it wasn't read from a file. The kind argument specifies what kind of code must be compiled; it can be exec if string consists of a sequence of statements, eval if it consists of a single expression, or single if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will print).

complex(real[, imag])
Creates a complex number with the value real + imag*j or converts a string or number to a complex number. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero, and the function serves as a numeric conversion function like int(), long(), and float(); in this case it also accepts a string argument that should be a valid complex number.

delattr(object, name)
A relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar' ) is equivalent to del x.foobar.

dir([object])
Without arguments, returns the list of names in the current local symbol table. With an argument, attempts to return a list of valid attribute for that object. This information is gleaned from the object's __dict__, __methods__, and __members__ attributes, if defined. The list is not necessarily complete; e.g., for classes, attributes defined in base classes aren't included, and for class instances, methods aren't included. The resulting list is sorted alphabetically. For example:

>>> import sys
>>> dir()
['sys']
>>> dir(sys)
['argv', 'exit', 'modules', 'path', 'stderr', 'stdin', 'stdout']
>>>

divmod(a, b)
Takes two numbers as arguments and returns a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand

types, the rules for binary arithmetic operators apply. For plain and long integers, the result is the same as (a / b, a % b). For floating-point numbers, the result is the same as (math.floor(a / b), a % b).

eval (expression[, globals[, locals]])
The arguments are a string and two optional dictionaries. The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the locals dictionary is omitted, it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1
>>> print eval('x+1')
2
This function can also execute arbitrary code objects (e.g., created by compile()). In this case, it passes a code object instead of a string. The code object must have been compiled passing eval to the kind argument.
Hints: dynamic execution of statements is supported by the exec statement. Execution of statements from a file is supported by the execfile() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or execfile().

execfile(file[, globals[, locals]])
Similar to the exec statement, but parses a file instead of a string. It's different from the import statement in that it doesn't use the module administration; it reads the file unconditionally and doesn't create a new module.*

The arguments are a filename and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similar to a module) using the globals and locals dictionaries as global and local namespace. If the locals dictionary is omitted, it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. The return value is None.

filter(function, list)
Constructs a list from those elements of list for which function returns true. If list is a string or a tuple, the result also has that type; otherwise it's always a list. If function is None, the identity function is assumed, i.e., all elements of list that are false (zero or empty) are removed.

* It's used relatively rarely so it doesn't warrant being made into a statement.

float(x)
Converts a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating-point number, possibly embedded in whitespace; this behaves identically to string.atof(x). Otherwise, the argument may be a plain or long integer or a floating-point number, and a floating-point number with the same value (within Python's floating-point precision) is returned.

When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted that cause these values to be returned depends entirely on the C library and is known to vary.

getattr(object, name)
The arguments are an object and a string. The string must be the name of one of the object's attributes. The result is the value of that attribute. For example, getattr(x, 'foobar ) is equivalent to x.foobar.

globals()
Returns a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

hasattr(object, name)
The arguments are an object and a string. The result is 1 if the string is the name of one of the object's attributes, 0 if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception.)

hash (object)
Returns the hash value of the object (if it has one). Hash values are integers. They can quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, e.g., 1 and 1.0).

hex(x)
Converts an integer number (of any size) to a hexadecimal string. The result is a valid Python expression. This always yields an unsigned literal, e.g., on a 32-bit machine, hex(-1) yields '0xffffffff . When evaluated on a machine with the same word size, this literal is evaluated as -1; at a different word size, it may be a large positive number or raise an OverflowError exception.

id(object)
Returns the identity of an object. This is an integer that's guaranteed to be unique and constant for this object during its lifetime. Two objects whose lifetimes don't overlap may have the same id() value. (Implementation note: this is the address of the object.)

input([prompt])
Equivalent to eval(raw_input(prompt)).

intern(string)
Enters string in the table of interned strings and returns the interned string, which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup; if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries that hold module, class, or instance attributes have interned keys. Interned strings are immortal (i.e., never get garbage-collected).

int(x))
Converts a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace; this behaves identically to string. atoi(x). Otherwise, the argument may be a plain or long integer or a floating-point number. Conversion of floating-point numbers to integers is defined by the C semantics; normally the conversion truncates towards zero.*

isinstance(object, class)
Returns true if the object argument is an instance of the class argument or of a (direct or indirect) subclass thereof. Also returns true if class is a type object and object is an object of that type. If object is not a class instance or an object of the given type, the function always returns false. If class is neither a class object nor a type object, a TypeError exception is raised.

issubclass(class1, class2)
Returns true if class1 is a subclass (direct or indirect) of class2. A class is considered a subclass of itself. If either argument isn't a class object, a TypeError exception is raised.

len(s)
Returns the length (the number of items) of an object. The argument may be a sequence (string, tuple, or list) or a mapping (dictionary).

list(sequence)
Returns a list whose items are the same and in the same order as sequence's items. If sequence is already a list, a copy is made and returned, similar to sequence[:]. For instance, list( abc ) returns [ a , b ,  c ], and list( (1, 2, 3) ) returns [1, 2, 3].

* This is ugly: the language definition should require truncation towards zero.

locals()
Returns a dictionary representing the current local symbol table. Warning: the contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter.

long(x)
Converts a string or number to a long integer. If the argument is a string, it must contain a possibly signed decimal number of arbitrary size, possibly embedded in whitespace; this behaves identically to string.atol(x). Otherwise, the argument may be a plain or long integer or a floating-point number, and a long integer with the same value is returned. Conversion of floating-point numbers to integers is defined by the C semantics; see the description of int().

map (function, list, )
Applies function to every item of list and returns a list of the results. If additional list arguments are passed, function must take that many arguments and is applied to the items of all lists in parallel; if a list is shorter than another, it's assumed to be extended with None items. If function is None, the identity function is assumed;if there are multiple list arguments, map() returns a list consisting of tuples containing the corresponding items from all lists (i.e., a kind of transpose operation). The list arguments may be any kind of sequence; the result is always a list.

max (s[, args ])
With a single argument s, returns the largest item of a nonempty sequence (e.g., a string, tuple, or list). With more than one argument, returns the largest of the arguments.

min(s[, args ])
With a single argument s, returns the smallest item of a nonempty sequence (e.g., a string, tuple, or list). With more than one argument, returns the smallest of the arguments.

oct(x)
Converts an integer number (of any size) to an octal string. The result is a valid Python expression. This always yields an unsigned literal, e.g., on a 32-bit machine, oct(-1) yields '037777777777 . When evaluated on a machine with the same word size, this literal is evaluated as -1; at a different word size, it may be a large positive number or raise an OverflowError exception.

open(filename[, model[, bufsize]])
Returns a new file object (described earlier in the section ''Built-in Types''). The first two arguments are the same as for stdio's fopen(): filename is the filename to be opened, mode indicates how the file is to be opened: r for reading, w for writing (truncating an existing file), and a opens it for

appending (which on some Unix systems means that all writes append to the end of the file, regardless of the current seek position).
Modes r+ , w+ , and a+ open the file for updating (note that w+ truncates the file). Append b to the mode to open the file in binary mode, on systems that differentiate between binary and text files (else it is ignored). If the file can't be opened, IOError is raised.
If mode is omitted, it defaults to r . When opening a binary file, you should append b to the mode value for improved portability. (It's useful even on systems that don't treat binary and text files differently, where it serves as documentation.) The optional bufsize argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.

ord(C)
Returns the ASCII value of a string of one character. For example, ord( a ) returns the integer 97. This is the inverse of chr()

pow(x, y[, z])
Returns x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The arguments must have numeric types. With mixed operand types, the rules for binary arithmetic operators apply. The effective operand type is also the type of the result; if the result isn't expressible in this type, the function raises an exception; e.g., pow(2, -1) or pow(2, 35000) isn't allowed.

range ([start,] stop[, step])
This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the largest start + i *  step greater than stop. step must not be zero (or else ValueError is raised). Here's an example:

>>> range (10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
* Specifying a buffer size currently has no effect on systems that don't have setvbuf(). The interface to specify the buffer size is not done using a method that calls setvbuf(), because that may dump core when called after any I/O has been performed, and there's no reliable way to determine whether this is the case.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range (0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
>>>

raw_input ([prompt])
If the ([prompt])
If the prompt argument is present, it's written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Here's an example:

>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
>>>
If the readline module was loaded, then raw_input() uses it to provide elaborate line-editing and history features.

reduce (function, sequence [, initializer])
Applies function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If the optional initializer is present, it's placed before the items of the sequence in the calculation and serves as a default when the sequence is empty.

reload (module)
Reparses and reinitializes an already imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (i.e., the same as the module argument). There are a number of caveats:

— If a module is syntactically correct but its initialization fails, the first import statement for it doesn't bind its name locally, but does store a (partially initialized) module object in sys.modules. To reload the module you must first import it again (this binds the name to the partially initialized module object) before you can reload() it.
— When a module is reloaded, its dictionary (containing the module's global variables) is retained. Redefinitions of names override the old definitions, so this is generally not a problem. If the new version of a module doesn't define a name that was defined by the old version, the old definition remains. This feature can be used to the module's advantage if it maintains a global table or cache of objects; with a try statement it can test for the table's presence and skip its initialization if desired.
— It is legal though generally not useful to reload built-in or dynamically loaded modules, except for sys, __main__, and __builtin__. In certain cases, however, extension modules aren't designed to be initialized more than once, and may fail in arbitrary ways when reloaded.
— If a module imports objects from another module using from import , calling reload() for the other module doesn't redefine the objects imported from it; one way around this is to reexecute the from statement, another is to use import and qualified names (module.name) instead.
— If a module instantiates instances of a class, reloading the module that defines the class doesn't affect the method definitions of the instances; they continue to use the old class definition. The same is true for derived classes.

repr(object)
Returns a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It's sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval().

round(x[, n])
Returns the floating-point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating-point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (e.g., round(0.5) is 1.0 and round(-0.5) is -1.0).

setattr (object, name, value)
The counterpart of getattr(). The arguments are an object, a string, and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, foobar' , 123) is equivalent to x.foobar = 123.

slice ([start,] stop[, step])
Returns a slice object representing the set of indexes specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop, and step, which

merely return the argument values (or their default). They have no other explicit functionality; however, they are used by Numerical Python and other third-party extensions. Slice objects are also generated when extended when extended indexing syntax is used, e.g., for a[start:stop:step] or a[start:stop, i].

str (object)
Returns a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) doesn't always attempt to return a string that is acceptable to eval(); its goal is to return a printable string.

tuple(sequence)
Returns a tuple whose items are the same and in the same order as sequence's items. If sequence is already a tuple, it's returned unchanged. For instance, tuple( abc ) returns ( a , b , c ), and tuple ([1, 2, 3 ]) returns (1, 2, 3).

type(object)
Returns the type of an object. The return value is a type object. The standard module types defines names for all built-in types. For instance:

>>> import types
>>> if type(x) == types.StringType: print "It's a string"
>>>

vars([object])
Without arguments, returns a dictionary corresponding to the current local symbol table. With a module, class, or class instance object as argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table. The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.*

xrange ([start,] stop [, step])
Similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type that yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a large range is used on a memory-starved machine (e.g., MS-DOS) or when all of the range's elements are never used (e.g., when the loop is usually terminated with break).

* In the current implementation, local variable bindings can't normally be affected this way, but variables retrieved from other scopes (e.g., modules) can. This may change.

Module Sys: System-Specific Parameters and Functions

This module is always available and provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.

argv
The list of command-line arguments passed to a Python script. argv[0] is the script name (it's operating system-dependent, whether this is a full pathname or not). If the command is executed using the -c command-line option to the interpreter, argv[0] is set to the string -c. If no script name is passed to the Python interpreter, argv has zero length.

builtin_module_names
A tuple of strings giving the names of all modules that are compiled into this Python interpreter. (This information isn't available in any other way: modules.keys() lists only the imported modules.)

copyright
A string containing the copyright pertaining to the Python interpreter.

exc_info()
Returns a tuple of three values that give information about the exception that's currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, handling an exception is defined as executing or having executed an except clause. For any stack frame, only information about the most recently handled exception is accessible.

If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the exception type of the exception being handled (a string or class object); value gets the exception parameter (its associated value or the second argument to raise, which is always a class instance if the exception type is a class object); traceback gets a traceback object (see the reference manual) that encapsulates the call stack at the point where the exception originally occurred.
Note that assigning the traceback return valueto a local variable in a function that is handling an exception causes acircular reference. This prevents anything referenced by a localvariable in the same function or by the traceback from beinggarbage-collected. Since most functions don't need access to
the traceback, the best solution is to use something like type, value = sys. exc_info() [:2] to extract only the exception type and value. If you do need the traceback, make sure to delete it after use (best done with a try finally statement) or to call exc_info() in a function that doesn't itself handle an exception.

exc_type, exc_value, exc_traceback
Deprecated since Release 1.5. Use exc_info() instead. Since they are global variables, they aren't specific to the current thread, and their use is not safe in a multithreaded program. When no exception is being handled, exc_type is set to None, and the other two are undefined.

exec_prefix
A string giving the site-specific directory prefix where the platform-dependent Python files are installed; by default, this is also /usr/local. This can be set at build time with the --exec-prefix argument to the configure script. Specifically, all configuration files (e.g., the config.h header file) are installed in the directory exec_prefix + /lib/pythonversion/config , and shared library modules are installed in exec_prefix+ /lib/pythonversion/libdynload , where version is equal to version[:3].

executable
A string giving the name of the executable binary for the Python interpreter, on systems that support it.

exit( [arg])
Exits from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it's possible to intercept the exit attempt at an outer level. The optional argument arg can be an integer giving the exit status (defaulting to zero) or another type of object. If it's an integer, zero is considered successful termination, and any nonzero value is considered abnormal termination by shells and the like. Most systems require it to be in the range 0 127 and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command-line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed tosys. stderr and results in an exit code of 1. In particular, sys.exit( some error message ) is a quick way to exit a program when an error occurs.

exitfunc
This value is not actually defined by the module but can be set by the user (or by a program) to specify a cleanup action at program exit. When set, it should be a parameterless function. This function is called when the interpreter exits.

The exit function is not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.

getrefcount (object)
Returns the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

last_type, last_value, last_traceback
These three variables aren't always defined; they are set when an exception is not handled, and the interpreter prints an error message and a stack traceback. Their intended use is to allow an interactive user to import a debugger module and engage in postmortem debugging without having to reexecute the command that caused the error. (Typical use is import pdb; pdb.pm() to enter the postmortem debugger.)

The meaning of the variables is the same as that of the return values from exc_info(), as seen in the previous entry. (Since there is only one interactive thread, thread-safety is not a concern for these variables, unlike for exc_type, etc.)

maxint
The largest positive integer supported by Python's regular integer type. This is at least 231-1. The largest negative integer is -maxint-1: the asymmetry results from the use of 2's complement binary arithmetic.

modules
A dictionary that maps module names to modules that have already been loaded. This can be manipulated to force reloading of modules and other tricks. Removing a module from this dictionary is not the same as calling reload() on the corresponding module object.

path
A list of strings that specifies the search path for modules. Initialized from the environment variable $PYTHONPATH or an installation-dependent default.

The first item of this list, path[0], is the directory containing the script that invoked the Python interpreter. If the script directory isn't available (e.g., if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of $PYTHONPATH.

platform
Contains a platform identifier, e.g., sunos5 or linux1. This can append platform-specific components to path, for instance.

prefix
A string giving the site-specific directory prefix where the platform-independent Python files are installed; by default, this is the string /usr/local. This can be set at build time with the --prefix argument to the configure script. The main collection of Python library modules is installed in the directory prefix +  /lib/pythonversion while the platform-independent header files (all except config.h) are stored in prefix + /include/pythonversion , where version is equal to version[:3].

ps1, ps2
Strings specifying the primary and secondary prompt of the interpreter. These are defined only if the interpreter is in interactive mode. Their initial values in this case are >>> and. If a nonstring object is assigned to either variable, its str() is reevaluated each time the interpreter prepares to read a new interactive command; this can implement a dynamic prompt.

setcheckinterval (interval)
Sets the interpreter's check interval. This integer value determines how often the interpreter checks for periodic things such as thread switches and signal handlers. The default is 10, meaning the check is performed every 10 Python virtual instructions. Setting it to a larger value may increase performance for programs using threads. Setting it to a value <= 0 checks every virtual instruction, maximizing responsiveness as well as overhead.

setprofile (profilefunc)
Sets the system's profile function, which allows you to implement a Python source code profiler in Python. The system's profile function is called similarly to the system's trace function (see settrace()), but it isn't called for each executed line of code (only on call and return and when an exception occurs). Also, its return value isn't used, so it can just return None.

settrace (tracefunc)
Sets the system's trace function, which allows you to implement a Python source code debugger in Python.

stdin, stdout, stderr
File objects corresponding to the interpreter's standard input, output, and error streams. stdin is used for all interpreter input except for scripts but including calls to input() and raw_input(). stdout is used for the output of print and expression statements and for the prompts of input() and raw_input(). The interpreter's own prompts and (almost all of) its error messages go to stderr. stdout and stderr needn't be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument. (Changing these objects doesn't affect the standard I/O streams of processes executed by os.popen(), os.system(), or the exec*() family of functions in the os module.)

__stdin__, __stdout__, __stderr__
Contain the original values of stdin, stderr, and stdout at the start of the program. They are used during finalization and can restore the actual files to known working file objects in case they have been overwritten with a broken object.

tracebacklimit
When this variable is set to an integer value, it determines the maximum number of levels of traceback information printed when an unhandled exception occurs. The default is 1000. When set to 0 or less, all traceback information is suppressed, and only the exception type and value are printed.

version
A string containing the version number of the Python interpreter.

Module String: Common String Operations

This module defines some constants that can check character classes, and some useful string functions. See the module re for string functions based on regular expressions. The constants defined in this module are:

digits
The string '0123456789'.

hexdigits
The string '0123456789abcdefABCDEF'.

letters
The concatenation of the strings lowercase() and uppercase() (check their entries in this list).

lowercase
A string containing all characters considered lowercase letters. On most systems this is the string abcdefghijklmnopqrstuvwxyz . Don't change its definition: the effect on the routines upper() and swapcase() is undefined.

octdigits
The string 01234567 .

uppercase
A string containing all characters considered uppercase letters. On most systems this is the string 'ABCDEFGHIJKLMNOPQRSTUVWXYZ . Don't change its definition: the effect on the routines lower() and swapcase() is undefined.

whitespace
A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and

vertical tab. Don't change its definition: the effect on the routines strip() and split() is undefined.

The functions defined in this module are:

atof(s)
Converts a string to a floating-point number. The string must have the standard syntax for a floating-point literal in Python, optionally preceded by a sign (+ or -). Note that this behaves identically to the built-in function float() when passed a string.

When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted that cause these values to be returned depends entirely on the C library and is known to vary.

atoi (s[, base])
Converts string s to an integer in the given base. The string must consist of one or more digits, optionally preceded by a sign (+ or -). The base defaults to 10. If it's 0, a default base is chosen depending on the leading characters of the string (after stripping the sign): 0x or 0X means 16, 0 means 8, anything else means 10. If base is 16, a leading 0x or 0X is always accepted. When invoked without base or with base set to 10, this behaves identically to the built-in function int() when passed a string. (Also note: for a more flexible interpretation of numeric literals, use the built-in function eval().)

atol (s[, base])
Converts string s to a long integer in the given base. The string must consist of one or more digits, optionally preceded by a sign (+ or -). The base argument has the same meaning as for atoi(). A trailing 1 or L isn't allowed, except if the base is 0. When invoked without base or with base set to 10, this behaves identically to the built-in function long() when passed a string.

capitalize (word)
Capitalizes the first character of the argument.

capwords (s)
Splits the argument into words using split(), capitalizes each word using capitalize(), and joins the capitalized words using join(). This replaces runs of whitespace characters by a single space and removes leading and trailing whitespace.

expandtabs (s, [tabsize])
Expands tabs in a string, i.e., replaces them by one or more spaces, depending on the current column and the given tab size. The column number is reset to zero after each newline occurring in the string. This doesn't understand other nonprinting characters or escape sequences. The tab size defaults to 8.

find(s, sub[, start[, end]])
Returns the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Returns -1 on failure. Defaults for start and end, and interpretation of negative values is the same as for slices.

rfind(s, sub[, start[, end]])
Like find() but finds the highest index.

index(s, sub[, start[, end]])
Like find() but raises ValueError when the substring isn't found.

rindex(s, sub[, start[, end]])
Like rfind() but raises ValueError when the substring isn't found.

count(s, sub[, start[, end]])
Returns the number of (nonoverlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end, and interpretation of negative values is the same as for slices.

lower(s)
Returns a copy of s, but with uppercase letters converted to lowercase.

maketrans(from, to)
Returns a translation table suitable for passing to translate() or regex. compile() that maps each character in from into the character at the same position in to; from and to must have the same length.

Don't use strings derived from lowercase and uppercase as arguments; in some locales, these don't have the same length. For case conversions, always use lower() and upper().

split(s[, sep[, maxsplit]])
Returns a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list then has one more item than the number of nonoverlapping occurrences of the separator in the string. The optional third argument maxsplit defaults to 0. If it's nonzero, at most maxsplit number of splits occur, and the remainder of the string is returned as the final element of the list (thus, the list has at most maxsplit+1 elements).

splitfields (s[, sep[, maxsplit]])
This function behaves identically to split(). In the past, split() was used with only one argument; splitfields() was used with two.

join (words[, sep])
Concatenates a list or tuple of words with intervening occurrences of sep. The default value for sep is a single space character. It's always true that string. join(string.split(s,, sep), sep) equals s.

joinfields(words[, sep])
This function behaves identically to join(). In the past, join() was used with only one argument, while joinfields() was used with two arguments.

lstrip(s)
Returns a copy of s but without leading whitespace characters.

rstrip(s)
Returns a copy of s but without trailing whitespace characters.

strip(s)
Returns a copy of s without leading or trailing whitespace.

swapcase(s)
Returns a copy of s, but with lowercase letters converted to uppercase and vice versa.

translate(s, table[, deletechars])
Deletes all characters from s that are in deletechars (if present) and then translates the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal.

upper(s)
Returns a copy of s, but with lowercase letters converted to uppercase.

ljust(s, width), rjust(s, width), center(s, width)
Respectively left justifies, right justifies, and centers a string in a field of given width. They return a string that is at least width characters wide, created by padding the string s with spaces until the given width on the right, left, or both sides. The string is never truncated.

zfill(s, width)
Pads a numeric string on the left with zero digits until the given width is reached. Strings starting with a sign are handled correctly.

replace(str, old, new[, maxsplit])
Returns a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxsplit is given, the first maxsplit occurrences are replaced.

This module is implemented in Python. Much of its functionality has been reimplemented in the built-in module strop. However, you should never import the latter module directly. When string discovers that strop exists, it transparently replaces parts of itself with the implementation from strop. After initialization, there is no overhead in using string instead of strop.

Module Os: Miscellaneous OS Interfaces

This module provides a more portable way to use operating system-dependent functionality than importing an OS-dependent built-in module such as posix or nt.

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

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

After os is imported for the first time, there's no performance penalty in using functions from os instead of directly from the OS-dependent built-in module, so there should be no reason not to use os.

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

When exceptions are classes, this exception carries two attributes, errno and strerror. The first holds the value of the C errno variable, and the latter holds the corresponding error message from strerror(). For exceptions that involve a filesystem path (e.g., chdir() or unlink()), the exception instance contains a third attribute, filename, which is the filename passed to the function.
When exceptions are strings, the string for the exception is OSError .

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

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

Process Parameters

These functions and data items provide information and operate on the current process and user:

chdir(path)
Changes the current working directory to path. Availability: Macintosh, Unix, Windows.

environ
A mapping representing the string environment. For example, environ[ HOME ] is the pathname of your home directory, equivalent to getenv( HOME ) in C.

If the platform supports the putenv() function, this mapping can modify the environment as well as query the environment. putenv() is called automatically when the mapping is modified.
If putenv() isn't provided, this mapping can be passed to the appropriate process-creation functions to cause child processes to use a modified environment.

getcwd()
Returns a string representing the current working directory. Availability: Macintosh, Unix, Windows.

getegid()
Returns the current process's effective group ID. Availability: Unix.

geteuid()
Returns the current process's effective user ID. Availability: Unix.

getgid()
Returns the current process's group ID. Availability: Unix.

getpgrp()
Returns the current process's group ID. Availability: Unix.

getpid()
Returns the current process ID. Availability: Unix, Windows.

getppid()
Returns the parent's process ID. Availability: Unix.

getuid()
Returns the current process's user ID. Availability: Unix.

putenv(varname, value)
Sets the environment variable, varname, to the string value. Such changes to the environment affect subprocesses started with os.system(), popen(), or fork() and execv(). Availability: most flavors of Unix, most flavors of Unix, Windows.

When putenv() is supported, assignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to putenv() don't update os.environ, so it's actually preferable to assign to items of os.environ.

setgid(gid)
Sets the current process's group ID. Availability: Unix.

setpgrp-()
Calls the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics. Availability: Unix.

setpgid(pid, pgrp)
Calls the system call setpgid(). See the Unix manual for the semantics. Availability: Unix.

setsid()
Calls the system call setsid(). See the Unix manual for the semantics. Availability: Unix.

setuid(uid)
Sets the current process's user ID. Availability: Unix.

strerror(code)
Returns the error message corresponding to the error code in code. Availability: Unix, Windows.

umask(mask)
Sets the current numeric umask and returns the previous umask. Availability: Unix, Windows.

uname()
Returns a five-tuple containing information identifying the current operating system. The tuple contains five strings: (sysname, nodename, release, version, machine). Some systems truncate the nodename to eight characters or to the leading component; a better way to get the hostname is socket. gethostname() or even socket.gethostbyaddr (socket.gethostname()). Availability: recent flavors of Unix.

File Object Creation

These functions create new file objects:

fdopen(fd[, mode[, bufsize]])
Returns an open file object connected to the file descriptor fd. The mode and bufsize arguments have the same meaning as the corresponding arguments to the built-in open() function. Availability: Macintosh, Unix, Windows.

popen(command[, mode[, bufsize]])
Opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is r (default) or w. The bufsize argument has the same meaning as the corresponding argument to the built-in open() function. The exit status of the command (encoded in the format specified for wait()) is available as the return value of the close() method of the file object, except that when the exit status is zero (termination without errors), None is returned. Availability: Unix, Windows.

File Descriptor Operations

These functions operate on I/O streams referred to with file descriptors:

close(fd)
Closes file descriptor fd. Availability: Macintosh, Unix, Windows.

This function is intended for low-level I/O and must be applied to a file descriptor as returned by open() or pipe(). To close a file object returned by the built-in function open(), by popen(), or fdopen(), use its close() method.

dup(fd)
Returns a duplicate of file descriptor fd. Availability: Macintosh, Unix, Windows.

dup2(fd, fd2)
Duplicates file descriptor fd to fd2,, closing the latter first if necessary. Availability: Unix, Windows.

fstat(fd)
Returns status for file descriptor fd, like stat(). Availability: Unix, Windows.

fstatvfs(fd)
Returns information about the filesystem containing the file associated with file descriptor fd, like statvfs(). Availability: Unix.

ftruncate(fd length)
Truncates the file corresponding to file descriptor fd, so that it is length bytes in size. Availability: Unix.

lseek(fd, pos, how)
Sets the current position of file descriptor fd to position pos, modified by how. 0 to set the position relative to the beginning of the file; 1 to set it relative to the current position; and 2 to set it relative to the end of the file. Availability: Macintosh, Unix, Windows.

open(file, flags[, mode])
Opens the file file and sets various flags according to flags and, possibly, its mode according to mode. The default mode is 0777 (octal), and the current umask value is first masked out. Returns the file descriptor for the newly opened file. Availability: Macintosh, Unix, Windows.

For a description of the flag and mode values, see the C runtime documentation; flag constants (such as O_RDONLY and O_WRONLY) are also defined in this module (see later in this section).
This function is intended for low-level I/O. Normally, you should use the built-in function open(), which returns a file object with read() and write() methods (and many more).

pipe()
Creates a pipe. Returns a pair of file descriptors (r, w) usable for reading and writing, respectively. Availability: Unix, Windows.

read(fd, n)
Reads at most n bytes from file descriptor fd. Returns a string containing the bytes read. Availability: Macintosh, Unix, Windows.
This function is intended for low-level I/O and must be applied to a file descriptor as returned by open() or pipe(). To read a file object returned by the built-in function open() or by popen(), fdopen(), or sys.stdin, use its read() or readline() methods.

tcgetpgrp(fd)
Returns the process group associated with the terminal given by fd (an open file descriptor as returned by open))). Availability: Unix.

tcsetpgrp(fd, pg))
Sets the process group associated with the terminal given by fd(an open file descriptor as returned by open()). to pg. Availability: Unix.

ttyname(fd)
Returns a string that specifies the terminal device associated with file-descriptor fd. If fd isn't associated with a terminal device, an exception is raised. Availability: Unix.

write(fd, str)
Writes the string str to file descriptor fd. Returns the number of bytes actually written. Availability: Macintosh, Unix, Windows.

This function is intended for low-level I/O and must be applied to a file descriptor as returned by open() or pipe(). To write a file object returned by the built-in function open() or by popen(), fdopen(), sys.stdout, or sys. stderr, use its write() method.
The following data items are available for constructing the flags parameter to the open() function:
O_RDONLY
O_WRONLY
O_RDWR
O_NDELAY
O_NONBLOCK
O_APPEND
O_DSYNC
O_RSYNC
O_SYNC
O_NOCTTY
O_CREAT
O_EXCL
O_TRUNC
These can be bitwise OR'd together. Availability: Macintosh, Unix, Windows.

Files and Directories

These functions operate on files and directories.

access(path, mode)
Checks read/write/execute permissions for this process or file path. Returns 1 if access is granted, 0 if not. See the Unix manual for the semantics. Availability: Unix.

chmod(path, mode)
Changes the mode of path to the numeric mode. Availability: Unix, Windows.

chown(path, uid, gid)
Changes the owner and group ID of path to the numeric uid and gid. Availability: Unix.

link(src, dst)
Creates a hard link pointing to src named dst. Availability: Unix.

listdir(path)
Returns a list containing the names of the entries in the directory. The list is in arbitrary order. It doesn't include the special entries ''.'' and ".." even if they are present in the directory. Availability: Macintosh, Unix, Windows.

lstat(path)
Like stat(), but doesn't follow symbolic links. Availability: Unix.

mkfifo(path[, mode])
Creates a FIFO (a named pipe) named path with numeric mode mode. The default mode is 0666 (octal). The current umask value is first masked out from the mode. Availability: Unix.

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink()). Generally, FIFOs are used as rendezvous between client and server type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that mkfifo() doesn't open the FIFO, it creates the rendezvous point.

mkdir(path[, mode])
Creates a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it's used, the current umask value is first masked out. Availability: Macintosh, Unix, Windows.

makedirs(path[, mode])
Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Throws an error exception if the leaf directory already exists or can't be created. The default mode is 0777 (octal). New in version 1.5.2.

readlink(path)
Returns a string representing the path to which the symbolic link points. Availability: Unix.

remove(path)
Removes the file path. See the entry for rmdir() to remove directory. This is identical to the unlink() function, documented later. Availability: Macintosh, Unix, Windows.

removedirs(path)
Recursive directory removal function. Works like rmdir() except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments are pruned until either the whole path is consumed or an error is raised (which is ignored, because it generally means that a parent directory isn't empty). Throws an error exception if the leaf directory can't be successfully removed. New in Version 1.5.2.

rename(src, dst)
Renames the file or directory src to dst. Availability: Macintosh, Unix, Windows.

renames(old, new)
Recursive directory or file renaming function. Works like rename(),except that the creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name are removed using removedirs().

This function can fail after the new directory structure is created if you lack permissions needed to remove the leaf directory or file. New in Version 1.5.2.

rmdir(path)
Removes the directory path. Availability: Macintosh, Unix, Windows.

stat(path)
Performs a stat() system call on the given path. The return value is a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. More items may be added at the end by some implementations. (On MS Windows, some items are filled with dummy values.) Availability: Macintosh, Unix, Windows.

The standard module stat defines functions and constants that are useful for extracting information from a stat structure.

statvfs(path)
Performs a statvfs() system call on the given path. The return value is a tuple of 10 integers giving the most common members of the statvfs structure, in the order f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax. Availability: Unix.

The standard module statvfs defines constants that are useful for extracting information from a statvfs structure.

symlink (src, dst)
Creates a symbolic link pointing to src named dst. Availability: Unix.

unlink (path)
Removes the file path. This is the same function as remove(); the unlink() name is its traditional Unix name. Availability: Macintosh, Unix, Windows.

utime (path, (atime, mtime))
Sets the access and modified time of the file to the given values. (The second argument is a tuple of two items.) Availability: Macintosh, Unix, Windows.

Process Management

These functions can create and manage additional processes:

execl(path, arg0, arg1,  )
This is quivalent to execv (path, (arg0, arg1, )). Availability: Unix, Windows.

execle (path, arg0, arg1,  , env)
This is equivalent to execve (path, (argo, arg1,  ), env). Availability: Unix, Windows.

execlp(path, arg0, arg1,  )
This is equivalent to execvp (path, (arg0, arg1,  )). Availability: Unix, Windows.

execv(path, args)
Executes the executable path with argument list args, replacing the current process (i.e., the Python interpreter). The argument list may be a tuple or list of strings. Availability: Unix, Windows.

execve(path, args, env)
Executes the executable path with argument list args, and environment env, replacing the current process (i.e., the Python interpreter). The argument list may be a tuple or list of strings. The environment must be a dictionary mapping strings to strings. Availability: Unix, Windows.

execvp(path, args)
Like execv(path, args) but duplicates the shell's actions in searching for an executable file in a list of directories. The directory list is obtained from environ[ PATH ]. Availability: Unix, Windows.

execvpe(path, args, env)
A cross between execve() and execvp(). The directory list is obtained from env[ PATH ]. Availability: Unix, Windows.

_exit(n)
Exits to the system with status n, without calling cleanup handlers, flushing stdio buffers, etc. Availability: Unix, Windows.

The standard way to exit is sys.exit(n). _exit() should normally be used only in the child process after a fork().

fork()
Forks a child process. Returns 0 in the child, the child's process ID in the parent. Availability: Unix.

kill(pid, sig)
Kills the process pid with signal sig. Availability: Unix.

nice(increment)
Adds increment to the process's "niceness." Returns the new niceness. Availability: Unix.

plock(op)
Locks program segments into memory. The value of op (defined in <sys/lock.h>) determines which segments are locked. Availability: Unix.

spawnv(mode, path, args)
Executes the program path in a new process, passing the arguments specified in args as command-line parameters. args may be a list or a tuple. mode

is a magic operational constant. See the Visual C++ runtime library documentation for further information. Availability: Windows. New in Version 1.5.2.

spawnve(mode, path, args, env)
Executes the program path in a new process, passing the arguments specified in args as command-line parameters and the contents of the mapping env as the environment. args may be a list or a tuple. mode is a magic operational constant. See the Visual C++ runtime library documentation for further information. Availability: Windows. New in Version 1.5.2.

P_WAIT
P_NOWAIT
P_NOWAITO
P_OVERLAY
P_DETACH
Possible values for the mode parameter to spawnv() and spawnve(). Availability: Windows. New in Version 1.5.2.

system(command)
Executes the command (a string) in a subshell. This is implemented by calling the standard C function system() and has the same limitations. Changes to posix.environ, sys.stdin, etc., aren't reflected in the environment of the executed command. The return value is the exit status of the process encoded in the format specified for wait(). Availability: Unix, Windows.

times()
Returns a five-tuple of floating-point numbers indicating accumulated (CPU or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manpage times(2) or the corresponding Windows Platform API documentation. Availability: Unix, Windows.

wait()
Waits for completion of a child process and returns a tuple containing its process ID and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. Availability: Unix.

waitpid(pid, options)
Waits for completion of a child process given by process ID and returns a tuple containing its process ID and exit status indication (encoded as for wait()). The semantics of the call are affected by the value of the integer options, which should be 0 for normal operation. Availability: Unix.

WNOHANG
The option for waitpid() to avoid hanging if no child process status is available immediately. Availability: Unix.

The following functions take a process status code as returned by waitpid() as a parameter. They can determine the disposition of a process.

WIFSTOPPED(status)
Returns true if the process has been stopped. Availability: Unix.

WIFSIGNALED(status)
Returns true if the process exited due to a signal. Availability: Unix.

WIFEXITED(status)
Returns true if the process exited using the exit(2) system call. Availability: Unix.

WEXITSTATUS(status)
If WIFEXITED(status) is true, returns the integer parameter to the exit(2) system call. Otherwise, the return value is meaningless. Availability: Unix.

WSTOPSIG(status)
Returns the signal that caused the process to stop. Availability: Unix.

WTERMSIG(status)
Returns the signal that caused the process to exit. Availability: Unix.

Miscellaneous System Data

The follow data values can support path-manipulation operations. These are defined for all platforms. Higher-level operations on pathnames are defined in the os.path module.

curdir
The constant string used by the OS to refer to the current directory, e.g., "." for POSIX or ":" for the Macintosh.

pardir
The constant string used by the OS to refer to the parent directory, e.g., ".." for POSIX or "::" for the Macintosh.

sep
The character used by the OS to separate pathname components, e.g., "/" for POSIX or ":" for the Macintosh. This character isn't sufficient to parse or concatenate pathnames (use os.path.split() and os.path.join()) but it's

altsep
An alternative character used by the OS to separate pathname components or None if only one separator character exists. This is set to "/" on DOS and Windows systems where sep is a backslash.

pathsep
The character conventionally used by the OS to separate search patch components (as in $PATH), e.g., ":" for POSIX or ";" for DOS and Windows.

defpath
The default search path used by exec*p*() if the environment doesn't have a PATH key.

linesep
The string that separates (or, rather, terminates) lines on the current platform. This may be a single character, e.g., /n for POSIX or /r for MacOS, or multiple characters, e.g., \r\n for MS-DOS and MS Windows.

Module os.Path: Common Pathname Manipulations

This module implements some useful functions on pathnames:

abspath(path)
Returns a normalized, absolute version of the pathname path. On most platforms, this is equivalent to normpath(join(os.getcwd()), path). New in Version 1.5.2.

basename(path)
Returns the base name of pathname path. This is the second half of the pair returned by split(path).

commonprefix(list)
Returns the longest string that is a prefix of all strings in list. If list is empty, returns the empty string (' ').

dirname(path)
Returns the directory name of pathname path. This is the first half of the pair returned by split(path).

exists(path)
Returns true if path refers to an existing path.

expanduser(path)
Returns the argument with an initial component of "~" or "~user" replaced by that user's home directory. An initial "~" is replaced by the environment variable $HOME; an initial "~user" is looked up in the password directory through the built-in module pwd. If the expansion fails, or if the path doesn't begin with a tilde, the path is returned unchanged. On the Macintosh, this always returns path unchanged.

expandvars(path)
Returns the argument with environment variables expanded. Substrings of the form $name or ${name} are replaced by the value of environment variable name. Malformed variable names and references to nonexisting variables are left unchanged. On the Macintosh, this always returns path unchanged.

getatime(path)
Returns the time of last access of a filename identified by path. The return value is an integer giving the number of seconds since the epoch (see the time module). Raise os.error if the file doesn't exist or is inaccessible. New in Version 1.5.2.

getmtime(path)
Returns the time of last modification of a filename identified by path. The return value is an integer giving the number of seconds since the epoch (see the time module). Raise os.error if the file doesn't exist or is inaccessible. New in Version 1.5.2.

getsize(path)
Returns the size, in bytes, of filename identified by path. Raise os.error if the file doesn't exist or is inaccessible. New in Version 1.5.2.

isabs(path)
Returns true if path is an absolute pathname (begins with a slash).

isfile(path)
Returns true if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

isdir(path)
Returns true if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.

islink(path)
Returns true if path refers to a directory entry that's a symbolic link. Always false if symbolic links aren't supported.

ismount(path)
Returns true if pathname path is a mount point: a point in a filesystem where a different filesystem has been mounted. The function checks whether path's parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device; this detects mount points for all Unix and POSIX variants.

join(path1[, path2[,  ]])
Joins one or more path components intelligently. If any component is an absolute path, all previous components are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2,

etc., with exactly one slash (/) inserted between components, unless path is empty.

normcase(path)
Normalizes the case of a pathname. On Unix, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes.

normpath(path)
Normalizes a pathname. This collapses redundant separators and up-level references, e.g., A//B, A/./B and A/foo/../B all become A/B. It doesn't normalize the case (use normcase() for that). On Windows, it converts forward slashes to backward slashes.

samefile(path1, path2)
Returns true if both pathname arguments refer to the same file or directory (as indicated by device number and i-node number). It raises an exception if an os.stat() call on either pathname fails. Availability: Macintosh, Unix.

sameopenfile(fp1, fp2)
Returns true if the file objects fp1 and fp2 refer to the same file. The two file objects may represent different file descriptors. Availability: Macintosh, Unix.

samestat(stat1, stat2)
Returns true if the stat tuples stat1 and stat2 refer to the same file. These structures may have been returned by fstat(), lstat(), or stat(). This function implements the underlying comparison used by samefile() and sameopenfile(). Availability: Macintosh, Unix.

split(path)
Splits the pathname path into a pair, (head, tail) where tail is the last pathname component, and head is everything leading up to that. The tail part never contains a slash; if path ends in a slash, tail is empty. If there is no slash in path, head is empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it's the root (one or more slashes only). In nearly all cases, join (head, tail) equals path (the only exception being when there were multiple slashes separating head from tail).

splitdrive(path)
Splits the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems that don't use drive specifications, drive is always the empty string. In all cases, drive + tail is the same as path.

splitext(path)
Splits the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period.

walk(path, visit, arg)
Calls the function visit with arguments (arg, dirname, names) for each directory in the directory tree rooted at path (including path itself, if it's a directory). The argument dirname specifies the visited directory, the argument names lists the files in the directory (from os.listdir(dirname)). The visit function may modify names to influence the set of directories visited below dirname, e.g., to avoid visiting certain parts of the tree. The object referred to by names must be modified in place, using del or slice assignment.


Back



Python Programming On Win32. Help for Windows Programmers
Python Programming on WIN32: Help for Windows Programmers
ISBN: 1565926218
EAN: 2147483647
Year: 1999
Pages: 35

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net