1 Python 2.0 Quick Reference
5 16 May 2001 upgraded by Richard Gruet and Simon Brunning for Python 2.0
6 2000/07/18 upgraded by Richard Gruet, rgruet@intraware.com for Python 1.5.2
8 1995/10/30, by Chris Hoffmann, choffman@vicorp.com
11 Python Bestiary, Author: Ken Manheimer, ken.manheimer@nist.gov
12 Python manuals, Authors: Guido van Rossum and Fred Drake
13 What's new in Python 2.0, Authors: A.M. Kuchling and Moshe Zadka
14 python-mode.el, Author: Tim Peters, tim_one@email.msn.com
16 and the readers of comp.lang.python
18 Python's nest: http://www.python.org Developement: http://
19 python.sourceforge.net/ ActivePython : http://www.ActiveState.com/ASPN/
21 newsgroup: comp.lang.python Help desk: help@python.org
22 Resources: http://starship.python.net/ and http://www.vex.net/parnassus/
23 Full documentation: http://www.python.org/doc/
24 An excellent Python reference book: Python Essential Reference by David Beazley
31 * Environment Variables
32 * Lexical Entities : keywords, identifiers, strings, numbers, sequences,
33 dictionaries, operators
34 * Basic Types And Their Operations
39 * Standard methods & operators redefinition in user-created Classes
40 * Special informative state attributes for some types
41 * Important Modules : sys, os, posix, posixpath, shutil, time, string, re,
43 * List of modules In base distribution
44 * Workspace Exploration And Idiom Hints
45 * Python Mode for Emacs
52 python [-diOStuUvxX?] [-c command | script | - ] [args]
56 -d Outputs parser debugging information (also PYTHONDEBUG=x)
57 -i Inspect interactively after running script (also PYTHONINSPECT=x) and
58 force prompts, even if stdin appears not to be a terminal
59 -O Optimize generated bytecode (set __debug__ = 0 =>s suppresses asserts)
60 -S Don't perform 'import site' on initialization
61 -t Issue warnings about inconsistent tab usage (-tt: issue errors)
62 -u Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x).
63 -U Force Python to interpret all string literals as Unicode literals.
64 -v Verbose (trace import statements) (also PYTHONVERBOSE=x)
65 -x Skip first line of source, allowing use of non-unix Forms of #!cmd
66 [DEL:-X [DEL:Disable class based built-in exceptions (for backward
67 :DEL] compatibility management of exceptions):DEL]
69 -c Specify the command to execute (see next section). This terminates the
70 command option list (following options are passed as arguments to the command).
71 the name of a python file (.py) to execute read from stdin.
72 script Anything afterward is passed as options to python script or command,
73 not interpreted as an option to interpreter itself.
74 args passed to script or command (in sys.argv[1:])
75 If no script or command, Python enters interactive mode.
77 * Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin
86 PYTHONHOME Alternate prefix directory (or prefix;exec_prefix). The
87 default module search path uses prefix/lib
88 Augments the default search path for module files. The format
89 is the same as the shell's $PATH: one or more directory
90 pathnames separated by ':' or ';' without spaces around
92 PYTHONPATH On Windows first search for Registry key HKEY_LOCAL_MACHINE\
93 Software\Python\PythonCore\x.y\PythonPath (default value). You
94 may also define a key named after your application with a
95 default string value giving the root directory path of your
97 If this is the name of a readable file, the Python commands in
98 PYTHONSTARTUP that file are executed before the first prompt is displayed in
99 interactive mode (no default).
100 PYTHONDEBUG If non-empty, same as -d option
101 PYTHONINSPECT If non-empty, same as -i option
102 PYTHONSUPPRESS If non-empty, same as -s option
103 PYTHONUNBUFFERED If non-empty, same as -u option
104 PYTHONVERBOSE If non-empty, same as -v option
105 PYTHONCASEOK If non-empty, ignore case in file/module names (imports)
110 Notable lexical entities
115 assert elif from lambda return
116 break else global not try
117 class except if or while
118 continue exec import pass
121 * (list of keywords in std module: keyword)
122 * Illegitimate Tokens (only valid in strings): @ $ ?
123 * A statement must all be on a single line. To break a statement over
124 multiple lines use "\", as with the C preprocessor.
125 Exception: can always break when inside any (), [], or {} pair, or in
126 triple-quoted strings.
127 * More than one statement can appear on a line if they are separated with
129 * Comments start with "#" and continue to end of line.
133 (letter | "_") (letter | digit | "_")*
135 * Python identifiers keywords, attributes, etc. are case-sensitive.
136 * Special forms: _ident (not imported by 'from module import *'); __ident__
137 (system defined name);
138 __ident (class-private name mangling)
142 "a string enclosed by double quotes"
143 'another string delimited by single quotes and with a " inside'
144 '''a string containing embedded newlines and quote (') marks, can be
145 delimited with triple quotes.'''
146 """ may also use 3- double quotes as delimiters """
147 u'a unicode string' U"Another unicode string"
148 r'a raw string where \ are kept (literalized): handy for regular
149 expressions and windows paths!'
150 R"another raw string" -- raw strings cannot end with a \
151 ur'a unicode raw string' UR"another raw unicode"
153 Use \ at end of line to continue a string on next line.
154 adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as
156 u'hello' + ' world' --> u'hello world' (coerced to unicode)
158 String Literal Escapes
160 \newline Ignored (escape newline)
161 \\ Backslash (\) \e Escape (ESC) \v Vertical Tab (VT)
162 \' Single quote (') \f Formfeed (FF) \OOO char with octal value OOO
163 \" Double quote (") \n Linefeed (LF)
164 \a Bell (BEL) \r Carriage Return (CR) \xHH char with hex value HH
165 \b Backspace (BS) \t Horizontal Tab (TAB)
166 \uHHHH unicode char with hex value HHHH, can only be used in unicode string
167 \UHHHHHHHH unicode char with hex value HHHHHHHH, can only be used in unicode string
168 \AnyOtherChar is left as-is
170 * NUL byte (\000) is NOT an end-of-string marker; NULs may be embedded in
172 * Strings (and tuples) are immutable: they cannot be modified.
176 Decimal integer: 1234, 1234567890546378940L (or l)
177 Octal integer: 0177, 0177777777777777777L (begin with a 0)
178 Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFFL (begin with 0x or 0X)
179 Long integer (unlimited precision): 1234567890123456L (ends with L or l)
180 Float (double precision): 3.14e-10, .001, 10., 1E3
181 Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and
186 * String of length 0, 1, 2 (see above)
187 '', '1', "12", 'hello\n'
188 * Tuple of length 0, 1, 2, etc:
189 () (1,) (1,2) # parentheses are optional if len > 0
190 * List of length 0, 1, 2, etc:
193 Indexing is 0-based. Negative indices (usually) mean count backwards from end
196 Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to
197 '0'; End defaults to 'sequence-length'.
199 a = (0,1,2,3,4,5,6,7)
203 a[1:] ==> (1, 2, 3, 4, 5, 6, 7)
205 a[:] ==> (0,1,2,3,4,5,6,7) # makes a copy of the sequence.
207 Dictionaries (Mappings)
209 Dictionary of length 0, 1, 2, etc:
210 {} {1 : 'first'} {1 : 'first', 'next': 'second'}
212 Operators and their evaluation order
214 Operators and their evaluation order
215 Highest Operator Comment
216 (...) [...] {...} `...` Tuple, list & dict. creation; string
218 s[i] s[i:j] s.attr f(...) indexing & slicing; attributes, fct
220 +x, -x, ~x Unary operators
222 x*y x/y x%y mult, division, modulo
223 x+y x-y addition, substraction
224 x<<y x>>y Bit shifting
226 x^y Bitwise exclusive or
228 x<y x<=y x>y x>=y x==y x!=y Comparison,
230 x is y x is not y membership
232 not x boolean negation
235 Lowest lambda args: expr anonymous function
237 Alternate names are defined in module operator (e.g. __add__ and add for +)
238 Most operators are overridable
241 Basic Types and Their Operations
243 Comparisons (defined between *any* types)
246 Comparison Meaning Notes
247 < strictly less than (1)
248 <= less than or equal to
249 > strictly greater than
250 >= greater than or equal to
252 != or <> not equal to
253 is object identity (2)
254 is not negated object identity (2)
257 Comparison behavior can be overridden for a given class by defining special
259 (1) X < Y < Z < W has expected meaning, unlike C
260 (2) Compare object identities (i.e. id(object)), not object values.
262 Boolean values and operators
264 Boolean values and operators
265 Value or Operator Returns Notes
266 None, numeric zeros, empty sequences and False
268 all other values True
269 not x True if x is False, else
271 x or y if x is False then y, else (1)
273 x and y if x is False then x, else (1)
277 Truth testing behavior can be overridden for a given class by defining
278 special method __nonzero__.
279 (1) Evaluate second arg only if necessary to determine outcome.
283 None is used as default return value on functions. Built-in single object
285 Input that evaluates to None does not print when running Python
290 Floats, integers and long integers.
292 Floats are implemented with C doubles.
293 Integers are implemented with C longs.
294 Long integers have unlimited size (only limit is system resources)
296 Operators on all numeric types
298 Operators on all numeric types
300 abs(x) the absolute value of x
301 int(x) x converted to integer
302 long(x) x converted to long integer
303 float(x) x converted to floating point
306 x + y the sum of x and y
307 x - y difference of x and y
308 x * y product of x and y
309 x / y quotient of x and y
310 x % y remainder of x / y
311 divmod(x, y) the tuple (x/y, x%y)
312 x ** y x to the power y (the same as pow(x, y))
314 Bit operators on integers and long integers
318 ~x the bits of x inverted
319 x ^ y bitwise exclusive or of x and y
320 x & y bitwise and of x and y
321 x | y bitwise or of x and y
322 x << n x shifted left by n bits
323 x >> n x shifted right by n bits
327 * represented as a pair of machine-level double precision floating point
329 * The real and imaginary value of a complex number z can be retrieved through
330 the attributes z.real and z.imag.
335 raised on application of arithmetic operation to non-number
337 numeric bounds exceeded
339 raised when zero second argument of div or modulo op
341 Operations on all sequence types (lists, tuples, strings)
343 Operations on all sequence types
344 Operation Result Notes
345 x in s 1 if an item of s is equal to x, else 0
346 x not in s 0 if an item of s is equal to x, else 1
347 s + t the concatenation of s and t
348 s * n, n*s n copies of s concatenated
349 s[i] i'th item of s, origin 0 (1)
350 s[i:j] slice of s from i (included) to j (excluded) (1), (2)
352 min(s) smallest item of s
353 max(s) largest item of (s)
356 (1) if i or j is negative, the index is relative to the end of the string,
357 ie len(s)+ i or len(s)+j is
358 substituted. But note that -0 is still 0.
359 (2) The slice of s from i to j is defined as the sequence of items with
360 index k such that i <= k < j.
361 If i or j is greater than len(s), use len(s). If i is omitted, use
362 len(s). If i is greater than or
363 equal to j, the slice is empty.
365 Operations on mutable (=modifiable) sequences (lists)
367 Operations on mutable sequences
368 Operation Result Notes
369 s[i] =x item i of s is replaced by x
370 s[i:j] = t slice of s from i to j is replaced by t
371 del s[i:j] same as s[i:j] = []
372 s.append(x) same as s[len(s) : len(s)] = [x]
373 s.extend(x) same as s[len(s):len(s)]= x (5)
374 s.count(x) return number of i's for which s[i] == x
375 s.index(x) return smallest i such that s[i] == x (1)
376 s.insert(i, x) same as s[i:i] = [x] if i >= 0
377 s.remove(x) same as del s[s.index(x)] (1)
378 s.pop([i]) same as x = s[i]; del s[i]; return x (4)
379 s.reverse() reverse the items of s in place (3)
380 s.sort([cmpFct]) sort the items of s in place (2), (3)
383 (1) raise a ValueError exception when x is not found in s (i.e. out of
385 (2) The sort() method takes an optional argument specifying a comparison
386 fct of 2 arguments (list items) which should
387 return -1, 0, or 1 depending on whether the 1st argument is
388 considered smaller than, equal to, or larger than the 2nd
389 argument. Note that this slows the sorting process down considerably.
390 (3) The sort() and reverse() methods modify the list in place for economy
391 of space when sorting or reversing a large list.
392 They don't return the sorted or reversed list to remind you of this
394 (4) [New 1.5.2] The pop() method is experimental and not supported by
395 other mutable sequence types than lists.
396 The optional argument i defaults to -1, so that by default the last
397 item is removed and returned.
398 (5) [New 1.5.2] Experimental ! Raises an exception when x is not a list
403 Operations on mappings (dictionaries)
405 Operations on mappings
406 Operation Result Notes
407 len(d) the number of items in d
408 d[k] the item of d with key k (1)
409 d[k] = x set d[k] to x
410 del d[k] remove d[k] from d (1)
411 d.clear() remove all items from d
412 d.copy() a shallow copy of d
413 d.has_key(k) 1 if d has key k, else 0
414 d.items() a copy of d's list of (key, item) pairs (2)
415 d.keys() a copy of d's list of keys (2)
416 d1.update(d2) for k, v in d2.items(): d1[k] = v (3)
417 d.values() a copy of d's list of values (2)
418 d.get(k,defaultval) the item of d with key k (4)
419 d.setdefault(k,defaultval) the item of d with key k (5)
422 TypeError is raised if key is not acceptable
423 (1) KeyError is raised if key k is not in the map
424 (2) Keys and values are listed in random order
425 (3) d2 must be of the same type as d1
426 (4) Never raises an exception if k is not in the map, instead it returns
428 defaultVal is optional, when not provided and k is not in the map,
430 (5) Never raises an exception if k is not in the map, instead it returns
431 defaultVal, and adds k to map with value defaultVal. defaultVal is
432 optional. When not provided and k is not in the map, None is returned and
435 Operations on strings
437 Note that these string methods largely (but not completely) supersede the
438 functions available in the string module.
441 Operations on strings
442 Operation Result Notes
443 s.capitalize() return a copy of s with only its first character
445 s.center(width) return a copy of s centered in a string of length width (1)
447 s.count(sub[ return the number of occurrences of substring sub in (2)
448 ,start[,end]]) string s.
449 s.encode([ return an encoded version of s. Default encoding is the
450 encoding[,errors current default string encoding. (3)
452 s.endswith(suffix return true if s ends with the specified suffix, (2)
453 [,start[,end]]) otherwise return false.
454 s.expandtabs([ return a copy of s where all tab characters are (4)
455 tabsize]) expanded using spaces.
456 s.find(sub[,start return the lowest index in s where substring sub is (2)
457 [,end]]) found. Return -1 if sub is not found.
458 s.index(sub[ like find(), but raise ValueError when the substring is (2)
459 ,start[,end]]) not found.
460 s.isalnum() return true if all characters in s are alphanumeric, (5)
462 s.isalpha() return true if all characters in s are alphabetic, (5)
464 s.isdigit() return true if all characters in s are digit (5)
465 characters, false otherwise.
466 s.islower() return true if all characters in s are lowercase, false (6)
468 s.isspace() return true if all characters in s are whitespace (5)
469 characters, false otherwise.
470 s.istitle() return true if string s is a titlecased string, false (7)
472 s.isupper() return true if all characters in s are uppercase, false (6)
474 s.join(seq) return a concatenation of the strings in the sequence
475 seq, seperated by 's's.
476 s.ljust(width) return s left justified in a string of length width. (1),
478 s.lower() return a copy of s converted to lowercase.
479 s.lstrip() return a copy of s with leading whitespace removed.
480 s.replace(old, return a copy of s with all occurrences of substring (9)
481 new[, maxsplit]) old replaced by new.
482 s.rfind(sub[ return the highest index in s where substring sub is (2)
483 ,start[,end]]) found. Return -1 if sub is not found.
484 s.rindex(sub[ like rfind(), but raise ValueError when the substring (2)
485 ,start[,end]]) is not found.
486 s.rjust(width) return s right justified in a string of length width. (1),
488 s.rstrip() return a copy of s with trailing whitespace removed.
489 s.split([sep[ return a list of the words in s, using sep as the (10)
490 ,maxsplit]]) delimiter string.
491 s.splitlines([ return a list of the lines in s, breaking at line (11)
492 keepends]) boundaries.
493 s.startswith return true if s starts with the specified prefix,
494 (prefix[,start[ otherwise return false. (2)
496 s.strip() return a copy of s with leading and trailing whitespace
498 s.swapcase() return a copy of s with uppercase characters converted
499 to lowercase and vice versa.
500 return a titlecased copy of s, i.e. words start with
501 s.title() uppercase characters, all remaining cased characters
503 s.translate(table return a copy of s mapped through translation table (12)
504 [,deletechars]) table.
505 s.upper() return a copy of s converted to uppercase.
508 (1) Padding is done using spaces.
509 (2) If optional argument start is supplied, substring s[start:] is
510 processed. If optional arguments start and end are supplied, substring s[start:
512 (3) Optional argument errors may be given to set a different error handling
513 scheme. The default for errors is 'strict', meaning that encoding errors raise
514 a ValueError. Other possible values are 'ignore' and 'replace'.
515 (4) If optional argument tabsize is not given, a tab size of 8 characters
517 (5) Returns false if string s does not contain at least one character.
518 (6) Returns false if string s does not contain at least one cased
520 (7) A titlecased string is a string in which uppercase characters may only
521 follow uncased characters and lowercase characters only cased ones.
522 (8) s is returned if width is less than len(s).
523 (9) If the optional argument maxsplit is given, only the first maxsplit
524 occurrences are replaced.
525 (10) If sep is not specified or None, any whitespace string is a separator.
526 If maxsplit is given, at most maxsplit splits are done.
527 (11) Line breaks are not included in the resulting list unless keepends is
529 (12) table must be a string of length 256. All characters occurring in the
530 optional argument deletechars are removed prior to translation.
532 String formatting with the % operator
534 formatString % args--> evaluates to a string
536 * formatString uses C printf format codes : %, c, s, i, d, u, o, x, X, e, E,
537 f, g, G, r (details below).
538 * Width and precision may be a * to specify that an integer argument gives
539 the actual width or precision.
540 * The flag characters -, +, blank, # and 0 are understood. (details below)
541 * %s will convert any type argument to string (uses str() function)
542 * args may be a single arg or a tuple of args
544 '%s has %03d quote types.' % ('Python', 2) # => 'Python has 002 quote types.'
546 * Right-hand-side can also be a mapping:
548 a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python}
549 (vars() function very handy to use on right-hand-side.)
553 d Signed integer decimal.
554 i Signed integer decimal.
557 x Unsigned hexidecimal (lowercase).
558 X Unsigned hexidecimal (uppercase).
559 e Floating point exponential format (lowercase).
560 E Floating point exponential format (uppercase).
561 f Floating point decimal format.
562 F Floating point decimal format.
563 g Same as "e" if exponent is greater than -4 or less than precision,
565 G Same as "E" if exponent is greater than -4 or less than precision,
567 c Single character (accepts integer or single character string).
568 r String (converts any python object using repr()).
569 s String (converts any python object using str()).
570 % No argument is converted, results in a "%" character in the result.
571 (The complete specification is %%.)
573 Conversion flag characters
575 # The value conversion will use the ``alternate form''.
576 0 The conversion will be zero padded.
577 - The converted value is left adjusted (overrides "-").
578 (a space) A blank should be left before a positive number (or empty
579 string) produced by a signed conversion.
580 + A sign character ("+" or "-") will precede the conversion (overrides a
585 Created with built-in function open; may be created by other modules' functions
588 Operators on file objects
592 f.close() Close file f.
593 f.fileno() Get fileno (fd) for file f.
594 f.flush() Flush file f's internal buffer.
595 f.isatty() 1 if file f is connected to a tty-like dev, else 0.
596 f.read([size]) Read at most size bytes from file f and return as a string
597 object. If size omitted, read to EOF.
598 f.readline() Read one entire line from file f.
599 f.readlines() Read until EOF with readline() and return list of lines read.
600 Set file f's position, like "stdio's fseek()".
601 f.seek(offset[, whence == 0 then use absolute indexing.
602 whence=0]) whence == 1 then offset relative to current pos.
603 whence == 2 then offset relative to file end.
604 f.tell() Return file f's current position (byte offset).
605 f.write(str) Write string to file f.
606 f.writelines(list Write list of strings to file f.
612 End-of-file hit when reading (may be raised many times, e.g. if f is a
615 Other I/O-related I/O operation failure
620 -See manuals for more details -
623 + Class instance objects
624 + Type objects (see module: types)
625 + File objects (see above)
629 o User-defined (written in Python):
630 # User-defined Function objects
631 # User-defined Method objects
632 o Built-in (written in C):
633 # Built-in Function objects
634 # Built-in Method objects
636 o Code objects (byte-compile executable Python code: bytecode)
637 o Frame objects (execution frames)
638 o Traceback objects (stack trace of an exception)
643 pass -- Null statement
644 del name[,name]* -- Unbind name(s) from object. Object will be indirectly
645 (and automatically) deleted only if no longer referenced.
646 print [>> fileobject,] [s1 [, s2 ]* [,]
647 -- Writes to sys.stdout, or to fileobject if supplied.
648 Puts spaces between arguments. Puts newline at end
649 unless statement ends with comma.
650 Print is not required when running interactively,
651 simply typing an expression will print its value,
652 unless the value is None.
653 exec x [in globals [,locals]]
654 -- Executes x in namespaces provided. Defaults
655 to current namespaces. x can be a string, file
656 object or a function object.
657 callable(value,... [id=value], [*args], [**kw])
658 -- Call function callable with parameters. Parameters can
659 be passed by name or be omitted if function
660 defines default values. E.g. if callable is defined as
661 "def callable(p1=1, p2=2)"
662 "callable()" <=> "callable(1, 2)"
663 "callable(10)" <=> "callable(10, 2)"
664 "callable(p2=99)" <=> "callable(1, 99)"
665 *args is a tuple of positional arguments.
666 **kw is a dictionary of keyword arguments.
671 Operator Result Notes
672 a = b Basic assignment - assign object b to label a (1)
673 a += b Roughly equivalent to a = a + b (2)
674 a -= b Roughly equivalent to a = a - b (2)
675 a *= b Roughly equivalent to a = a * b (2)
676 a /= b Roughly equivalent to a = a / b (2)
677 a %= b Roughly equivalent to a = a % b (2)
678 a **= b Roughly equivalent to a = a ** b (2)
679 a &= b Roughly equivalent to a = a & b (2)
680 a |= b Roughly equivalent to a = a | b (2)
681 a ^= b Roughly equivalent to a = a ^ b (2)
682 a >>= b Roughly equivalent to a = a >> b (2)
683 a <<= b Roughly equivalent to a = a << b (2)
686 (1) Can unpack tuples, lists, and strings.
687 first, second = a[0:2]; [f, s] = range(2); c1,c2,c3='abc'
688 Tip: x,y = y,x swaps x and y.
689 (2) Not exactly equivalent - a is evaluated only once. Also, where
690 possible, operation performed in-place - a is modified rather than
696 [elif condition: suite]*
697 [else: suite] -- usual if/else_if/else statement
698 while condition: suite
700 -- usual while statement. "else" suite is executed
701 after loop exits, unless the loop is exited with
703 for element in sequence: suite
705 -- iterates over sequence, assigning each element to element.
706 Use built-in range function to iterate a number of times.
707 "else" suite executed at end unless loop exited
709 break -- immediately exits "for" or "while" loop
710 continue -- immediately does next iteration of "for" or "while" loop
711 return [result] -- Exits from function (or method) and returns result (use a tuple to
712 return more than one value). If no result given, then returns None.
716 assert expr[, message]
717 -- expr is evaluated. if false, raises exception AssertionError
718 with message. Inhibited if __debug__ is 0.
720 [except [exception [, value]: suite2]+
722 -- statements in suite1 are executed. If an exception occurs, look
723 in "except" clauses for matching <exception>. If matches or bare
724 "except" execute suite of that clause. If no exception happens
725 suite in "else" clause is executed after suite1.
726 If exception has a value, it is put in value.
727 exception can also be tuple of exceptions, e.g.
728 "except (KeyError, NameError), val: print val"
731 -- statements in suite1 are executed. If no
732 exception, execute suite2 (even if suite1 is
733 exited with a "return", "break" or "continue"
734 statement). If exception did occur, executes
735 suite2 and then immediately reraises exception.
736 raise exception [,value [, traceback]]
737 -- raises exception with optional value
738 value. Arg traceback specifies a traceback object to
739 use when printing the exception's backtrace.
740 raise -- a raise statement without arguments re-raises
741 the last exception raised in the current function
742 An exception is either a string (object) or a class instance.
743 Can create a new one simply by creating a new string:
745 my_exception = 'You did something wrong'
748 raise my_exception, bad
749 except my_exception, value:
752 Exception classes must be derived from the predefined class: Exception, e.g.:
753 class text_exception(Exception): pass
756 raise text_exception()
757 # This is a shorthand for the form
758 # "raise <class>, <instance>"
761 # This will be printed because
762 # text_exception is a subclass of Exception
763 When an error message is printed for an unhandled exception which is a
764 class, the class name is printed, then a colon and a space, and
765 finally the instance converted to a string using the built-in function
767 All built-in exception classes derives from StandardError, itself
768 derived from Exception.
770 Name Space Statements
772 [1.51: On Mac & Windows, the case of module file names must now match the case
774 in the import statement]
775 Packages (>1.5): a package is a name space which maps to a directory including
776 module(s) and the special initialization module '__init__.py'
777 (possibly empty). Packages/dirs can be nested. You address a
778 module's symbol via '[package.[package...]module.symbol's.
779 import module1 [as name1] [, module2]*
780 -- imports modules. Members of module must be
781 referred to by qualifying with [package.]module name:
782 "import sys; print sys.argv:"
783 "import package1.subpackage.module; package1.subpackage.module.foo()"
784 module1 renamed as name1, if supplied.
785 from module import name1 [as othername1] [, name2]*
786 -- imports names from module module in current namespace.
787 "from sys import argv; print argv"
788 "from package1 import module; module.foo()"
789 "from package1.module import foo; foo()"
790 name1 renamed as othername1, if supplied.
792 -- imports all names in module, except those starting with "_";
793 *to be used sparsely, beware of name clashes* :
794 "from sys import *; print argv"
795 "from package.module import *; print x'
796 NB: "from package import *" only imports the symbols defined
797 in the package's __init__.py file, not those in the
799 global name1 [, name2]*
800 -- names are from global scope (usually meaning from module)
801 rather than local (usually meaning only in function).
802 -- E.g. in fct without "global" statements, assuming
803 "a" is name that hasn't been used in fct or module
805 -Try to read from "a" -> NameError
806 -Try to write to "a" -> creates "a" local to fcn
807 -If "a" not defined in fct, but is in module, then
808 -Try to read from "a", gets value from module
809 -Try to write to "a", creates "a" local to fct
810 But note "a[0]=3" starts with search for "a",
811 will use to global "a" if no local "a".
815 def func_id ([param_list]): suite
816 -- Creates a function object & binds it to name func_id.
818 param_list ::= [id [, id]*]
819 id ::= value | id = value | *id | **id
820 [Args are passed by value.Thus only args representing a mutable object
821 can be modified (are inout parameters). Use a tuple to return more than
825 def test (p1, p2 = 1+1, *rest, **keywords):
826 -- Parameters with "=" have default value (v is
827 evaluated when function defined).
828 If list has "*id" then id is assigned a tuple of
829 all remaining args passed to function (like C vararg)
830 If list has "**id" then id is assigned a dictionary of
831 all extra arguments passed as keywords.
835 class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite>
836 -- Creates a class object and assigns it name <class_id>
837 <suite> may contain local "defs" of class methods and
838 assignments to class attributes.
840 class my_class (class1, class_list[3]): ...
841 Creates a class object inheriting from both "class1" and whatever
842 class object "class_list[3]" evaluates to. Assigns new
843 class object to name "my_class".
844 - First arg to class methods is always instance object, called 'self'
846 - Special method __init__() is called when instance is created.
847 - Special method __del__() called when no more reference to object.
848 - Create instance by "calling" class object, possibly with arg
849 (thus instance=apply(aClassObject, args...) creates an instance!)
850 - In current implementation, can't subclass off built-in
851 classes. But can "wrap" them, see UserDict & UserList modules,
852 and see __getattr__() below.
855 def __init__(self, name): self.name = name
856 def print_name(self): print "I'm", self.name
857 def call_parent(self): c_parent.print_name(self)
861 instance.print_name()
863 Call parent's super class by accessing parent's method
864 directly and passing "self" explicitly (see "call_parent"
866 Many other special methods available for implementing
867 arithmetic operators, sequence, mapping indexing, etc.
869 Documentation Strings
871 Modules, classes and functions may be documented by placing a string literal by
872 itself as the first statement in the suite. The documentation can be retrieved
873 by getting the '__doc__' attribute from the module, class or function.
878 "A description of the constructor"
880 Then c.__doc__ == "A description of C".
881 Then c.__init__.__doc__ == "A description of the constructor".
885 lambda [param_list]: returnedExpr
886 -- Creates an anonymous function. returnedExpr must be
887 an expression, not a statement (e.g., not "if xx:...",
888 "print xxx", etc.) and thus can't contain newlines.
889 Used mostly for filter(), map(), reduce() functions, and GUI callbacks..
891 result = [expression for item1 in sequence1 [if condition1]
892 [for item2 in sequence2 ... for itemN in sequenceN]
896 for item1 in sequence1:
897 for item2 in sequence2:
899 for itemN in sequenceN:
900 if (condition1) and furthur conditions:
901 result.append(expression)
909 __import__(name[, Imports module within the given context (see lib ref for
910 globals[, locals[, more details)
912 abs(x) Return the absolute value of number x.
913 apply(f, args[, Calls func/method f with arguments args and optional
915 callable(x) Returns 1 if x callable, else 0.
916 chr(i) Returns one-character string whose ASCII code isinteger i
917 cmp(x,y) Returns negative, 0, positive if x <, ==, > to y
918 coerce(x,y) Returns a tuple of the two numeric arguments converted to a
920 Compiles string into a code object.filename is used in
921 error message, can be any string. It isusually the file
922 compile(string, from which the code was read, or eg. '<string>'if not read
923 filename, kind) from file.kind can be 'eval' if string is a single stmt, or
924 'single' which prints the output of expression statements
925 thatevaluate to something else than None, or be 'exec'.
926 complex(real[, Builds a complex object (can also be done using J or j
927 image]) suffix,e.g. 1+3J)
928 delattr(obj, name) deletes attribute named name of object obj <=> del obj.name
929 If no args, returns the list of names in current
930 dir([object]) localsymbol table. With a module, class or class
931 instanceobject as arg, returns list of names in its attr.
933 divmod(a,b) Returns tuple of (a/b, a%b)
934 eval(s[, globals[, Eval string s in (optional) globals, locals contexts.s must
935 locals]]) have no NUL's or newlines. s can also be acode object.
936 Example: x = 1; incr_x = eval('x + 1')
937 execfile(file[, Executes a file without creating a new module, unlike
938 globals[, locals]]) import.
939 filter(function, Constructs a list from those elements of sequence for which
940 sequence) function returns true. function takes one parameter.
941 float(x) Converts a number or a string to floating point.
942 getattr(object, [<default> arg added in 1.5.2]Gets attribute called name
943 name[, default])) from object,e.g. getattr(x, 'f') <=> x.f). If not found,
944 raisesAttributeError or returns default if specified.
945 globals() Returns a dictionary containing current global variables.
946 hasattr(object, Returns true if object has attr called name.
948 hash(object) Returns the hash value of the object (if it has one)
949 hex(x) Converts a number x to a hexadecimal string.
950 id(object) Returns a unique 'identity' integer for an object.
951 input([prompt]) Prints prompt if given. Reads input and evaluates it.
952 Converts a number or a string to a plain integer. Optional
953 int(x[, base]) base paramenter specifies base from which to convert string
955 intern(aString) Enters aString in the table of "interned strings"
956 andreturns the string. Interned strings are 'immortals'.
957 isinstance(obj, returns true if obj is an instance of class. Ifissubclass
958 class) (A,B) then isinstance(x,A) => isinstance(x,B)
959 issubclass(class1, returns true if class1 is derived from class2
961 Returns the length (the number of items) of an object
962 len(obj) (sequence, dictionary, or instance of class implementing
964 list(sequence) Converts sequence into a list. If already a list,returns a
966 locals() Returns a dictionary containing current local variables.
967 Converts a number or a string to a long integer. Optional
968 long(x[, base]) base paramenter specifies base from which to convert string
970 Applies function to every item of list and returns a listof
971 map(function, list, the results. If additional arguments are passed,function
972 ...) must take that many arguments and it is givento function on
974 max(seq) Returns the largest item of the non-empty sequence seq.
975 min(seq) Returns the smallest item of a non-empty sequence seq.
976 oct(x) Converts a number to an octal string.
977 open(filename [, Returns a new file object. First two args are same asthose
978 mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered,
979 implementation 1 for line-buffered, negative forsys-default, all else, of
980 dependent]]) (about) given size.
981 ord(c) Returns integer ASCII value of c (a string of len 1). Works
983 pow(x, y [, z]) Returns x to power y [modulo z]. See also ** operator.
984 range(start [,end Returns list of ints from >= start and < end.With 1 arg,
985 [, step]]) list from 0..arg-1With 2 args, list from start..end-1With 3
986 args, list from start up to end by step
987 raw_input([prompt]) Prints prompt if given, then reads string from stdinput (no
988 trailing \n). See also input().
989 reduce(f, list [, Applies the binary function f to the items oflist so as to
990 init]) reduce the list to a single value.If init given, it is
992 Re-parses and re-initializes an already imported module.
993 Useful in interactive mode, if you want to reload amodule
994 reload(module) after fixing it. If module was syntacticallycorrect but had
995 an error in initialization, mustimport it one more time
996 before calling reload().
997 Returns a string containing a printable and if possible
998 repr(object) evaluable representation of an object. <=> `object`
999 (usingbackquotes). Class redefinissable (__repr__). See
1001 round(x, n=0) Returns the floating point value x rounded to n digitsafter
1003 setattr(object, This is the counterpart of getattr().setattr(o, 'foobar',
1004 name, value) 3) <=> o.foobar = 3Creates attribute if it doesn't exist!
1005 slice([start,] stop Returns a slice object representing a range, with R/
1006 [, step]) Oattributes: start, stop, step.
1007 Returns a string containing a nicely
1008 str(object) printablerepresentation of an object. Class overridable
1009 (__str__).See also repr().
1010 tuple(sequence) Creates a tuple with same elements as sequence. If already
1011 a tuple, return itself (not a copy).
1012 Returns a type object [see module types] representing
1013 thetype of obj. Example: import typesif type(x) ==
1014 type(obj) types.StringType: print 'It is a string'NB: it is
1015 recommanded to use the following form:if isinstance(x,
1016 types.StringType): etc...
1018 unicode(string[, Creates a Unicode string from a 8-bit string, using
1019 encoding[, error thegiven encoding name and error treatment ('strict',
1020 ]]]) 'ignore',or 'replace'}.
1021 Without arguments, returns a dictionary correspondingto the
1022 current local symbol table. With a module,class or class
1023 vars([object]) instance object as argumentreturns a dictionary
1024 corresponding to the object'ssymbol table. Useful with "%"
1025 formatting operator.
1026 xrange(start [, end Like range(), but doesn't actually store entire listall at
1027 [, step]]) once. Good to use in "for" loops when there is abig range
1029 zip(seq1[, seq2, Returns a list of tuples where each tuple contains the nth
1030 ...]) element of each of the argument sequences.
1038 Root class for all exceptions
1042 Base class for all built-in exceptions; derived from Exception
1045 Base class for OverflowError, ZeroDivisionError,
1048 When a floating point operation fails.
1050 On excessively large arithmetic operation
1052 On division or modulo operation with 0 as 2nd arg
1054 When an assert statement fails.
1056 On attribute reference or assignment failure
1057 EnvironmentError [new in 1.5.2]
1058 On error outside Python; error arg tuple is (errno, errMsg...)
1059 IOError [changed in 1.5.2]
1060 I/O-related operation failure
1061 OSError [new in 1.5.2]
1062 used by the os module's os.error exception.
1064 Immediate end-of-file hit by input() or raw_input()
1066 On failure of `import' to find module or name
1068 On user entry of the interrupt key (often `Control-C')
1070 base class for IndexError, KeyError
1072 On out-of-range sequence subscript
1074 On reference to a non-existent mapping (dict) key
1076 On recoverable memory exhaustion
1078 On failure to find a local or global (unqualified) name
1080 Obsolete catch-all; define a suitable error instead
1081 NotImplementedError [new in 1.5.2]
1082 On method not implemented
1084 On parser encountering a syntax error
1086 On parser encountering an indentation syntax error
1088 On parser encountering an indentation syntax error
1090 On non-fatal interpreter error - bug - report it
1092 On passing inappropriate type to built-in op or func
1094 On arg error not covered by TypeError or more precise
1098 Standard methods & operators redefinition in classes
1100 Standard methods & operators map to special '__methods__' and thus may be
1101 redefined (mostly in in user-defined classes), e.g.:
1103 def __init__(self, v): self.value = v
1104 def __add__(self, r): return self.value + r
1105 a = x(3) # sort of like calling x.__init__(a, 3)
1106 a + 4 # is equivalent to a.__add__(4)
1108 Special methods for any class
1111 __init__(s, args) instance initialization (on construction)
1112 __del__(s) called on object demise (refcount becomes 0)
1113 __repr__(s) repr() and `...` conversions
1114 __str__(s) str() and 'print' statement
1115 __cmp__(s, o) Compares s to o and returns <0, 0, or >0.
1116 Implements >, <, == etc...
1117 __hash__(s) Compute a 32 bit hash code; hash() and dictionary ops
1118 __nonzero__(s) Returns 0 or 1 for truth value testing
1119 __getattr__(s, name) called when attr lookup doesn't find <name>
1120 __setattr__(s, name, val) called when setting an attr
1121 (inside, don't use "self.name = value"
1122 use "self.__dict__[name] = val")
1123 __delattr__(s, name) called to delete attr <name>
1124 __call__(self, *args) called when an instance is called as function.
1128 See list in the operator module. Operator function names are provided with
1129 2 variants, with or without
1130 ading & trailing '__' (eg. __add__ or add).
1132 Numeric operations special methods
1135 s+o = __add__(s,o) s-o = __sub__(s,o)
1136 s*o = __mul__(s,o) s/o = __div__(s,o)
1137 s%o = __mod__(s,o) divmod(s,o) = __divmod__(s,o)
1140 s^o = __xor__(s,o) s|o = __or__(s,o)
1141 s<<o = __lshift__(s,o) s>>o = __rshift__(s,o)
1142 nonzero(s) = __nonzero__(s) (used in boolean testing)
1143 -s = __neg__(s) +s = __pos__(s)
1144 abs(s) = __abs__(s) ~s = __invert__(s) (bitwise)
1145 s+=o = __iadd__(s,o) s-=o = __isub__(s,o)
1146 s*=o = __imul__(s,o) s/=o = __idiv__(s,o)
1147 s%=o = __imod__(s,o)
1148 s**=o = __ipow__(s,o)
1149 s&=o = __iand__(s,o)
1150 s^=o = __ixor__(s,o) s|=o = __ior__(s,o)
1151 s<<=o = __ilshift__(s,o) s>>=o = __irshift__(s,o)
1153 int(s) = __int__(s) long(s) = __long__(s)
1154 float(s) = __float__(s) complex(s) = __complex__(s)
1155 oct(s) = __oct__(s) hex(s) = __hex__(s)
1156 coerce(s,o) = __coerce__(s,o)
1157 Right-hand-side equivalents for all binary operators exist;
1158 are called when class instance is on r-h-s of operator:
1159 a + 3 calls __add__(a, 3)
1160 3 + a calls __radd__(a, 3)
1162 All seqs and maps, general operations plus:
1163 (s: self, i: index or key)
1165 len(s) = __len__(s) length of object, >= 0. Length 0 == false
1166 s[i] = __getitem__(s,i) Element at index/key i, origin 0
1168 Sequences, general methods, plus:
1169 s[i]=v = __setitem__(s,i,v)
1170 del s[i] = __delitem__(s,i)
1171 s[i:j] = __getslice__(s,i,j)
1172 s[i:j]=seq = __setslice__(s,i,j,seq)
1173 del s[i:j] = __delslice__(s,i,j) == s[i:j] = []
1174 seq * n = __repeat__(seq, n)
1175 s1 + s2 = __concat__(s1, s2)
1176 i in s = __contains__(s, i)
1177 Mappings, general methods, plus
1178 hash(s) = __hash__(s) - hash value for dictionary references
1179 s[k]=v = __setitem__(s,k,v)
1180 del s[k] = __delitem__(s,k)
1182 Special informative state attributes for some types:
1184 Lists & Dictionaries:
1185 __methods__ (list, R/O): list of method names of the object
1188 __doc__ (string/None, R/O): doc string (<=> __dict__['__doc__'])
1189 __name__(string, R/O): module name (also in __dict__['__name__'])
1190 __dict__ (dict, R/O): module's name space
1191 __file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for
1192 modules statically linked to the interpreter)
1193 __path__(string/undefined, R/O): fully qualified package name when applies.
1195 Classes: [in bold: writable since 1.5.2]
1196 __doc__ (string/None, R/W): doc string (<=> __dict__['__doc__'])
1197 __name__(string, R/W): class name (also in __dict__['__name__'])
1198 __bases__ (tuple, R/W): parent classes
1199 __dict__ (dict, R/W): attributes (class name space)
1202 __class__ (class, R/W): instance's class
1203 __dict__ (dict, R/W): attributes
1204 User-defined functions: [bold: writable since 1.5.2]
1205 __doc__ (string/None, R/W): doc string
1206 __name__(string, R/O): function name
1207 func_doc (R/W): same as __doc__
1208 func_name (R/O): same as __name__
1209 func_defaults (tuple/None, R/W): default args values if any
1210 func_code (code, R/W): code object representing the compiled function body
1211 func_globals (dict, R/O): ref to dictionary of func global variables
1213 User-defined Methods:
1214 __doc__ (string/None, R/O): doc string
1215 __name__(string, R/O): method name (same as im_func.__name__)
1216 im_class (class, R/O): class defining the method (may be a base class)
1217 im_self (instance/None, R/O): target instance object (None if unbound)
1218 im_func (function, R/O): function object
1219 Built-in Functions & methods:
1220 __doc__ (string/None, R/O): doc string
1221 __name__ (string, R/O): function name
1222 __self__ : [methods only] target object
1223 __members__ = list of attr names: ['__doc__','__name__','__self__'])
1225 co_name (string, R/O): function name
1226 co_argcount (int, R/0): number of positional args
1227 co_nlocals (int, R/O): number of local vars (including args)
1228 co_varnames (tuple, R/O): names of local vars (starting with args)
1229 co_code (string, R/O): sequence of bytecode instructions
1230 co_consts (tuple, R/O): litterals used by the bytecode, 1st one is
1232 co_names (tuple, R/O): names used by the bytecode
1233 co_filename (string, R/O): filename from which the code was compiled
1234 co_firstlineno (int, R/O): first line number of the function
1235 co_lnotab (string, R/O): string encoding bytecode offsets to line numbers.
1236 co_stacksize (int, R/O): required stack size (including local vars)
1237 co_firstlineno (int, R/O): first line number of the function
1238 co_flags (int, R/O): flags for the interpreter
1239 bit 2 set if fct uses "*arg" syntax
1240 bit 3 set if fct uses '**keywords' syntax
1242 f_back (frame/None, R/O): previous stack frame (toward the caller)
1243 f_code (code, R/O): code object being executed in this frame
1244 f_locals (dict, R/O): local vars
1245 f_globals (dict, R/O): global vars
1246 f_builtins (dict, R/O): built-in (intrinsic) names
1247 f_restricted (int, R/O): flag indicating whether fct is executed in
1249 f_lineno (int, R/O): current line number
1250 f_lasti (int, R/O): precise instruction (index into bytecode)
1251 f_trace (function/None, R/W): debug hook called at start of each source line
1252 f_exc_type (Type/None, R/W): Most recent exception type
1253 f_exc_value (any, R/W): Most recent exception value
1254 f_exc_traceback (traceback/None, R/W): Most recent exception traceback
1256 tb_next (frame/None, R/O): next level in stack trace (toward the frame where
1257 the exception occurred)
1258 tb_frame (frame, R/O): execution frame of the current level
1259 tb_lineno (int, R/O): line number where the exception occured
1260 tb_lasti (int, R/O): precise instruction (index into bytecode)
1263 start (any/None, R/O): lowerbound
1264 stop (any/None, R/O): upperbound
1265 step (any/None, R/O): step value
1268 real (float, R/O): real part
1269 imag (float, R/O): imaginary part
1271 tolist (Built-in method, R/O): ?
1280 argv The list of command line arguments passed to aPython
1281 script. sys.argv[0] is the script name.
1282 builtin_module_names A list of strings giving the names of all moduleswritten
1283 in C that are linked into this interpreter.
1284 check_interval How often to check for thread switches or signals(measured
1285 in number of virtual machine instructions)
1286 exc_type, exc_value, Deprecated since release 1.5. Use exc_info() instead.
1288 exitfunc User can set to a parameterless fcn. It will getcalled
1289 before interpreter exits.
1290 last_type, Set only when an exception not handled andinterpreter
1291 last_value, prints an error. Used by debuggers.
1293 maxint maximum positive value for integers
1294 modules Dictionary of modules that have already been loaded.
1295 path Search path for external modules. Can be modifiedby
1296 program. sys.path[0] == dir of script executing
1297 platform The current platform, e.g. "sunos5", "win32"
1298 ps1, ps2 prompts to use in interactive mode.
1299 File objects used for I/O. One can redirect byassigning a
1300 stdin, stdout, new file object to them (or any object:.with a method
1301 stderr write(string) for stdout/stderr,.with a method readline()
1303 version string containing version info about Python interpreter.
1304 (and also: copyright, dllhandle, exec_prefix, prefix)
1305 version_info tuple containing Python version info - (major, minor,
1306 micro, level, serial).
1310 exit(n) Exits with status n. Raises SystemExit exception.(Hence can
1311 be caught and ignored by program)
1312 getrefcount(object Returns the reference count of the object. Generally 1
1313 ) higherthan you might expect, because of object arg temp
1315 setcheckinterval( Sets the interpreter's thread switching interval (in number
1316 interval) ofvirtualcode instructions, default:10).
1317 settrace(func) Sets a trace function: called before each line ofcode is
1319 setprofile(func) Sets a profile function for performance profiling.
1320 Info on exception currently being handled; this is atuple
1321 (exc_type, exc_value, exc_traceback).Warning: assigning the
1322 exc_info() traceback return value to a loca variable in a
1323 functionhandling an exception will cause a circular
1325 setdefaultencoding Change default Unicode encoding - defaults to 7-bit ASCII.
1327 getrecursionlimit Retrieve maximum recursion depth.
1329 setrecursionlimit Set maximum recursion depth. (Defaults to 1000.)
1335 "synonym" for whatever O/S-specific module is proper for current environment.
1336 this module uses posix whenever possible.
1337 (see also M.A. Lemburg's utility http://www.lemburg.com/files/python/
1342 name name of O/S-specific module (e.g. "posix", "mac", "nt")
1343 path O/S-specific module for path manipulations.
1344 On Unix, os.path.split() <=> posixpath.split()
1345 curdir string used to represent current directory ('.')
1346 pardir string used to represent parent directory ('..')
1347 sep string used to separate directories ('/' or '\'). Tip: use
1348 os.path.join() to build portable paths.
1349 altsep Alternate sep
1352 pathsep character used to separate search path components (as in
1353 $PATH), eg. ';' for windows.
1354 linesep line separator as used in binary files, ie '\n' on Unix, '\
1355 r\n' on Dos/Win, '\r'
1359 makedirs(path[, Recursive directory creation (create required intermediary
1360 mode=0777]) dirs); os.error if fails.
1361 removedirs(path) Recursive directory delete (delete intermediary empty
1363 renames(old, new) Recursive directory or file renaming; os.error if fails.
1368 don't import this module directly, import os instead !
1369 (see also module: shutil for file copy & remove fcts)
1373 environ dictionary of environment variables, e.g.posix.environ['HOME'].
1374 error exception raised on POSIX-related error.
1375 Corresponding value is tuple of errno code and perror() string.
1377 Some posix functions
1379 chdir(path) Changes current directory to path.
1380 chmod(path, Changes the mode of path to the numeric mode
1382 close(fd) Closes file descriptor fd opened with posix.open.
1383 _exit(n) Immediate exit, with no cleanups, no SystemExit,etc. Should use
1384 this to exit a child process.
1385 execv(p, args) "Become" executable p with args args
1386 getcwd() Returns a string representing the current working directory
1387 getpid() Returns the current process id
1388 fork() Like C's fork(). Returns 0 to child, child pid to parent.[Not
1390 kill(pid, Like C's kill [Not on Windows]
1392 listdir(path) Lists (base)names of entries in directory path, excluding '.'
1394 lseek(fd, pos, Sets current position in file fd to position pos, expressedas
1395 how) an offset relative to beginning of file (how=0), tocurrent
1396 position (how=1), or to end of file (how=2)
1397 mkdir(path[, Creates a directory named path with numeric mode (default 0777)
1399 open(file, Like C's open(). Returns file descriptor. Use file object
1400 flags, mode) fctsrather than this low level ones.
1401 pipe() Creates a pipe. Returns pair of file descriptors (r, w) [Not on
1403 popen(command, Opens a pipe to or from command. Result is a file object to
1404 mode='r', read to orwrite from, as indicated by mode being 'r' or 'w'.
1405 bufSize=0) Use it to catch acommand output ('r' mode) or to feed it ('w'
1407 remove(path) See unlink.
1408 rename(src, dst Renames/moves the file or directory src to dst. [error iftarget
1409 ) name already exists]
1410 rmdir(path) Removes the empty directory path
1411 read(fd, n) Reads n bytes from file descriptor fd and return as string.
1412 Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid,
1413 stat(path) st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid
1414 are dummy on Windows]
1415 system(command) Executes string command in a subshell. Returns exitstatus of
1416 subshell (usually 0 means OK).
1417 Returns accumulated CPU times in sec (user, system, children's
1418 times() user,children's sys, elapsed real time). [3 last not on
1420 unlink(path) Unlinks ("deletes") the file (not dir!) path. same as: remove
1421 utime(path, ( Sets the access & modified time of the file to the given tuple
1422 aTime, mTime)) of values.
1423 wait() Waits for child process completion. Returns tuple ofpid,
1424 exit_status [Not on Windows]
1425 waitpid(pid, Waits for process pid to complete. Returns tuple ofpid,
1426 options) exit_status [Not on Windows]
1427 write(fd, str) Writes str to file fd. Returns nb of bytes written.
1432 Do not import this module directly, import os instead and refer to this module
1433 as os.path. (e.g. os.path.exists(p)) !
1435 Some posixpath functions
1437 abspath(p) Returns absolute path for path p, taking current working dir in
1440 basename(p directory and name parts of the path p. See also split.
1442 exists(p) True if string p is an existing path (file or directory)
1443 expanduser Returns string that is (a copy of) p with "~" expansion done.
1445 expandvars Returns string that is (a copy of) p with environment vars expanded.
1446 (p) [Windows: case significant; must use Unix: $var notation, not %var%]
1447 getsize( return the size in bytes of filename. raise os.error.
1449 getmtime( return last modification time of filename (integer nb of seconds
1450 filename) since epoch).
1451 getatime( return last access time of filename (integer nb of seconds since
1453 isabs(p) True if string p is an absolute path.
1454 isdir(p) True if string p is a directory.
1455 islink(p) True if string p is a symbolic link.
1456 ismount(p) True if string p is a mount point [true for all dirs on Windows].
1457 join(p[,q Joins one or more path components intelligently.
1459 Splits p into (head, tail) where tail is lastpathname component and
1460 split(p) <head> is everything leadingup to that. <=> (dirname(p), basename
1462 splitdrive Splits path p in a pair ('drive:', tail) [Windows]
1464 splitext(p Splits into (root, ext) where last comp of root contains no periods
1465 ) and ext is empty or startswith a period.
1466 Calls the function visit with arguments(arg, dirname, names) for
1467 each directory recursively inthe directory tree rooted at p
1468 walk(p, (including p itself if it's a dir)The argument dirname specifies the
1469 visit, arg visited directory, the argumentnames lists the files in the
1470 ) directory. The visit function maymodify names to influence the set
1471 of directories visited belowdirname, e.g., to avoid visiting certain
1477 high-level file operations (copying, deleting).
1479 Main shutil functions
1481 copy(src, dst) Copies the contents of file src to file dst, retaining file
1483 copytree(src, dst Recursively copies an entire directory tree rooted at src
1484 [, symlinks]) into dst (which should not already exist). If symlinks is
1485 true, links insrc are kept as such in dst.
1486 rmtree(path[, Deletes an entire directory tree, ignoring errors if
1487 ignore_errors[, ignore_errors true,or calling onerror(func, path,
1488 onerror]]) sys.exc_info()) if supplied with
1490 (and also: copyfile, copymode, copystat, copy2)
1496 altzone signed offset of local DST timezone in sec west of the 0th meridian.
1497 daylight nonzero if a DST timezone is specified
1501 time() return a float representing UTC time in seconds since the epoch.
1502 gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day
1503 localtime( (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is
1504 secs) monday), Julian day(1-366), daylight flag(-1,0 or 1))
1508 format, return a formated string representing time.
1510 mktime(tuple) inverse of localtime(). Return a float.
1511 strptime( parse a formated string representing time, return tuple as in
1514 sleep(secs) Suspend execution for <secs> seconds. <secs> can be a float.
1516 and also: clock, ctime.
1520 As of Python 2.0, much (though not all) of the functionality provided by the
1521 string module have been superseded by built-in string methods - see Operations
1522 on strings for details.
1524 Some string variables
1526 digits The string '0123456789'
1527 hexdigits, octdigits legal hexadecimal & octal digits
1528 letters, uppercase, lowercase, Strings containing the appropriate
1529 whitespace characters
1530 index_error Exception raised by index() if substr not
1533 Some string functions
1535 expandtabs(s, returns a copy of string <s> with tabs expanded.
1537 find/rfind(s, sub Return the lowest/highest index in <s> where the substring
1538 [, start=0[, end= <sub> is found such that <sub> is wholly contained ins
1539 0]) [start:end]. Return -1 if <sub> not found.
1540 ljust/rjust/center Return a copy of string <s> left/right justified/centerd in
1541 (s, width) afield of given width, padded with spaces. <s> is
1543 lower/upper(s) Return a string that is (a copy of) <s> in lowercase/
1545 split(s[, sep= Return a list containing the words of the string <s>,using
1546 whitespace[, the string <sep> as a separator.
1548 join(words[, sep=' Concatenate a list or tuple of words with
1549 ']) interveningseparators; inverse of split.
1550 replace(s, old, Returns a copy of string <s> with all occurences of
1551 new[, maxsplit=0] substring<old> replaced by <new>. Limits to <maxsplit>
1552 firstsubstitutions if specified.
1553 strip(s) Return a string that is (a copy of) <s> without leadingand
1554 trailing whitespace. see also lstrip, rstrip.
1560 Handles Unicode strings. Implemented in new module sre, re now a mere front-end
1562 Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to
1563 litteralize backslashes.
1566 Regular expression syntax
1568 . matches any character (including newline if DOTALL flag specified)
1569 ^ matches start of the string (of every line in MULTILINE mode)
1570 $ matches end of the string (of every line in MULTILINE mode)
1571 * 0 or more of preceding regular expression (as many as possible)
1572 + 1 or more of preceding regular expression (as many as possible)
1573 ? 0 or 1 occurence of preceding regular expression
1574 *?, +?, ?? Same as *, + and ? but matches as few characters as possible
1575 {m,n} matches from m to n repetitions of preceding RE
1576 {m,n}? idem, attempting to match as few repetitions as possible
1577 [ ] defines character set: e.g. '[a-zA-Z]' to match all letters(see also
1579 [^ ] defines complemented character set: matches if char is NOT in set
1580 escapes special chars '*?+&$|()' and introduces special sequences
1581 \ (see below). Due to Python string rules, write as '\\' orr'\' in the
1583 \\ matches a litteral '\'; due to Python string rules, write as '\\\\
1584 'in pattern string, or better using raw string: r'\\'.
1585 | specifies alternative: 'foo|bar' matches 'foo' or 'bar'
1586 (...) matches any RE inside (), and delimits a group.
1587 (?:...) idem but doesn't delimit a group.
1588 matches if ... matches next, but doesn't consume any of the string
1589 (?=...) e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by
1591 (?!...) matches if ... doesn't match next. Negative of (?=...)
1592 (?P<name matches any RE inside (), and delimits a named group. (e.g. r'(?P
1593 >...) <id>[a-zA-Z_]\w*)' defines a group named id)
1594 (?P=name) matches whatever text was matched by the earlier group named name.
1595 (?#...) A comment; ignored.
1596 (?letter) letter is one of 'i','L', 'm', 's', 'x'. Set the corresponding flags
1597 (re.I, re.L, re.M, re.S, re.X) for the entire RE.
1600 Sequence Description
1601 number matches content of the group of the same number; groups are numbered
1603 \A matches only at the start of the string
1604 \b empty str at beg or end of word: '\bis\b' matches 'is', but not 'his'
1605 \B empty str NOT at beginning or end of word
1606 \d any decimal digit (<=> [0-9])
1607 \D any non-decimal digit char (<=> [^O-9])
1608 \s any whitespace char (<=> [ \t\n\r\f\v])
1609 \S any non-whitespace char (<=> [^ \t\n\r\f\v])
1610 \w any alphaNumeric char (depends on LOCALE flag)
1611 \W any non-alphaNumeric char (depends on LOCALE flag)
1612 \Z matches only at the end of the string
1616 error Exception when pattern string isn't a valid regexp.
1620 Compile a RE pattern string into a regular expression object.
1621 Flags (combinable by |):
1623 I or IGNORECASE or (?i)
1624 case insensitive matching
1625 compile( L or LOCALE or (?L)
1626 pattern[, make \w, \W, \b, \B dependent on thecurrent locale
1627 flags=0]) M or MULTILINE or (?m)
1628 matches every new line and not onlystart/end of the whole
1631 '.' matches ALL chars, including newline
1632 X or VERBOSE or (?x)
1633 Ignores whitespace outside character sets
1634 escape(string) return (a copy of) string with all non-alphanumerics
1636 match(pattern, if 0 or more chars at beginning of <string> match the RE pattern
1637 string[, flags string,return a corresponding MatchObject instance, or None if
1639 search(pattern scan thru <string> for a location matching <pattern>, return
1640 , string[, acorresponding MatchObject instance, or None if no match.
1642 split(pattern, split <string> by occurrences of <pattern>. If capturing () are
1643 string[, used inpattern, then occurrences of patterns or subpatterns are
1644 maxsplit=0]) also returned.
1645 findall( return a list of non-overlapping matches in <pattern>, either a
1646 pattern, list ofgroups or a list of tuples if the pattern has more than 1
1648 return string obtained by replacing the (<count> first) lefmost
1649 sub(pattern, non-overlapping occurrences of <pattern> (a string or a RE
1650 repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct
1651 count=0]) called with a single MatchObj arg, which must return the
1654 repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade)
1657 Regular Expression Objects
1660 (RE objects are returned by the compile fct)
1662 re object attributes
1663 Attribute Descrition
1664 flags flags arg used when RE obj was compiled, or 0 if none provided
1665 groupindex dictionary of {group name: group number} in pattern
1666 pattern pattern string from which RE obj was compiled
1670 If zero or more characters at the beginning of string match this
1671 regular expression, return a corresponding MatchObject instance.
1672 Return None if the string does not match the pattern; note that
1673 this is different from a zero-length match.
1674 The optional second parameter pos gives an index in the string
1675 match( where the search is to start; it defaults to 0. This is not
1676 string[, completely equivalent to slicing the string; the '' pattern
1677 pos][, character matches at the real beginning of the string and at
1678 endpos]) positions just after a newline, but not necessarily at the index
1679 where the search is to start.
1680 The optional parameter endpos limits how far the string will be
1681 searched; it will be as if the string is endpos characters long, so
1682 only the characters from pos to endpos will be searched for a
1684 Scan through string looking for a location where this regular
1685 search( expression produces a match, and return a corresponding MatchObject
1686 string[, instance. Return None if no position in the string matches the
1687 pos][, pattern; note that this is different from finding a zero-length
1688 endpos]) match at some point in the string.
1689 The optional pos and endpos parameters have the same meaning as for
1692 string[, Identical to the split() function, using the compiled pattern.
1695 findall( Identical to the findall() function, using the compiled pattern.
1698 string[, Identical to the sub() function, using the compiled pattern.
1701 string[, Identical to the subn() function, using the compiled pattern.
1707 (Match objects are returned by the match & search functions)
1709 Match object attributes
1710 Attribute Description
1711 pos value of pos passed to search or match functions; index intostring at
1712 which RE engine started search.
1713 endpos value of endpos passed to search or match functions; index intostring
1714 beyond which RE engine won't go.
1715 re RE object whose match or search fct produced this MatchObj instance
1716 string string passed to match() or search()
1718 Match object functions
1720 returns one or more groups of the match. If one arg, result is a
1721 group([g1 string;if multiple args, result is a tuple with one item per arg. If
1722 , g2, gi is 0,return value is entire matching string; if 1 <= gi <= 99,
1723 ...]) returnstring matching group #gi (or None if no such group); gi may
1724 also bea group name.
1725 returns a tuple of all groups of the match; groups not
1726 groups() participatingto the match have a value of None. Returns a string
1727 instead of tupleif len(tuple)=1
1729 group), returns indices of start & end of substring matched by group (or
1730 end(group Noneif group exists but doesn't contribute to the match)
1732 span( returns the 2-tuple (start(group), end(group)); can be (None, None)if
1733 group) group didn't contibute to the match.
1742 Functions (see ordinary C man pages for info):
1754 frexp(x) -- Unlike C: (float, int) = frexp(float)
1758 modf(x) -- Unlike C: (float, float) = modf(float)
1769 getopt(list, optstr) -- Similar to C. <optstr> is option
1770 letters to look for. Put ':' after letter
1771 if option takes arg. E.g.
1772 # invocation was "python test.py -c hi -a arg1 arg2"
1773 opts, args = getopt.getopt(sys.argv[1:], 'ab:c:')
1775 [('-c', 'hi'), ('-a', '')]
1780 List of modules and packages in base distribution
1782 (built-ins and content of python Lib directory)
1783 (Python NT distribution, may be slightly different in other distributions)
1785 Standard library modules
1787 aifc Stuff to parse AIFF-C and AIFF files.
1788 anydbm Generic interface to all dbm clones. (dbhash, gdbm,
1790 asynchat Support for 'chat' style protocols
1791 asyncore Asynchronous File I/O (in select style)
1792 atexit Register functions to be called at exit of Python interpreter.
1793 audiodev Audio support for a few platforms.
1794 base64 Conversions to/from base64 RFC-MIME transport encoding .
1795 BaseHTTPServer Base class forhttp services.
1796 Bastion "Bastionification" utility (control access to instance vars)
1797 bdb A generic Python debugger base class.
1798 binhex Macintosh binhex compression/decompression.
1799 bisect List bisection algorithms.
1800 calendar Calendar printing functions.
1801 cgi Wraps the WWW Forms Common Gateway Interface (CGI).
1802 CGIHTTPServer CGI http services.
1803 cmd A generic class to build line-oriented command interpreters.
1804 [DEL:cmp:DEL] [DEL:Efficiently compare files, boolean outcome only.:DEL]
1805 [DEL:cmpcache: [DEL:Same, but caches 'stat' results for speed.:DEL]
1807 code Utilities needed to emulate Python's interactive interpreter
1808 codecs Lookup existing Unicode encodings and register new ones.
1809 colorsys Conversion functions between RGB and other color systems.
1810 commands Tools for executing UNIX commands .
1811 compileall Force "compilation" of all .py files in a directory.
1812 ConfigParser Configuration file parser (much like windows .ini files)
1813 copy Generic shallow and deep copying operations.
1814 copy_reg Helper to provide extensibility for pickle/cPickle.
1815 dbhash (g)dbm-compatible interface to bsdhash.hashopen.
1816 dircache Sorted list of files in a dir, using a cache.
1817 [DEL:dircmp:DEL] [DEL:Defines a class to build directory diff tools on.:DEL]
1818 dis Bytecode disassembler.
1819 distutils Package installation system.
1820 dospath Common operations on DOS pathnames.
1821 dumbdbm A dumb and slow but simple dbm clone.
1822 [DEL:dump:DEL] [DEL:Print python code that reconstructs a variable.:DEL]
1823 exceptions Class based built-in exception hierarchy.
1824 filecmp File comparison.
1825 fileinput Helper class to quickly write a loop over all standard input
1827 [DEL:find:DEL] [DEL:Find files directory hierarchy matching a pattern.:DEL]
1828 fnmatch Filename matching with shell patterns.
1829 formatter A test formatter.
1830 fpformat General floating point formatting functions.
1831 ftplib An FTP client class. Based on RFC 959.
1832 gc Perform garbacge collection, obtain GC debug stats, and tune
1834 getopt Standard command line processing. See also ftp://
1835 www.pauahtun.org/pub/getargspy.zip
1836 getpass Utilities to get a password and/or the current user name.
1837 glob filename globbing.
1838 gopherlib Gopher protocol client interface.
1839 [DEL:grep:DEL] [DEL:'grep' utilities.:DEL]
1840 gzip Read & write gzipped files.
1841 htmlentitydefs Proposed entity definitions for HTML.
1842 htmllib HTML parsing utilities.
1843 httplib HTTP client class.
1844 ihooks Hooks into the "import" mechanism.
1845 imaplib IMAP4 client.Based on RFC 2060.
1846 imghdr Recognizing image files based on their first few bytes.
1847 imputil Privides a way of writing customised import hooks.
1848 keyword List of Python keywords.
1849 knee A Python re-implementation of hierarchical module import.
1850 linecache Cache lines from files.
1851 linuxaudiodev Lunix /dev/audio support.
1852 locale Support for number formatting using the current locale
1854 macpath Pathname (or related) operations for the Macintosh.
1855 macurl2path Mac specific module for conversion between pathnames and URLs.
1856 mailbox A class to handle a unix-style or mmdf-style mailbox.
1857 mailcap Mailcap file handling (RFC 1524).
1858 mhlib MH (mailbox) interface.
1859 mimetools Various tools used by MIME-reading or MIME-writing programs.
1860 mimetypes Guess the MIME type of a file.
1861 MimeWriter Generic MIME writer.
1862 mimify Mimification and unmimification of mail messages.
1863 mmap Interface to memory-mapped files - they behave like mutable
1865 multifile Class to make multi-file messages easier to handle.
1866 mutex Mutual exclusion -- for use with module sched.
1868 nntplib An NNTP client class. Based on RFC 977.
1869 ntpath Common operations on DOS pathnames.
1870 nturl2path Mac specific module for conversion between pathnames and URLs.
1871 os Either mac, dos or posix depending system.
1872 [DEL:packmail: [DEL:Create a self-unpacking shell archive.:DEL]
1874 pdb A Python debugger.
1875 pickle Pickling (save and restore) of Python objects (a faster
1876 Cimplementation exists in built-in module: cPickle).
1877 pipes Conversion pipeline templates.
1878 [DEL:poly:DEL] [DEL:Polynomials.:DEL]
1879 popen2 variations on pipe open.
1880 poplib A POP3 client class. Based on the J. Myers POP3 draft.
1881 posixfile Extended (posix) file operations.
1882 posixpath Common operations on POSIX pathnames.
1883 pprint Support to pretty-print lists, tuples, & dictionaries
1885 profile Class for profiling python code.
1886 pstats Class for printing reports on profiled python code.
1887 pty Pseudo terminal utilities.
1888 pyexpat Interface to the Expay XML parser.
1889 py_compile Routine to "compile" a .py file to a .pyc file.
1890 pyclbr Parse a Python file and retrieve classes and methods.
1891 Queue A multi-producer, multi-consumer queue.
1892 quopri Conversions to/from quoted-printable transport encoding.
1893 rand Don't use unless you want compatibility with C's rand().
1894 random Random variable generators (obsolete, use whrandom)
1895 re Regular Expressions.
1896 reconvert Convert old ("regex") regular expressions to new syntax
1898 regex_syntax Flags for regex.set_syntax().
1899 regexp Backward compatibility for module "regexp" using "regex".
1900 regsub Regular expression subroutines.
1901 repr Redo repr() but with limits on most sizes.
1902 rexec Restricted execution facilities ("safe" exec, eval, etc).
1903 rfc822 RFC-822 message manipulation class.
1904 rlcompleter Word completion for GNU readline 2.0.
1905 robotparser Parse robot.txt files, useful for web spiders.
1906 sched A generally useful event scheduler class.
1907 sgmllib A parser for SGML.
1908 shelve Manage shelves of pickled objects.
1909 shlex Lexical analyzer class for simple shell-like syntaxes.
1910 shutil Utility functions usable in a shell-like program.
1911 SimpleHTTPServer Simple extension to base http class
1912 site Append module search paths for third-party packages to
1914 smtplib SMTP Client class (RFC 821)
1915 sndhdr Several routines that help recognizing sound.
1916 SocketServer Generic socket server classes.
1917 stat Constants and functions for interpreting stat/lstat struct.
1918 statcache Maintain a cache of file stats.
1919 statvfs Constants for interpreting statvfs struct as returned by
1920 os.statvfs()and os.fstatvfs() (if they exist).
1921 string A collection of string operations.
1922 StringIO File-like objects that read/write a string buffer (a fasterC
1923 implementation exists in built-in module: cStringIO).
1924 sunau Stuff to parse Sun and NeXT audio files.
1925 sunaudio Interpret sun audio headers.
1926 symbol Non-terminal symbols of Python grammar (from "graminit.h").
1927 tabnanny,/font> Check Python source for ambiguous indentation.
1928 telnetlib TELNET client class. Based on RFC 854.
1929 tempfile Temporary file name allocation.
1930 threading Proposed new higher-level threading interfaces
1931 threading_api (doc of the threading module)
1932 toaiff Convert "arbitrary" sound files to AIFF files .
1933 token Tokens (from "token.h").
1934 tokenize Compiles a regular expression that recognizes Python tokens.
1935 traceback Format and print Python stack traces.
1936 tty Terminal utilities.
1937 turtle LogoMation-like turtle graphics
1938 types Define names for all type symbols in the std interpreter.
1939 tzparse Parse a timezone specification.
1940 unicodedata Interface to unicode properties.
1941 urllib Open an arbitrary URL.
1942 urlparse Parse URLs according to latest draft of standard.
1943 user Hook to allow user-specified customization code to run.
1944 UserDict A wrapper to allow subclassing of built-in dict class.
1945 UserList A wrapper to allow subclassing of built-in list class.
1946 UserString A wrapper to allow subclassing of built-in string class.
1947 [DEL:util:DEL] [DEL:some useful functions that don't fit elsewhere !!:DEL]
1948 uu UUencode/UUdecode.
1949 wave Stuff to parse WAVE files.
1950 webbrowser Platform independent URL launcher.
1951 [DEL:whatsound: [DEL:Several routines that help recognizing sound files.:DEL]
1953 whichdb Guess which db package to use to open a db file.
1954 whrandom Wichmann-Hill random number generator.
1955 xdrlib Implements (a subset of) Sun XDR (eXternal Data
1957 xmllib A parser for XML, using the derived class as static DTD.
1958 xml.dom Classes for processing XML using the Document Object Model.
1959 xml.sax Classes for processing XML using the SAX API.
1960 zipfile Read & write PK zipped files.
1961 [DEL:zmod:DEL] [DEL:Demonstration of abstruse mathematical concepts.:DEL]
1965 (following list not revised)
1969 sys Interpreter state vars and functions
1970 __built-in__ Access to all built-in python identifiers
1971 __main__ Scope of the interpreters main program, script or stdin
1972 array Obj efficiently representing arrays of basic values
1973 math Math functions of C standard
1974 time Time-related functions
1975 regex Regular expression matching operations
1976 marshal Read and write some python values in binary format
1977 struct Convert between python values and C structs
1981 getopt Parse cmd line args in sys.argv. A la UNIX 'getopt'.
1982 os A more portable interface to OS dependent functionality
1983 re Functions useful for working with regular expressions
1984 string Useful string and characters functions and exceptions
1985 whrandom Wichmann-Hill pseudo-random number generator
1986 thread Low-level primitives for working with process threads
1987 threading idem, new recommanded interface.
1991 dbm Interface to Unix ndbm database library
1992 grp Interface to Unix group database
1993 posix OS functionality standardized by C and POSIX standards
1994 posixpath POSIX pathname functions
1995 pwd Access to the Unix password database
1996 select Access to Unix select multiplex file synchronization
1997 socket Access to BSD socket interface
1999 * Tk User-interface Toolkit *
2001 tkinter Main interface to Tk
2005 audioop Useful operations on sound fragments
2006 imageop Useful operations on images
2007 jpeg Access to jpeg image compressor and decompressor
2008 rgbimg Access SGI imglib image files
2010 * Cryptographic Extensions *
2012 md5 Interface to RSA's MD5 message digest algorithm
2013 mpz Interface to int part of GNU multiple precision library
2014 rotor Implementation of a rotor-based encryption algorithm
2016 * Stdwin * Standard Window System
2018 stdwin Standard Window System interface
2019 stdwinevents Stdwin event, command, and selection constants
2020 rect Rectangle manipulation operations
2022 * SGI IRIX * (4 & 5)
2024 al SGI audio facilities
2026 fl Interface to FORMS library
2028 flp Functions for form designer
2029 fm Access to font manager library
2030 gl Access to graphics library
2032 DEVICE More constants for gl
2033 imgfile Imglib image file interface
2037 sunaudiodev Access to sun audio interface
2040 Workspace exploration and idiom hints
2042 dir(<module>) list functions, variables in <module>
2043 dir() get object keys, defaults to local name space
2044 X.__methods__ list of methods supported by X (if any)
2045 X.__members__ List of X's data attributes
2046 if __name__ == '__main__': main() invoke main if running as script
2047 map(None, lst1, lst2, ...) merge lists
2048 b = a[:] create copy of seq structure
2049 _ in interactive mode, is last value printed
2057 Python Mode for Emacs
2059 (Not revised, possibly not up to date)
2060 Type C-c ? when in python-mode for extensive help.
2062 Primarily for entering new code:
2063 TAB indent line appropriately
2064 LFD insert newline, then indent
2065 DEL reduce indentation, or delete single character
2066 Primarily for reindenting existing code:
2067 C-c : guess py-indent-offset from file content; change locally
2068 C-u C-c : ditto, but change globally
2069 C-c TAB reindent region to match its context
2070 C-c < shift region left by py-indent-offset
2071 C-c > shift region right by py-indent-offset
2072 MARKING & MANIPULATING REGIONS OF CODE
2073 C-c C-b mark block of lines
2074 M-C-h mark smallest enclosing def
2075 C-u M-C-h mark smallest enclosing class
2076 C-c # comment out region of code
2077 C-u C-c # uncomment region of code
2079 C-c C-p move to statement preceding point
2080 C-c C-n move to statement following point
2081 C-c C-u move up to start of current block
2082 M-C-a move to start of def
2083 C-u M-C-a move to start of class
2084 M-C-e move to end of def
2085 C-u M-C-e move to end of class
2086 EXECUTING PYTHON CODE
2087 C-c C-c sends the entire buffer to the Python interpreter
2088 C-c | sends the current region
2089 C-c ! starts a Python interpreter window; this will be used by
2090 subsequent C-c C-c or C-c | commands
2092 py-indent-offset indentation increment
2093 py-block-comment-prefix comment string used by py-comment-region
2094 py-python-command shell command to invoke Python interpreter
2095 py-scroll-process-buffer t means always scroll Python process buffer
2096 py-temp-directory directory used for temp files (if needed)
2097 py-beep-if-tab-change ring the bell if tab-width is changed
2102 (Not revised, possibly not up to date, see 1.5.2 Library Ref section 9.1; in 1.5.2, you may also use debugger integrated in IDLE)
2106 import pdb (it's a module written in Python)
2107 -- defines functions :
2108 run(statement[,globals[, locals]])
2109 -- execute statement string under debugger control, with optional
2110 global & local environment.
2111 runeval(expression[,globals[, locals]])
2112 -- same as run, but evaluate expression and return value.
2113 runcall(function[, argument, ...])
2114 -- run function object with given arg(s)
2115 pm() -- run postmortem on last exception (like debugging a core file)
2117 -- run postmortem on traceback object <t>
2119 -- defines class Pdb :
2120 use Pdb to create reusable debugger objects. Object
2121 preserves state (i.e. break points) between calls.
2123 runs until a breakpoint hit, exception, or end of program
2124 If exception, variable '__exception__' holds (exception,value).
2129 brief reminder of commands
2131 if <arg> numeric, break at line <arg> in current file
2132 if <arg> is function object, break on entry to fcn <arg>
2133 if no arg, list breakpoints
2135 if <arg> numeric, clear breakpoint at <arg> in current file
2136 if no arg, clear all breakpoints after confirmation
2138 print current call stack
2140 move up one stack frame (to top-level caller)
2142 move down one stack frame
2144 advance one line in the program, stepping into calls
2146 advance one line, stepping over calls
2148 continue execution until current function returns
2149 (return value is saved in variable "__return__", which
2150 can be printed or manipulated from debugger)
2152 continue until next breakpoint
2154 print args to current function
2156 prints return value from last function that returned
2158 prints value of <arg> in current stack frame
2159 l, list [<first> [, <last>]]
2160 List source code for the current file.
2161 Without arguments, list 11 lines around the current line
2162 or continue the previous listing.
2163 With one argument, list 11 lines starting at that line.
2164 With two arguments, list the given range;
2165 if the second argument is less than the first, it is a count.
2167 prints type of <arg>
2169 executes rest of line as a Python statement in the current stack frame
2171 immediately stop execution and leave debugger
2173 executes last command again
2174 Any input debugger doesn't recognize as a command is assumed to be a
2175 Python statement to execute in the current stack frame, the same way
2176 the exclamation mark ("!") command does.
2181 Python 1.0.3 (Sep 26 1994)
2182 Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
2185 Traceback (innermost last):
2186 File "<stdin>", line 1
2187 File "./rm.py", line 7
2189 File "./rm.py", line 2
2191 ZeroDivisionError: integer division or modulo
2194 > ./rm.py(2)div: return a / r
2208 >>> pdb.runcall(rm.run)
2213 Breakpoints are stored as filename, line number tuples. If a module is reloaded
2214 after editing, any remembered breakpoints are likely to be wrong.
2216 Always single-steps through top-most stack frame. That is, "c" acts like "n".