blob: a4d96e2dd31d2d4bc859f4882f6a57761573a600 [file] [log] [blame]
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001 Python 2.0 Quick Reference
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002
Guido van Rossumc8180cc1994-08-05 15:57:31 +00003
Guido van Rossumc8180cc1994-08-05 15:57:31 +00004
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00005 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
7from V1.3 ref
81995/10/30, by Chris Hoffmann, choffman@vicorp.com
Guido van Rossumc8180cc1994-08-05 15:57:31 +00009
Andrew M. Kuchling13423f32001-08-06 17:43:49 +000010Based on:
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
15
16 and the readers of comp.lang.python
17
18Python's nest: http://www.python.org Developement: http://
19python.sourceforge.net/ ActivePython : http://www.ActiveState.com/ASPN/
20Python/
21newsgroup: comp.lang.python Help desk: help@python.org
22Resources: http://starship.python.net/ and http://www.vex.net/parnassus/
23Full documentation: http://www.python.org/doc/
24An excellent Python reference book: Python Essential Reference by David Beazley
25(New Riders)
26
27
28Contents
29
30 * Invocation Options
31 * Environment Variables
32 * Lexical Entities : keywords, identifiers, strings, numbers, sequences,
33 dictionaries, operators
34 * Basic Types And Their Operations
35 * Advanced Types
36 * Statements
37 * Built In Functions
38 * Built In Exceptions
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,
42 math, getopt
43 * List of modules In base distribution
44 * Workspace Exploration And Idiom Hints
45 * Python Mode for Emacs
46 * The Python Debugger
47
48
49
50Invocation Options
51
52python [-diOStuUvxX?] [-c command | script | - ] [args]
53
54 Invocation Options
55Option Effect
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]
68-? Help!
69-c Specify the command to execute (see next section). This terminates the
70command option list (following options are passed as arguments to the command).
71 the name of a python file (.py) to execute read from stdin.
72script Anything afterward is passed as options to python script or command,
73 not interpreted as an option to interpreter itself.
74args passed to script or command (in sys.argv[1:])
75 If no script or command, Python enters interactive mode.
76
77 * Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin
78 (Windows).
79
80
81
82Environment variables
83
84 Environment variables
85 Variable Effect
86PYTHONHOME 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
91 (semi-)colons!
92PYTHONPATH 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
96 app.
97 If this is the name of a readable file, the Python commands in
98PYTHONSTARTUP that file are executed before the first prompt is displayed in
99 interactive mode (no default).
100PYTHONDEBUG If non-empty, same as -d option
101PYTHONINSPECT If non-empty, same as -i option
102PYTHONSUPPRESS If non-empty, same as -s option
103PYTHONUNBUFFERED If non-empty, same as -u option
104PYTHONVERBOSE If non-empty, same as -v option
105PYTHONCASEOK If non-empty, ignore case in file/module names (imports)
106
107
108
109
110Notable lexical entities
111
112Keywords
113
114 and del for is raise
115 assert elif from lambda return
116 break else global not try
117 class except if or while
118 continue exec import pass
119 def finally in print
120
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
128 semicolons (";").
129 * Comments start with "#" and continue to end of line.
130
131Identifiers
132
133 (letter | "_") (letter | digit | "_")*
134
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)
139
140Strings
141
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"
152
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
155 'Monty Python'.
156 u'hello' + ' world' --> u'hello world' (coerced to unicode)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000157
158 String Literal Escapes
159
160 \newline Ignored (escape newline)
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000161 \\ 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
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000169
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000170 * NUL byte (\000) is NOT an end-of-string marker; NULs may be embedded in
171 strings.
172 * Strings (and tuples) are immutable: they cannot be modified.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000173
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000174Numbers
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000175
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000176 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
182 imaginary parts)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000183
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000184Sequences
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000185
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000186 * 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:
191 [] [1] [1,2]
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000192
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000193Indexing is 0-based. Negative indices (usually) mean count backwards from end
194of sequence.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000195
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000196Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to
197'0'; End defaults to 'sequence-length'.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000198
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000199a = (0,1,2,3,4,5,6,7)
200 a[3] ==> 3
201 a[-1] ==> 7
202 a[2:4] ==> (2, 3)
203 a[1:] ==> (1, 2, 3, 4, 5, 6, 7)
204 a[:3] ==> (0, 1, 2)
205 a[:] ==> (0,1,2,3,4,5,6,7) # makes a copy of the sequence.
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000206
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000207Dictionaries (Mappings)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000208
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000209 Dictionary of length 0, 1, 2, etc:
210 {} {1 : 'first'} {1 : 'first', 'next': 'second'}
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000211
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000212Operators and their evaluation order
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000213
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000214 Operators and their evaluation order
215Highest Operator Comment
216 (...) [...] {...} `...` Tuple, list & dict. creation; string
217 conv.
218 s[i] s[i:j] s.attr f(...) indexing & slicing; attributes, fct
219 calls
220 +x, -x, ~x Unary operators
221 x**y Power
222 x*y x/y x%y mult, division, modulo
223 x+y x-y addition, substraction
224 x<<y x>>y Bit shifting
225 x&y Bitwise and
226 x^y Bitwise exclusive or
227 x|y Bitwise or
228 x<y x<=y x>y x>=y x==y x!=y Comparison,
229 x<>y identity,
230 x is y x is not y membership
231 x in s x not in s
232 not x boolean negation
233 x and y boolean and
234 x or y boolean or
235Lowest lambda args: expr anonymous function
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000236
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000237Alternate names are defined in module operator (e.g. __add__ and add for +)
238Most operators are overridable
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000239
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000240
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000241Basic Types and Their Operations
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000242
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000243Comparisons (defined between *any* types)
Guido van Rossumc8180cc1994-08-05 15:57:31 +0000244
Andrew M. Kuchling13423f32001-08-06 17:43:49 +0000245 Comparisons
246Comparison Meaning Notes
247< strictly less than (1)
248<= less than or equal to
249> strictly greater than
250>= greater than or equal to
251== equal to
252!= or <> not equal to
253is object identity (2)
254is not negated object identity (2)
255
256Notes :
257 Comparison behavior can be overridden for a given class by defining special
258method __cmp__.
259 (1) X < Y < Z < W has expected meaning, unlike C
260 (2) Compare object identities (i.e. id(object)), not object values.
261
262Boolean values and operators
263
264 Boolean values and operators
265 Value or Operator Returns Notes
266None, numeric zeros, empty sequences and False
267mappings
268all other values True
269not x True if x is False, else
270 True
271x or y if x is False then y, else (1)
272 x
273x and y if x is False then x, else (1)
274 y
275
276Notes :
277 Truth testing behavior can be overridden for a given class by defining
278special method __nonzero__.
279 (1) Evaluate second arg only if necessary to determine outcome.
280
281None
282
283 None is used as default return value on functions. Built-in single object
284 with type NoneType.
285 Input that evaluates to None does not print when running Python
286 interactively.
287
288Numeric types
289
290Floats, integers and long integers.
291
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)
295
296Operators on all numeric types
297
298 Operators on all numeric types
299 Operation Result
300abs(x) the absolute value of x
301int(x) x converted to integer
302long(x) x converted to long integer
303float(x) x converted to floating point
304-x x negated
305+x x unchanged
306x + y the sum of x and y
307x - y difference of x and y
308x * y product of x and y
309x / y quotient of x and y
310x % y remainder of x / y
311divmod(x, y) the tuple (x/y, x%y)
312x ** y x to the power y (the same as pow(x, y))
313
314Bit operators on integers and long integers
315
316 Bit operators
317Operation >Result
318~x the bits of x inverted
319x ^ y bitwise exclusive or of x and y
320x & y bitwise and of x and y
321x | y bitwise or of x and y
322x << n x shifted left by n bits
323x >> n x shifted right by n bits
324
325Complex Numbers
326
327 * represented as a pair of machine-level double precision floating point
328 numbers.
329 * The real and imaginary value of a complex number z can be retrieved through
330 the attributes z.real and z.imag.
331
332Numeric exceptions
333
334TypeError
335 raised on application of arithmetic operation to non-number
336OverflowError
337 numeric bounds exceeded
338ZeroDivisionError
339 raised when zero second argument of div or modulo op
340
341Operations on all sequence types (lists, tuples, strings)
342
343 Operations on all sequence types
344Operation Result Notes
345x in s 1 if an item of s is equal to x, else 0
346x not in s 0 if an item of s is equal to x, else 1
347s + t the concatenation of s and t
348s * n, n*s n copies of s concatenated
349s[i] i'th item of s, origin 0 (1)
350s[i:j] slice of s from i (included) to j (excluded) (1), (2)
351len(s) length of s
352min(s) smallest item of s
353max(s) largest item of (s)
354
355Notes :
356 (1) if i or j is negative, the index is relative to the end of the string,
357ie 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
360index k such that i <= k < j.
361 If i or j is greater than len(s), use len(s). If i is omitted, use
362len(s). If i is greater than or
363 equal to j, the slice is empty.
364
365Operations on mutable (=modifiable) sequences (lists)
366
367 Operations on mutable sequences
368 Operation Result Notes
369s[i] =x item i of s is replaced by x
370s[i:j] = t slice of s from i to j is replaced by t
371del s[i:j] same as s[i:j] = []
372s.append(x) same as s[len(s) : len(s)] = [x]
373s.extend(x) same as s[len(s):len(s)]= x (5)
374s.count(x) return number of i's for which s[i] == x
375s.index(x) return smallest i such that s[i] == x (1)
376s.insert(i, x) same as s[i:i] = [x] if i >= 0
377s.remove(x) same as del s[s.index(x)] (1)
378s.pop([i]) same as x = s[i]; del s[i]; return x (4)
379s.reverse() reverse the items of s in place (3)
380s.sort([cmpFct]) sort the items of s in place (2), (3)
381
382Notes :
383 (1) raise a ValueError exception when x is not found in s (i.e. out of
384range).
385 (2) The sort() method takes an optional argument specifying a comparison
386fct of 2 arguments (list items) which should
387 return -1, 0, or 1 depending on whether the 1st argument is
388considered 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
391of space when sorting or reversing a large list.
392 They don't return the sorted or reversed list to remind you of this
393side effect.
394 (4) [New 1.5.2] The pop() method is experimental and not supported by
395other mutable sequence types than lists.
396 The optional argument i defaults to -1, so that by default the last
397item is removed and returned.
398 (5) [New 1.5.2] Experimental ! Raises an exception when x is not a list
399object.
400
401
402
403Operations on mappings (dictionaries)
404
405 Operations on mappings
406 Operation Result Notes
407len(d) the number of items in d
408d[k] the item of d with key k (1)
409d[k] = x set d[k] to x
410del d[k] remove d[k] from d (1)
411d.clear() remove all items from d
412d.copy() a shallow copy of d
413d.has_key(k) 1 if d has key k, else 0
414d.items() a copy of d's list of (key, item) pairs (2)
415d.keys() a copy of d's list of keys (2)
416d1.update(d2) for k, v in d2.items(): d1[k] = v (3)
417d.values() a copy of d's list of values (2)
418d.get(k,defaultval) the item of d with key k (4)
419d.setdefault(k,defaultval) the item of d with key k (5)
420
421 Notes :
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
427 defaultVal.
428 defaultVal is optional, when not provided and k is not in the map,
429 None is returned.
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
433 added to map.
434
435Operations on strings
436
437Note that these string methods largely (but not completely) supersede the
438functions available in the string module.
439
440
441 Operations on strings
442 Operation Result Notes
443s.capitalize() return a copy of s with only its first character
444 capitalized.
445s.center(width) return a copy of s centered in a string of length width (1)
446 .
447s.count(sub[ return the number of occurrences of substring sub in (2)
448,start[,end]]) string s.
449s.encode([ return an encoded version of s. Default encoding is the
450encoding[,errors current default string encoding. (3)
451]])
452s.endswith(suffix return true if s ends with the specified suffix, (2)
453[,start[,end]]) otherwise return false.
454s.expandtabs([ return a copy of s where all tab characters are (4)
455tabsize]) expanded using spaces.
456s.find(sub[,start return the lowest index in s where substring sub is (2)
457[,end]]) found. Return -1 if sub is not found.
458s.index(sub[ like find(), but raise ValueError when the substring is (2)
459,start[,end]]) not found.
460s.isalnum() return true if all characters in s are alphanumeric, (5)
461 false otherwise.
462s.isalpha() return true if all characters in s are alphabetic, (5)
463 false otherwise.
464s.isdigit() return true if all characters in s are digit (5)
465 characters, false otherwise.
466s.islower() return true if all characters in s are lowercase, false (6)
467 otherwise.
468s.isspace() return true if all characters in s are whitespace (5)
469 characters, false otherwise.
470s.istitle() return true if string s is a titlecased string, false (7)
471 otherwise.
472s.isupper() return true if all characters in s are uppercase, false (6)
473 otherwise.
474s.join(seq) return a concatenation of the strings in the sequence
475 seq, seperated by 's's.
476s.ljust(width) return s left justified in a string of length width. (1),
477 (8)
478s.lower() return a copy of s converted to lowercase.
479s.lstrip() return a copy of s with leading whitespace removed.
480s.replace(old, return a copy of s with all occurrences of substring (9)
481new[, maxsplit]) old replaced by new.
482s.rfind(sub[ return the highest index in s where substring sub is (2)
483,start[,end]]) found. Return -1 if sub is not found.
484s.rindex(sub[ like rfind(), but raise ValueError when the substring (2)
485,start[,end]]) is not found.
486s.rjust(width) return s right justified in a string of length width. (1),
487 (8)
488s.rstrip() return a copy of s with trailing whitespace removed.
489s.split([sep[ return a list of the words in s, using sep as the (10)
490,maxsplit]]) delimiter string.
491s.splitlines([ return a list of the lines in s, breaking at line (11)
492keepends]) boundaries.
493s.startswith return true if s starts with the specified prefix,
494(prefix[,start[ otherwise return false. (2)
495,end]])
496s.strip() return a copy of s with leading and trailing whitespace
497 removed.
498s.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
501s.title() uppercase characters, all remaining cased characters
502 are lowercase.
503s.translate(table return a copy of s mapped through translation table (12)
504[,deletechars]) table.
505s.upper() return a copy of s converted to uppercase.
506
507Notes :
508 (1) Padding is done using spaces.
509 (2) If optional argument start is supplied, substring s[start:] is
510processed. If optional arguments start and end are supplied, substring s[start:
511end] is processed.
512 (3) Optional argument errors may be given to set a different error handling
513scheme. The default for errors is 'strict', meaning that encoding errors raise
514a ValueError. Other possible values are 'ignore' and 'replace'.
515 (4) If optional argument tabsize is not given, a tab size of 8 characters
516is assumed.
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
519character.
520 (7) A titlecased string is a string in which uppercase characters may only
521follow 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
524occurrences are replaced.
525 (10) If sep is not specified or None, any whitespace string is a separator.
526If maxsplit is given, at most maxsplit splits are done.
527 (11) Line breaks are not included in the resulting list unless keepends is
528given and true.
529 (12) table must be a string of length 256. All characters occurring in the
530optional argument deletechars are removed prior to translation.
531
532String formatting with the % operator
533
534formatString % args--> evaluates to a string
535
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
543
544 '%s has %03d quote types.' % ('Python', 2) # => 'Python has 002 quote types.'
545
546 * Right-hand-side can also be a mapping:
547
548 a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python}
549(vars() function very handy to use on right-hand-side.)
550
551 Format codes
552Conversion Meaning
553d Signed integer decimal.
554i Signed integer decimal.
555o Unsigned octal.
556u Unsigned decimal.
557x Unsigned hexidecimal (lowercase).
558X Unsigned hexidecimal (uppercase).
559e Floating point exponential format (lowercase).
560E Floating point exponential format (uppercase).
561f Floating point decimal format.
562F Floating point decimal format.
563g Same as "e" if exponent is greater than -4 or less than precision,
564 "f" otherwise.
565G Same as "E" if exponent is greater than -4 or less than precision,
566 "F" otherwise.
567c Single character (accepts integer or single character string).
568r String (converts any python object using repr()).
569s String (converts any python object using str()).
570% No argument is converted, results in a "%" character in the result.
571 (The complete specification is %%.)
572
573 Conversion flag characters
574Flag Meaning
575# The value conversion will use the ``alternate form''.
5760 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
581 "space" flag).
582
583File Objects
584
585Created with built-in function open; may be created by other modules' functions
586as well.
587
588Operators on file objects
589
590 File operations
591 Operation Result
592f.close() Close file f.
593f.fileno() Get fileno (fd) for file f.
594f.flush() Flush file f's internal buffer.
595f.isatty() 1 if file f is connected to a tty-like dev, else 0.
596f.read([size]) Read at most size bytes from file f and return as a string
597 object. If size omitted, read to EOF.
598f.readline() Read one entire line from file f.
599f.readlines() Read until EOF with readline() and return list of lines read.
600 Set file f's position, like "stdio's fseek()".
601f.seek(offset[, whence == 0 then use absolute indexing.
602whence=0]) whence == 1 then offset relative to current pos.
603 whence == 2 then offset relative to file end.
604f.tell() Return file f's current position (byte offset).
605f.write(str) Write string to file f.
606f.writelines(list Write list of strings to file f.
607)
608
609File Exceptions
610
611 EOFError
612 End-of-file hit when reading (may be raised many times, e.g. if f is a
613 tty).
614 IOError
615 Other I/O-related I/O operation failure
616
617
618 Advanced Types
619
620 -See manuals for more details -
621 + Module objects
622 + Class objects
623 + Class instance objects
624 + Type objects (see module: types)
625 + File objects (see above)
626 + Slice objects
627 + XRange objects
628 + Callable types:
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
635 + Internal Types:
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)
639
640
641 Statements
642
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.
667
668 Assignment operators
669
670 Caption
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)
684
685 Notes :
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
691 replaced.
692
693 Control Flow
694
695 if condition: suite
696 [elif condition: suite]*
697 [else: suite] -- usual if/else_if/else statement
698 while condition: suite
699 [else: suite]
700 -- usual while statement. "else" suite is executed
701 after loop exits, unless the loop is exited with
702 "break"
703 for element in sequence: suite
704 [else: 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
708 with "break"
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.
713
714 Exception Statements
715
716 assert expr[, message]
717 -- expr is evaluated. if false, raises exception AssertionError
718 with message. Inhibited if __debug__ is 0.
719 try: suite1
720 [except [exception [, value]: suite2]+
721 [else: suite3]
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"
729 try: suite1
730 finally: suite2
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
742An exception is either a string (object) or a class instance.
743 Can create a new one simply by creating a new string:
744
745 my_exception = 'You did something wrong'
746 try:
747 if bad:
748 raise my_exception, bad
749 except my_exception, value:
750 print 'Oops', value
751
752Exception classes must be derived from the predefined class: Exception, e.g.:
753 class text_exception(Exception): pass
754 try:
755 if bad:
756 raise text_exception()
757 # This is a shorthand for the form
758 # "raise <class>, <instance>"
759 except Exception:
760 print 'Oops'
761 # This will be printed because
762 # text_exception is a subclass of Exception
763When an error message is printed for an unhandled exception which is a
764class, the class name is printed, then a colon and a space, and
765finally the instance converted to a string using the built-in function
766str().
767All built-in exception classes derives from StandardError, itself
768derived from Exception.
769
770Name Space Statements
771
772[1.51: On Mac & Windows, the case of module file names must now match the case
773as used
774 in the import statement]
775Packages (>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.
779import 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.
785from 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.
791from module import *
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
798 template modules!
799global 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
804 so far:
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".
812
813Function Definition
814
815def func_id ([param_list]): suite
816 -- Creates a function object & binds it to name func_id.
817
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
822 one value]
823
824Example:
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.
832
833Class Definition
834
835class <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.
839Example:
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'
845 by convention.
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.
853Example:
854 class c (c_parent):
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)
858 instance = c('tom')
859 print instance.name
860 'tom'
861 instance.print_name()
862 "I'm tom"
863 Call parent's super class by accessing parent's method
864 directly and passing "self" explicitly (see "call_parent"
865 in example above).
866 Many other special methods available for implementing
867 arithmetic operators, sequence, mapping indexing, etc.
868
869Documentation Strings
870
871Modules, classes and functions may be documented by placing a string literal by
872itself as the first statement in the suite. The documentation can be retrieved
873by getting the '__doc__' attribute from the module, class or function.
874Example:
875 class C:
876 "A description of C"
877 def __init__(self):
878 "A description of the constructor"
879 # etc.
880Then c.__doc__ == "A description of C".
881Then c.__init__.__doc__ == "A description of the constructor".
882
883Others
884
885lambda [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..
890List comprehensions
891result = [expression for item1 in sequence1 [if condition1]
892 [for item2 in sequence2 ... for itemN in sequenceN]
893 ]
894is equivalent to:
895result = []
896for item1 in sequence1:
897 for item2 in sequence2:
898 ...
899 for itemN in sequenceN:
900 if (condition1) and furthur conditions:
901 result.append(expression)
902
903
904
905Built-In Functions
906
907 Built-In Functions
908 Function Result
909__import__(name[, Imports module within the given context (see lib ref for
910globals[, locals[, more details)
911fromlist]]])
912abs(x) Return the absolute value of number x.
913apply(f, args[, Calls func/method f with arguments args and optional
914keywords]) keywords.
915callable(x) Returns 1 if x callable, else 0.
916chr(i) Returns one-character string whose ASCII code isinteger i
917cmp(x,y) Returns negative, 0, positive if x <, ==, > to y
918coerce(x,y) Returns a tuple of the two numeric arguments converted to a
919 common type.
920 Compiles string into a code object.filename is used in
921 error message, can be any string. It isusually the file
922compile(string, from which the code was read, or eg. '<string>'if not read
923filename, 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'.
926complex(real[, Builds a complex object (can also be done using J or j
927image]) suffix,e.g. 1+3J)
928delattr(obj, name) deletes attribute named name of object obj <=> del obj.name
929 If no args, returns the list of names in current
930dir([object]) localsymbol table. With a module, class or class
931 instanceobject as arg, returns list of names in its attr.
932 dict.
933divmod(a,b) Returns tuple of (a/b, a%b)
934eval(s[, globals[, Eval string s in (optional) globals, locals contexts.s must
935locals]]) have no NUL's or newlines. s can also be acode object.
936 Example: x = 1; incr_x = eval('x + 1')
937execfile(file[, Executes a file without creating a new module, unlike
938globals[, locals]]) import.
939filter(function, Constructs a list from those elements of sequence for which
940sequence) function returns true. function takes one parameter.
941float(x) Converts a number or a string to floating point.
942getattr(object, [<default> arg added in 1.5.2]Gets attribute called name
943name[, default])) from object,e.g. getattr(x, 'f') <=> x.f). If not found,
944 raisesAttributeError or returns default if specified.
945globals() Returns a dictionary containing current global variables.
946hasattr(object, Returns true if object has attr called name.
947name)
948hash(object) Returns the hash value of the object (if it has one)
949hex(x) Converts a number x to a hexadecimal string.
950id(object) Returns a unique 'identity' integer for an object.
951input([prompt]) Prints prompt if given. Reads input and evaluates it.
952 Converts a number or a string to a plain integer. Optional
953int(x[, base]) base paramenter specifies base from which to convert string
954 values.
955intern(aString) Enters aString in the table of "interned strings"
956 andreturns the string. Interned strings are 'immortals'.
957isinstance(obj, returns true if obj is an instance of class. Ifissubclass
958class) (A,B) then isinstance(x,A) => isinstance(x,B)
959issubclass(class1, returns true if class1 is derived from class2
960class2)
961 Returns the length (the number of items) of an object
962len(obj) (sequence, dictionary, or instance of class implementing
963 __len__).
964list(sequence) Converts sequence into a list. If already a list,returns a
965 copy of it.
966locals() Returns a dictionary containing current local variables.
967 Converts a number or a string to a long integer. Optional
968long(x[, base]) base paramenter specifies base from which to convert string
969 values.
970 Applies function to every item of list and returns a listof
971map(function, list, the results. If additional arguments are passed,function
972...) must take that many arguments and it is givento function on
973 each call.
974max(seq) Returns the largest item of the non-empty sequence seq.
975min(seq) Returns the smallest item of a non-empty sequence seq.
976oct(x) Converts a number to an octal string.
977open(filename [, Returns a new file object. First two args are same asthose
978mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered,
979implementation 1 for line-buffered, negative forsys-default, all else, of
980dependent]]) (about) given size.
981ord(c) Returns integer ASCII value of c (a string of len 1). Works
982 with Unicode char.
983pow(x, y [, z]) Returns x to power y [modulo z]. See also ** operator.
984range(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
987raw_input([prompt]) Prints prompt if given, then reads string from stdinput (no
988 trailing \n). See also input().
989reduce(f, list [, Applies the binary function f to the items oflist so as to
990init]) reduce the list to a single value.If init given, it is
991 "prepended" to list.
992 Re-parses and re-initializes an already imported module.
993 Useful in interactive mode, if you want to reload amodule
994reload(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
998repr(object) evaluable representation of an object. <=> `object`
999 (usingbackquotes). Class redefinissable (__repr__). See
1000 also str()
1001round(x, n=0) Returns the floating point value x rounded to n digitsafter
1002 the decimal point.
1003setattr(object, This is the counterpart of getattr().setattr(o, 'foobar',
1004name, value) 3) <=> o.foobar = 3Creates attribute if it doesn't exist!
1005slice([start,] stop Returns a slice object representing a range, with R/
1006[, step]) Oattributes: start, stop, step.
1007 Returns a string containing a nicely
1008str(object) printablerepresentation of an object. Class overridable
1009 (__str__).See also repr().
1010tuple(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) ==
1014type(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...
1017unichr(code) code.
1018unicode(string[, Creates a Unicode string from a 8-bit string, using
1019encoding[, 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
1023vars([object]) instance object as argumentreturns a dictionary
1024 corresponding to the object'ssymbol table. Useful with "%"
1025 formatting operator.
1026xrange(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
1028 and little memory.
1029zip(seq1[, seq2, Returns a list of tuples where each tuple contains the nth
1030...]) element of each of the argument sequences.
1031
1032
1033
1034
1035Built-In Exceptions
1036
1037Exception>
1038 Root class for all exceptions
1039 SystemExit
1040 On 'sys.exit()'
1041 StandardError
1042 Base class for all built-in exceptions; derived from Exception
1043 root class.
1044 ArithmeticError
1045 Base class for OverflowError, ZeroDivisionError,
1046 FloatingPointError
1047 FloatingPointError
1048 When a floating point operation fails.
1049 OverflowError
1050 On excessively large arithmetic operation
1051 ZeroDivisionError
1052 On division or modulo operation with 0 as 2nd arg
1053 AssertionError
1054 When an assert statement fails.
1055 AttributeError
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.
1063 EOFError
1064 Immediate end-of-file hit by input() or raw_input()
1065 ImportError
1066 On failure of `import' to find module or name
1067 KeyboardInterrupt
1068 On user entry of the interrupt key (often `Control-C')
1069 LookupError
1070 base class for IndexError, KeyError
1071 IndexError
1072 On out-of-range sequence subscript
1073 KeyError
1074 On reference to a non-existent mapping (dict) key
1075 MemoryError
1076 On recoverable memory exhaustion
1077 NameError
1078 On failure to find a local or global (unqualified) name
1079 RuntimeError
1080 Obsolete catch-all; define a suitable error instead
1081 NotImplementedError [new in 1.5.2]
1082 On method not implemented
1083 SyntaxError
1084 On parser encountering a syntax error
1085 IndentationError
1086 On parser encountering an indentation syntax error
1087 TabError
1088 On parser encountering an indentation syntax error
1089 SystemError
1090 On non-fatal interpreter error - bug - report it
1091 TypeError
1092 On passing inappropriate type to built-in op or func
1093 ValueError
1094 On arg error not covered by TypeError or more precise
1095
1096
1097
1098Standard methods & operators redefinition in classes
1099
1100Standard methods & operators map to special '__methods__' and thus may be
1101 redefined (mostly in in user-defined classes), e.g.:
1102 class x:
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)
1107
1108Special methods for any class
1109
1110(s: self, o: other)
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.
1125
1126Operators
1127
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).
1131
1132 Numeric operations special methods
1133 (s: self, o: other)
1134
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)
1138 s**o = __pow__(s,o)
1139 s&o = __and__(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)
1152 Conversions
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)
1161
1162 All seqs and maps, general operations plus:
1163 (s: self, i: index or key)
1164
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
1167
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)
1181
1182Special informative state attributes for some types:
1183
1184 Lists & Dictionaries:
1185 __methods__ (list, R/O): list of method names of the object
1186
1187 Modules:
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.
1194
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)
1200
1201 Instances:
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
1212
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__'])
1224 Codes:
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
1231 fct doc (or None)
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
1241 Frames:
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
1248 restricted mode
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
1255 Tracebacks:
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)
1261
1262 Slices:
1263 start (any/None, R/O): lowerbound
1264 stop (any/None, R/O): upperbound
1265 step (any/None, R/O): step value
1266
1267 Complex numbers:
1268 real (float, R/O): real part
1269 imag (float, R/O): imaginary part
1270 XRanges:
1271 tolist (Built-in method, R/O): ?
1272
1273
1274Important Modules
1275
1276 sys
1277
1278 Some sys variables
1279 Variable Content
1280argv The list of command line arguments passed to aPython
1281 script. sys.argv[0] is the script name.
1282builtin_module_names A list of strings giving the names of all moduleswritten
1283 in C that are linked into this interpreter.
1284check_interval How often to check for thread switches or signals(measured
1285 in number of virtual machine instructions)
1286exc_type, exc_value, Deprecated since release 1.5. Use exc_info() instead.
1287exc_traceback
1288exitfunc User can set to a parameterless fcn. It will getcalled
1289 before interpreter exits.
1290last_type, Set only when an exception not handled andinterpreter
1291last_value, prints an error. Used by debuggers.
1292last_traceback
1293maxint maximum positive value for integers
1294modules Dictionary of modules that have already been loaded.
1295path Search path for external modules. Can be modifiedby
1296 program. sys.path[0] == dir of script executing
1297platform The current platform, e.g. "sunos5", "win32"
1298ps1, ps2 prompts to use in interactive mode.
1299 File objects used for I/O. One can redirect byassigning a
1300stdin, stdout, new file object to them (or any object:.with a method
1301stderr write(string) for stdout/stderr,.with a method readline()
1302 for stdin)
1303version string containing version info about Python interpreter.
1304 (and also: copyright, dllhandle, exec_prefix, prefix)
1305version_info tuple containing Python version info - (major, minor,
1306 micro, level, serial).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001307
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001308 Some sys functions
1309 Function Result
1310exit(n) Exits with status n. Raises SystemExit exception.(Hence can
1311 be caught and ignored by program)
1312getrefcount(object Returns the reference count of the object. Generally 1
1313) higherthan you might expect, because of object arg temp
1314 reference.
1315setcheckinterval( Sets the interpreter's thread switching interval (in number
1316interval) ofvirtualcode instructions, default:10).
1317settrace(func) Sets a trace function: called before each line ofcode is
1318 exited.
1319setprofile(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
1322exc_info() traceback return value to a loca variable in a
1323 functionhandling an exception will cause a circular
1324 reference.
1325setdefaultencoding Change default Unicode encoding - defaults to 7-bit ASCII.
1326(encoding)
1327getrecursionlimit Retrieve maximum recursion depth.
1328()
1329setrecursionlimit Set maximum recursion depth. (Defaults to 1000.)
1330()
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001331
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001332
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001333
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001334 os
1335"synonym" for whatever O/S-specific module is proper for current environment.
1336this module uses posix whenever possible.
1337(see also M.A. Lemburg's utility http://www.lemburg.com/files/python/
1338platform.py)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001339
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001340 Some os variables
1341 Variable Meaning
1342name name of O/S-specific module (e.g. "posix", "mac", "nt")
1343path O/S-specific module for path manipulations.
1344 On Unix, os.path.split() <=> posixpath.split()
1345curdir string used to represent current directory ('.')
1346pardir string used to represent parent directory ('..')
1347sep string used to separate directories ('/' or '\'). Tip: use
1348 os.path.join() to build portable paths.
1349altsep Alternate sep
1350if applicable (None
1351otherwise)
1352pathsep character used to separate search path components (as in
1353 $PATH), eg. ';' for windows.
1354linesep line separator as used in binary files, ie '\n' on Unix, '\
1355 r\n' on Dos/Win, '\r'
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001356
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001357 Some os functions
1358 Function Result
1359makedirs(path[, Recursive directory creation (create required intermediary
1360mode=0777]) dirs); os.error if fails.
1361removedirs(path) Recursive directory delete (delete intermediary empty
1362 dirs); if fails.
1363renames(old, new) Recursive directory or file renaming; os.error if fails.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001364
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001365
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001366
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001367 posix
1368don't import this module directly, import os instead !
1369(see also module: shutil for file copy & remove fcts)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001370
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001371 posix Variables
1372Variable Meaning
1373environ dictionary of environment variables, e.g.posix.environ['HOME'].
1374error exception raised on POSIX-related error.
1375 Corresponding value is tuple of errno code and perror() string.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001376
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001377 Some posix functions
1378 Function Result
1379chdir(path) Changes current directory to path.
1380chmod(path, Changes the mode of path to the numeric mode
1381mode)
1382close(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.
1385execv(p, args) "Become" executable p with args args
1386getcwd() Returns a string representing the current working directory
1387getpid() Returns the current process id
1388fork() Like C's fork(). Returns 0 to child, child pid to parent.[Not
1389 on Windows]
1390kill(pid, Like C's kill [Not on Windows]
1391signal)
1392listdir(path) Lists (base)names of entries in directory path, excluding '.'
1393 and '..'
1394lseek(fd, pos, Sets current position in file fd to position pos, expressedas
1395how) an offset relative to beginning of file (how=0), tocurrent
1396 position (how=1), or to end of file (how=2)
1397mkdir(path[, Creates a directory named path with numeric mode (default 0777)
1398mode])
1399open(file, Like C's open(). Returns file descriptor. Use file object
1400flags, mode) fctsrather than this low level ones.
1401pipe() Creates a pipe. Returns pair of file descriptors (r, w) [Not on
1402 Windows].
1403popen(command, Opens a pipe to or from command. Result is a file object to
1404mode='r', read to orwrite from, as indicated by mode being 'r' or 'w'.
1405bufSize=0) Use it to catch acommand output ('r' mode) or to feed it ('w'
1406 mode).
1407remove(path) See unlink.
1408rename(src, dst Renames/moves the file or directory src to dst. [error iftarget
1409) name already exists]
1410rmdir(path) Removes the empty directory path
1411read(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,
1413stat(path) st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid
1414 are dummy on Windows]
1415system(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
1418times() user,children's sys, elapsed real time). [3 last not on
1419 Windows]
1420unlink(path) Unlinks ("deletes") the file (not dir!) path. same as: remove
1421utime(path, ( Sets the access & modified time of the file to the given tuple
1422aTime, mTime)) of values.
1423wait() Waits for child process completion. Returns tuple ofpid,
1424 exit_status [Not on Windows]
1425waitpid(pid, Waits for process pid to complete. Returns tuple ofpid,
1426options) exit_status [Not on Windows]
1427write(fd, str) Writes str to file fd. Returns nb of bytes written.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001428
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001429
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001430
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001431 posixpath
1432Do not import this module directly, import os instead and refer to this module
1433as os.path. (e.g. os.path.exists(p)) !
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001434
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001435 Some posixpath functions
1436 Function Result
1437abspath(p) Returns absolute path for path p, taking current working dir in
1438 account.
1439dirname/
1440basename(p directory and name parts of the path p. See also split.
1441)
1442exists(p) True if string p is an existing path (file or directory)
1443expanduser Returns string that is (a copy of) p with "~" expansion done.
1444(p)
1445expandvars Returns string that is (a copy of) p with environment vars expanded.
1446(p) [Windows: case significant; must use Unix: $var notation, not %var%]
1447getsize( return the size in bytes of filename. raise os.error.
1448filename)
1449getmtime( return last modification time of filename (integer nb of seconds
1450filename) since epoch).
1451getatime( return last access time of filename (integer nb of seconds since
1452filename) epoch).
1453isabs(p) True if string p is an absolute path.
1454isdir(p) True if string p is a directory.
1455islink(p) True if string p is a symbolic link.
1456ismount(p) True if string p is a mount point [true for all dirs on Windows].
1457join(p[,q Joins one or more path components intelligently.
1458[,...]])
1459 Splits p into (head, tail) where tail is lastpathname component and
1460split(p) <head> is everything leadingup to that. <=> (dirname(p), basename
1461 (p))
1462splitdrive Splits path p in a pair ('drive:', tail) [Windows]
1463(p)
1464splitext(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
1468walk(p, (including p itself if it's a dir)The argument dirname specifies the
1469visit, 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
1472 parts of the tree.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001473
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001474
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001475
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001476 shutil
1477high-level file operations (copying, deleting).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001478
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001479 Main shutil functions
1480 Function Result
1481copy(src, dst) Copies the contents of file src to file dst, retaining file
1482 permissions.
1483copytree(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.
1486rmtree(path[, Deletes an entire directory tree, ignoring errors if
1487ignore_errors[, ignore_errors true,or calling onerror(func, path,
1488onerror]]) sys.exc_info()) if supplied with
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001489
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001490(and also: copyfile, copymode, copystat, copy2)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001491
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001492time
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001493
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001494 Variables
1495Variable Meaning
1496altzone signed offset of local DST timezone in sec west of the 0th meridian.
1497daylight nonzero if a DST timezone is specified
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001498
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001499 Functions
1500 Function Result
1501time() return a float representing UTC time in seconds since the epoch.
1502gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day
1503localtime( (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is
1504secs) monday), Julian day(1-366), daylight flag(-1,0 or 1))
1505asctime(
1506timeTuple),
1507strftime(
1508format, return a formated string representing time.
1509timeTuple)
1510mktime(tuple) inverse of localtime(). Return a float.
1511strptime( parse a formated string representing time, return tuple as in
1512string[, gmtime().
1513format])
1514sleep(secs) Suspend execution for <secs> seconds. <secs> can be a float.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001515
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001516and also: clock, ctime.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001517
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001518 string
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001519
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001520As of Python 2.0, much (though not all) of the functionality provided by the
1521string module have been superseded by built-in string methods - see Operations
1522on strings for details.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001523
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001524 Some string variables
1525 Variable Meaning
1526digits The string '0123456789'
1527hexdigits, octdigits legal hexadecimal & octal digits
1528letters, uppercase, lowercase, Strings containing the appropriate
1529whitespace characters
1530index_error Exception raised by index() if substr not
1531 found.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001532
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001533 Some string functions
1534 Function Result
1535expandtabs(s, returns a copy of string <s> with tabs expanded.
1536tabSize)
1537find/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
15390]) [start:end]. Return -1 if <sub> not found.
1540ljust/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
1542 nevertruncated.
1543lower/upper(s) Return a string that is (a copy of) <s> in lowercase/
1544 uppercase
1545split(s[, sep= Return a list containing the words of the string <s>,using
1546whitespace[, the string <sep> as a separator.
1547maxsplit=0]])
1548join(words[, sep=' Concatenate a list or tuple of words with
1549']) interveningseparators; inverse of split.
1550replace(s, old, Returns a copy of string <s> with all occurences of
1551new[, maxsplit=0] substring<old> replaced by <new>. Limits to <maxsplit>
1552 firstsubstitutions if specified.
1553strip(s) Return a string that is (a copy of) <s> without leadingand
1554 trailing whitespace. see also lstrip, rstrip.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001555
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001556
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001557
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001558 re (sre)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001559
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001560Handles Unicode strings. Implemented in new module sre, re now a mere front-end
1561for compatibility.
1562Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to
1563litteralize backslashes.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001564
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001565
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001566 Regular expression syntax
1567 Form Description
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
1578 \w \S)
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
1582 pattern string.
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
1590 'Asimov'.
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.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001598
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001599 Special sequences
1600Sequence Description
1601number matches content of the group of the same number; groups are numbered
1602 starting from 1
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
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001613
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001614 Variables
1615Variable Meaning
1616error Exception when pattern string isn't a valid regexp.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001617
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001618 Functions
1619 Function Result
1620 Compile a RE pattern string into a regular expression object.
1621 Flags (combinable by |):
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001622
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001623 I or IGNORECASE or (?i)
1624 case insensitive matching
1625compile( L or LOCALE or (?L)
1626pattern[, make \w, \W, \b, \B dependent on thecurrent locale
1627flags=0]) M or MULTILINE or (?m)
1628 matches every new line and not onlystart/end of the whole
1629 string
1630 S or DOTALL or (?s)
1631 '.' matches ALL chars, including newline
1632 X or VERBOSE or (?x)
1633 Ignores whitespace outside character sets
1634escape(string) return (a copy of) string with all non-alphanumerics
1635 backslashed.
1636match(pattern, if 0 or more chars at beginning of <string> match the RE pattern
1637string[, flags string,return a corresponding MatchObject instance, or None if
1638]) no match.
1639search(pattern scan thru <string> for a location matching <pattern>, return
1640, string[, acorresponding MatchObject instance, or None if no match.
1641flags])
1642split(pattern, split <string> by occurrences of <pattern>. If capturing () are
1643string[, used inpattern, then occurrences of patterns or subpatterns are
1644maxsplit=0]) also returned.
1645findall( return a list of non-overlapping matches in <pattern>, either a
1646pattern, list ofgroups or a list of tuples if the pattern has more than 1
1647string) group.
1648 return string obtained by replacing the (<count> first) lefmost
1649sub(pattern, non-overlapping occurrences of <pattern> (a string or a RE
1650repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct
1651count=0]) called with a single MatchObj arg, which must return the
1652 replacement string.
1653subn(pattern,
1654repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade)
1655count=0])
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001656
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001657Regular Expression Objects
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001658
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001659
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001660(RE objects are returned by the compile fct)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001661
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001662 re object attributes
1663Attribute Descrition
1664flags flags arg used when RE obj was compiled, or 0 if none provided
1665groupindex dictionary of {group name: group number} in pattern
1666pattern pattern string from which RE obj was compiled
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001667
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001668 re object methods
1669 Method Result
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
1675match( where the search is to start; it defaults to 0. This is not
1676string[, completely equivalent to slicing the string; the '' pattern
1677pos][, character matches at the real beginning of the string and at
1678endpos]) 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
1683 match.
1684 Scan through string looking for a location where this regular
1685search( expression produces a match, and return a corresponding MatchObject
1686string[, instance. Return None if no position in the string matches the
1687pos][, pattern; note that this is different from finding a zero-length
1688endpos]) match at some point in the string.
1689 The optional pos and endpos parameters have the same meaning as for
1690 the match() method.
1691split(
1692string[, Identical to the split() function, using the compiled pattern.
1693maxsplit=
16940])
1695findall( Identical to the findall() function, using the compiled pattern.
1696string)
1697sub(repl,
1698string[, Identical to the sub() function, using the compiled pattern.
1699count=0])
1700subn(repl,
1701string[, Identical to the subn() function, using the compiled pattern.
1702count=0])
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001703
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001704Match Objects
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001705
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001706
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001707(Match objects are returned by the match & search functions)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001708
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001709 Match object attributes
1710Attribute Description
1711pos value of pos passed to search or match functions; index intostring at
1712 which RE engine started search.
1713endpos value of endpos passed to search or match functions; index intostring
1714 beyond which RE engine won't go.
1715re RE object whose match or search fct produced this MatchObj instance
1716string string passed to match() or search()
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001717
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001718 Match object functions
1719Function Result
1720 returns one or more groups of the match. If one arg, result is a
1721group([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
1726groups() participatingto the match have a value of None. Returns a string
1727 instead of tupleif len(tuple)=1
1728start(
1729group), returns indices of start & end of substring matched by group (or
1730end(group Noneif group exists but doesn't contribute to the match)
1731)
1732span( returns the 2-tuple (start(group), end(group)); can be (None, None)if
1733group) group didn't contibute to the match.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001734
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001735
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001736
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001737 math
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001738
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001739Variables:
1740pi
1741e
1742Functions (see ordinary C man pages for info):
1743acos(x)
1744asin(x)
1745atan(x)
1746atan2(x, y)
1747ceil(x)
1748cos(x)
1749cosh(x)
1750exp(x)
1751fabs(x)
1752floor(x)
1753fmod(x, y)
1754frexp(x) -- Unlike C: (float, int) = frexp(float)
1755ldexp(x, y)
1756log(x)
1757log10(x)
1758modf(x) -- Unlike C: (float, float) = modf(float)
1759pow(x, y)
1760sin(x)
1761sinh(x)
1762sqrt(x)
1763tan(x)
1764tanh(x)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001765
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001766 getopt
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001767
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001768Functions:
1769getopt(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:')
1774 # opts would be
1775 [('-c', 'hi'), ('-a', '')]
1776 # args would be
1777 ['arg1', 'arg2']
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001778
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001779
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001780List of modules and packages in base distribution
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001781
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001782(built-ins and content of python Lib directory)
1783(Python NT distribution, may be slightly different in other distributions)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001784
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001785 Standard library modules
1786 Operation Result
1787aifc Stuff to parse AIFF-C and AIFF files.
1788anydbm Generic interface to all dbm clones. (dbhash, gdbm,
1789 dbm,dumbdbm)
1790asynchat Support for 'chat' style protocols
1791asyncore Asynchronous File I/O (in select style)
1792atexit Register functions to be called at exit of Python interpreter.
1793audiodev Audio support for a few platforms.
1794base64 Conversions to/from base64 RFC-MIME transport encoding .
1795BaseHTTPServer Base class forhttp services.
1796Bastion "Bastionification" utility (control access to instance vars)
1797bdb A generic Python debugger base class.
1798binhex Macintosh binhex compression/decompression.
1799bisect List bisection algorithms.
1800calendar Calendar printing functions.
1801cgi Wraps the WWW Forms Common Gateway Interface (CGI).
1802CGIHTTPServer CGI http services.
1803cmd 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]
1806DEL]
1807code Utilities needed to emulate Python's interactive interpreter
1808codecs Lookup existing Unicode encodings and register new ones.
1809colorsys Conversion functions between RGB and other color systems.
1810commands Tools for executing UNIX commands .
1811compileall Force "compilation" of all .py files in a directory.
1812ConfigParser Configuration file parser (much like windows .ini files)
1813copy Generic shallow and deep copying operations.
1814copy_reg Helper to provide extensibility for pickle/cPickle.
1815dbhash (g)dbm-compatible interface to bsdhash.hashopen.
1816dircache 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]
1818dis Bytecode disassembler.
1819distutils Package installation system.
1820dospath Common operations on DOS pathnames.
1821dumbdbm A dumb and slow but simple dbm clone.
1822[DEL:dump:DEL] [DEL:Print python code that reconstructs a variable.:DEL]
1823exceptions Class based built-in exception hierarchy.
1824filecmp File comparison.
1825fileinput Helper class to quickly write a loop over all standard input
1826 files.
1827[DEL:find:DEL] [DEL:Find files directory hierarchy matching a pattern.:DEL]
1828fnmatch Filename matching with shell patterns.
1829formatter A test formatter.
1830fpformat General floating point formatting functions.
1831ftplib An FTP client class. Based on RFC 959.
1832gc Perform garbacge collection, obtain GC debug stats, and tune
1833 GC parameters.
1834getopt Standard command line processing. See also ftp://
1835 www.pauahtun.org/pub/getargspy.zip
1836getpass Utilities to get a password and/or the current user name.
1837glob filename globbing.
1838gopherlib Gopher protocol client interface.
1839[DEL:grep:DEL] [DEL:'grep' utilities.:DEL]
1840gzip Read & write gzipped files.
1841htmlentitydefs Proposed entity definitions for HTML.
1842htmllib HTML parsing utilities.
1843httplib HTTP client class.
1844ihooks Hooks into the "import" mechanism.
1845imaplib IMAP4 client.Based on RFC 2060.
1846imghdr Recognizing image files based on their first few bytes.
1847imputil Privides a way of writing customised import hooks.
1848keyword List of Python keywords.
1849knee A Python re-implementation of hierarchical module import.
1850linecache Cache lines from files.
1851linuxaudiodev Lunix /dev/audio support.
1852locale Support for number formatting using the current locale
1853 settings.
1854macpath Pathname (or related) operations for the Macintosh.
1855macurl2path Mac specific module for conversion between pathnames and URLs.
1856mailbox A class to handle a unix-style or mmdf-style mailbox.
1857mailcap Mailcap file handling (RFC 1524).
1858mhlib MH (mailbox) interface.
1859mimetools Various tools used by MIME-reading or MIME-writing programs.
1860mimetypes Guess the MIME type of a file.
1861MimeWriter Generic MIME writer.
1862mimify Mimification and unmimification of mail messages.
1863mmap Interface to memory-mapped files - they behave like mutable
1864 strings./font>
1865multifile Class to make multi-file messages easier to handle.
1866mutex Mutual exclusion -- for use with module sched.
1867netrc
1868nntplib An NNTP client class. Based on RFC 977.
1869ntpath Common operations on DOS pathnames.
1870nturl2path Mac specific module for conversion between pathnames and URLs.
1871os Either mac, dos or posix depending system.
1872[DEL:packmail: [DEL:Create a self-unpacking shell archive.:DEL]
1873DEL]
1874pdb A Python debugger.
1875pickle Pickling (save and restore) of Python objects (a faster
1876 Cimplementation exists in built-in module: cPickle).
1877pipes Conversion pipeline templates.
1878[DEL:poly:DEL] [DEL:Polynomials.:DEL]
1879popen2 variations on pipe open.
1880poplib A POP3 client class. Based on the J. Myers POP3 draft.
1881posixfile Extended (posix) file operations.
1882posixpath Common operations on POSIX pathnames.
1883pprint Support to pretty-print lists, tuples, & dictionaries
1884 recursively.
1885profile Class for profiling python code.
1886pstats Class for printing reports on profiled python code.
1887pty Pseudo terminal utilities.
1888pyexpat Interface to the Expay XML parser.
1889py_compile Routine to "compile" a .py file to a .pyc file.
1890pyclbr Parse a Python file and retrieve classes and methods.
1891Queue A multi-producer, multi-consumer queue.
1892quopri Conversions to/from quoted-printable transport encoding.
1893rand Don't use unless you want compatibility with C's rand().
1894random Random variable generators (obsolete, use whrandom)
1895re Regular Expressions.
1896reconvert Convert old ("regex") regular expressions to new syntax
1897 ("re").
1898regex_syntax Flags for regex.set_syntax().
1899regexp Backward compatibility for module "regexp" using "regex".
1900regsub Regular expression subroutines.
1901repr Redo repr() but with limits on most sizes.
1902rexec Restricted execution facilities ("safe" exec, eval, etc).
1903rfc822 RFC-822 message manipulation class.
1904rlcompleter Word completion for GNU readline 2.0.
1905robotparser Parse robot.txt files, useful for web spiders.
1906sched A generally useful event scheduler class.
1907sgmllib A parser for SGML.
1908shelve Manage shelves of pickled objects.
1909shlex Lexical analyzer class for simple shell-like syntaxes.
1910shutil Utility functions usable in a shell-like program.
1911SimpleHTTPServer Simple extension to base http class
1912site Append module search paths for third-party packages to
1913 sys.path.
1914smtplib SMTP Client class (RFC 821)
1915sndhdr Several routines that help recognizing sound.
1916SocketServer Generic socket server classes.
1917stat Constants and functions for interpreting stat/lstat struct.
1918statcache Maintain a cache of file stats.
1919statvfs Constants for interpreting statvfs struct as returned by
1920 os.statvfs()and os.fstatvfs() (if they exist).
1921string A collection of string operations.
1922StringIO File-like objects that read/write a string buffer (a fasterC
1923 implementation exists in built-in module: cStringIO).
1924sunau Stuff to parse Sun and NeXT audio files.
1925sunaudio Interpret sun audio headers.
1926symbol Non-terminal symbols of Python grammar (from "graminit.h").
1927tabnanny,/font> Check Python source for ambiguous indentation.
1928telnetlib TELNET client class. Based on RFC 854.
1929tempfile Temporary file name allocation.
1930threading Proposed new higher-level threading interfaces
1931threading_api (doc of the threading module)
1932toaiff Convert "arbitrary" sound files to AIFF files .
1933token Tokens (from "token.h").
1934tokenize Compiles a regular expression that recognizes Python tokens.
1935traceback Format and print Python stack traces.
1936tty Terminal utilities.
1937turtle LogoMation-like turtle graphics
1938types Define names for all type symbols in the std interpreter.
1939tzparse Parse a timezone specification.
1940unicodedata Interface to unicode properties.
1941urllib Open an arbitrary URL.
1942urlparse Parse URLs according to latest draft of standard.
1943user Hook to allow user-specified customization code to run.
1944UserDict A wrapper to allow subclassing of built-in dict class.
1945UserList A wrapper to allow subclassing of built-in list class.
1946UserString A wrapper to allow subclassing of built-in string class.
1947[DEL:util:DEL] [DEL:some useful functions that don't fit elsewhere !!:DEL]
1948uu UUencode/UUdecode.
1949wave Stuff to parse WAVE files.
1950webbrowser Platform independent URL launcher.
1951[DEL:whatsound: [DEL:Several routines that help recognizing sound files.:DEL]
1952DEL]
1953whichdb Guess which db package to use to open a db file.
1954whrandom Wichmann-Hill random number generator.
1955xdrlib Implements (a subset of) Sun XDR (eXternal Data
1956 Representation)
1957xmllib A parser for XML, using the derived class as static DTD.
1958xml.dom Classes for processing XML using the Document Object Model.
1959xml.sax Classes for processing XML using the SAX API.
1960zipfile Read & write PK zipped files.
1961[DEL:zmod:DEL] [DEL:Demonstration of abstruse mathematical concepts.:DEL]
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001962
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001963
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001964
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001965(following list not revised)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001966
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001967* Built-ins *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001968
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001969 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
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001978
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001979* Standard *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001980
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001981 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.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001988
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001989* Unix/Posix *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001990
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001991 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
Guido van Rossumc8180cc1994-08-05 15:57:31 +00001998
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00001999* Tk User-interface Toolkit *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002000
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002001 tkinter Main interface to Tk
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002002
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002003* Multimedia *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002004
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002005 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
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002009
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002010* Cryptographic Extensions *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002011
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002012 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
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002015
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002016* Stdwin * Standard Window System
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002017
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002018 stdwin Standard Window System interface
2019 stdwinevents Stdwin event, command, and selection constants
2020 rect Rectangle manipulation operations
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002021
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002022* SGI IRIX * (4 & 5)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002023
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002024 al SGI audio facilities
2025 AL al constants
2026 fl Interface to FORMS library
2027 FL fl constants
2028 flp Functions for form designer
2029 fm Access to font manager library
2030 gl Access to graphics library
2031 GL Constants for gl
2032 DEVICE More constants for gl
2033 imgfile Imglib image file interface
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002034
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002035* Suns *
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002036
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002037 sunaudiodev Access to sun audio interface
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002038
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002039
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002040Workspace exploration and idiom hints
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002041
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002042 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
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002050
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002051
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002052
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002053
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002054
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002055
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002056
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002057Python Mode for Emacs
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002058
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002059(Not revised, possibly not up to date)
2060Type C-c ? when in python-mode for extensive help.
2061INDENTATION
2062Primarily for entering new code:
2063 TAB indent line appropriately
2064 LFD insert newline, then indent
2065 DEL reduce indentation, or delete single character
2066Primarily 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
2072MARKING & MANIPULATING REGIONS OF CODE
2073C-c C-b mark block of lines
2074M-C-h mark smallest enclosing def
2075C-u M-C-h mark smallest enclosing class
2076C-c # comment out region of code
2077C-u C-c # uncomment region of code
2078MOVING POINT
2079C-c C-p move to statement preceding point
2080C-c C-n move to statement following point
2081C-c C-u move up to start of current block
2082M-C-a move to start of def
2083C-u M-C-a move to start of class
2084M-C-e move to end of def
2085C-u M-C-e move to end of class
2086EXECUTING PYTHON CODE
2087C-c C-c sends the entire buffer to the Python interpreter
2088C-c | sends the current region
2089C-c ! starts a Python interpreter window; this will be used by
2090 subsequent C-c C-c or C-c | commands
2091VARIABLES
2092py-indent-offset indentation increment
2093py-block-comment-prefix comment string used by py-comment-region
2094py-python-command shell command to invoke Python interpreter
2095py-scroll-process-buffer t means always scroll Python process buffer
2096py-temp-directory directory used for temp files (if needed)
2097py-beep-if-tab-change ring the bell if tab-width is changed
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002098
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002099
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002100The Python Debugger
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002101
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002102(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)
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002103
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002104Accessing
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002105
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002106import 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)
2116 post_mortem(t)
2117 -- run postmortem on traceback object <t>
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002118
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002119 -- defines class Pdb :
2120 use Pdb to create reusable debugger objects. Object
2121 preserves state (i.e. break points) between calls.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002122
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002123 runs until a breakpoint hit, exception, or end of program
2124 If exception, variable '__exception__' holds (exception,value).
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002125
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002126Commands
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002127
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002128h, help
2129 brief reminder of commands
2130b, break [<arg>]
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
2134cl, clear [<arg>]
2135 if <arg> numeric, clear breakpoint at <arg> in current file
2136 if no arg, clear all breakpoints after confirmation
2137w, where
2138 print current call stack
2139u, up
2140 move up one stack frame (to top-level caller)
2141d, down
2142 move down one stack frame
2143s, step
2144 advance one line in the program, stepping into calls
2145n, next
2146 advance one line, stepping over calls
2147r, return
2148 continue execution until current function returns
2149 (return value is saved in variable "__return__", which
2150 can be printed or manipulated from debugger)
2151c, continue
2152 continue until next breakpoint
2153a, args
2154 print args to current function
2155rv, retval
2156 prints return value from last function that returned
2157p, print <arg>
2158 prints value of <arg> in current stack frame
2159l, 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.
2166whatis <arg>
2167 prints type of <arg>
2168!
2169 executes rest of line as a Python statement in the current stack frame
2170q quit
2171 immediately stop execution and leave debugger
2172<return>
2173 executes last command again
2174Any input debugger doesn't recognize as a command is assumed to be a
2175Python statement to execute in the current stack frame, the same way
2176the exclamation mark ("!") command does.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002177
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002178Example
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002179
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002180(1394) python
2181Python 1.0.3 (Sep 26 1994)
2182Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
2183>>> import rm
2184>>> rm.run()
2185Traceback (innermost last):
2186 File "<stdin>", line 1
2187 File "./rm.py", line 7
2188 x = div(3)
2189 File "./rm.py", line 2
2190 return a / r
2191ZeroDivisionError: integer division or modulo
2192>>> import pdb
2193>>> pdb.pm()
2194> ./rm.py(2)div: return a / r
2195(Pdb) list
2196 1 def div(a):
2197 2 -> return a / r
2198 3
2199 4 def run():
2200 5 global r
2201 6 r = 0
2202 7 x = div(3)
2203 8 print x
2204[EOF]
2205(Pdb) print r
22060
2207(Pdb) q
2208>>> pdb.runcall(rm.run)
2209etc.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002210
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002211Quirks
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002212
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002213Breakpoints are stored as filename, line number tuples. If a module is reloaded
2214after editing, any remembered breakpoints are likely to be wrong.
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002215
Andrew M. Kuchling13423f32001-08-06 17:43:49 +00002216Always single-steps through top-most stack frame. That is, "c" acts like "n".
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002217
Guido van Rossumc8180cc1994-08-05 15:57:31 +00002218