Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1 | Python 2.0 Quick Reference |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 3 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 4 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 5 | 16 May 2001 upgraded by Richard Gruet and Simon Brunning for Python 2.0 |
| 6 | 2000/07/18 upgraded by Richard Gruet, rgruet@intraware.com for Python 1.5.2 |
| 7 | from V1.3 ref |
| 8 | 1995/10/30, by Chris Hoffmann, choffman@vicorp.com |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 9 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 10 | Based 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 | |
| 18 | Python's nest: http://www.python.org Developement: http:// |
| 19 | python.sourceforge.net/ ActivePython : http://www.ActiveState.com/ASPN/ |
| 20 | Python/ |
| 21 | newsgroup: comp.lang.python Help desk: help@python.org |
| 22 | Resources: http://starship.python.net/ and http://www.vex.net/parnassus/ |
| 23 | Full documentation: http://www.python.org/doc/ |
| 24 | An excellent Python reference book: Python Essential Reference by David Beazley |
| 25 | (New Riders) |
| 26 | |
| 27 | |
| 28 | Contents |
| 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 | |
| 50 | Invocation Options |
| 51 | |
| 52 | python [-diOStuUvxX?] [-c command | script | - ] [args] |
| 53 | |
| 54 | Invocation Options |
| 55 | Option 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 |
| 70 | command option list (following options are passed as arguments to the command). |
| 71 | the name of a python file (.py) to execute read from stdin. |
| 72 | script Anything afterward is passed as options to python script or command, |
| 73 | not interpreted as an option to interpreter itself. |
| 74 | args passed to script or command (in sys.argv[1:]) |
| 75 | If no script or command, Python enters interactive mode. |
| 76 | |
| 77 | * Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin |
| 78 | (Windows). |
| 79 | |
| 80 | |
| 81 | |
| 82 | Environment variables |
| 83 | |
| 84 | Environment variables |
| 85 | Variable Effect |
| 86 | PYTHONHOME Alternate prefix directory (or prefix;exec_prefix). The |
| 87 | default module search path uses prefix/lib |
| 88 | Augments the default search path for module files. The format |
| 89 | is the same as the shell's $PATH: one or more directory |
| 90 | pathnames separated by ':' or ';' without spaces around |
| 91 | (semi-)colons! |
| 92 | PYTHONPATH On Windows first search for Registry key HKEY_LOCAL_MACHINE\ |
| 93 | Software\Python\PythonCore\x.y\PythonPath (default value). You |
| 94 | may also define a key named after your application with a |
| 95 | default string value giving the root directory path of your |
| 96 | app. |
| 97 | If this is the name of a readable file, the Python commands in |
| 98 | PYTHONSTARTUP that file are executed before the first prompt is displayed in |
| 99 | interactive mode (no default). |
| 100 | PYTHONDEBUG If non-empty, same as -d option |
| 101 | PYTHONINSPECT If non-empty, same as -i option |
| 102 | PYTHONSUPPRESS If non-empty, same as -s option |
| 103 | PYTHONUNBUFFERED If non-empty, same as -u option |
| 104 | PYTHONVERBOSE If non-empty, same as -v option |
| 105 | PYTHONCASEOK If non-empty, ignore case in file/module names (imports) |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | Notable lexical entities |
| 111 | |
| 112 | Keywords |
| 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 | |
| 131 | Identifiers |
| 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 | |
| 140 | Strings |
| 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 Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 157 | |
| 158 | String Literal Escapes |
| 159 | |
| 160 | \newline Ignored (escape newline) |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 161 | \\ Backslash (\) \e Escape (ESC) \v Vertical Tab (VT) |
| 162 | \' Single quote (') \f Formfeed (FF) \OOO char with octal value OOO |
| 163 | \" Double quote (") \n Linefeed (LF) |
| 164 | \a Bell (BEL) \r Carriage Return (CR) \xHH char with hex value HH |
| 165 | \b Backspace (BS) \t Horizontal Tab (TAB) |
| 166 | \uHHHH unicode char with hex value HHHH, can only be used in unicode string |
| 167 | \UHHHHHHHH unicode char with hex value HHHHHHHH, can only be used in unicode string |
| 168 | \AnyOtherChar is left as-is |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 169 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 170 | * 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 Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 173 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 174 | Numbers |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 175 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 176 | Decimal integer: 1234, 1234567890546378940L (or l) |
| 177 | Octal integer: 0177, 0177777777777777777L (begin with a 0) |
| 178 | Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFFL (begin with 0x or 0X) |
| 179 | Long integer (unlimited precision): 1234567890123456L (ends with L or l) |
| 180 | Float (double precision): 3.14e-10, .001, 10., 1E3 |
| 181 | Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and |
| 182 | imaginary parts) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 183 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 184 | Sequences |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 185 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 186 | * String of length 0, 1, 2 (see above) |
| 187 | '', '1', "12", 'hello\n' |
| 188 | * Tuple of length 0, 1, 2, etc: |
| 189 | () (1,) (1,2) # parentheses are optional if len > 0 |
| 190 | * List of length 0, 1, 2, etc: |
| 191 | [] [1] [1,2] |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 192 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 193 | Indexing is 0-based. Negative indices (usually) mean count backwards from end |
| 194 | of sequence. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 195 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 196 | Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to |
| 197 | '0'; End defaults to 'sequence-length'. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 198 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 199 | a = (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 Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 206 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 207 | Dictionaries (Mappings) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 208 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 209 | Dictionary of length 0, 1, 2, etc: |
| 210 | {} {1 : 'first'} {1 : 'first', 'next': 'second'} |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 211 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 212 | Operators and their evaluation order |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 213 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 214 | Operators and their evaluation order |
| 215 | Highest 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 |
| 235 | Lowest lambda args: expr anonymous function |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 236 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 237 | Alternate names are defined in module operator (e.g. __add__ and add for +) |
| 238 | Most operators are overridable |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 239 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 240 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 241 | Basic Types and Their Operations |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 242 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 243 | Comparisons (defined between *any* types) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 244 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 245 | Comparisons |
| 246 | Comparison Meaning Notes |
| 247 | < strictly less than (1) |
| 248 | <= less than or equal to |
| 249 | > strictly greater than |
| 250 | >= greater than or equal to |
| 251 | == equal to |
| 252 | != or <> not equal to |
| 253 | is object identity (2) |
| 254 | is not negated object identity (2) |
| 255 | |
| 256 | Notes : |
| 257 | Comparison behavior can be overridden for a given class by defining special |
| 258 | method __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 | |
| 262 | Boolean values and operators |
| 263 | |
| 264 | Boolean values and operators |
| 265 | Value or Operator Returns Notes |
| 266 | None, numeric zeros, empty sequences and False |
| 267 | mappings |
| 268 | all other values True |
| 269 | not x True if x is False, else |
| 270 | True |
| 271 | x or y if x is False then y, else (1) |
| 272 | x |
| 273 | x and y if x is False then x, else (1) |
| 274 | y |
| 275 | |
| 276 | Notes : |
| 277 | Truth testing behavior can be overridden for a given class by defining |
| 278 | special method __nonzero__. |
| 279 | (1) Evaluate second arg only if necessary to determine outcome. |
| 280 | |
| 281 | None |
| 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 | |
| 288 | Numeric types |
| 289 | |
| 290 | Floats, 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 | |
| 296 | Operators on all numeric types |
| 297 | |
| 298 | Operators on all numeric types |
| 299 | Operation Result |
| 300 | abs(x) the absolute value of x |
| 301 | int(x) x converted to integer |
| 302 | long(x) x converted to long integer |
| 303 | float(x) x converted to floating point |
| 304 | -x x negated |
| 305 | +x x unchanged |
| 306 | x + y the sum of x and y |
| 307 | x - y difference of x and y |
| 308 | x * y product of x and y |
| 309 | x / y quotient of x and y |
| 310 | x % y remainder of x / y |
| 311 | divmod(x, y) the tuple (x/y, x%y) |
| 312 | x ** y x to the power y (the same as pow(x, y)) |
| 313 | |
| 314 | Bit operators on integers and long integers |
| 315 | |
| 316 | Bit operators |
| 317 | Operation >Result |
| 318 | ~x the bits of x inverted |
| 319 | x ^ y bitwise exclusive or of x and y |
| 320 | x & y bitwise and of x and y |
| 321 | x | y bitwise or of x and y |
| 322 | x << n x shifted left by n bits |
| 323 | x >> n x shifted right by n bits |
| 324 | |
| 325 | Complex 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 | |
| 332 | Numeric exceptions |
| 333 | |
| 334 | TypeError |
| 335 | raised on application of arithmetic operation to non-number |
| 336 | OverflowError |
| 337 | numeric bounds exceeded |
| 338 | ZeroDivisionError |
| 339 | raised when zero second argument of div or modulo op |
| 340 | |
| 341 | Operations on all sequence types (lists, tuples, strings) |
| 342 | |
| 343 | Operations on all sequence types |
| 344 | Operation Result Notes |
| 345 | x in s 1 if an item of s is equal to x, else 0 |
| 346 | x not in s 0 if an item of s is equal to x, else 1 |
| 347 | s + t the concatenation of s and t |
| 348 | s * n, n*s n copies of s concatenated |
| 349 | s[i] i'th item of s, origin 0 (1) |
| 350 | s[i:j] slice of s from i (included) to j (excluded) (1), (2) |
| 351 | len(s) length of s |
| 352 | min(s) smallest item of s |
| 353 | max(s) largest item of (s) |
| 354 | |
| 355 | Notes : |
| 356 | (1) if i or j is negative, the index is relative to the end of the string, |
| 357 | ie len(s)+ i or len(s)+j is |
| 358 | substituted. But note that -0 is still 0. |
| 359 | (2) The slice of s from i to j is defined as the sequence of items with |
| 360 | index k such that i <= k < j. |
| 361 | If i or j is greater than len(s), use len(s). If i is omitted, use |
| 362 | len(s). If i is greater than or |
| 363 | equal to j, the slice is empty. |
| 364 | |
| 365 | Operations on mutable (=modifiable) sequences (lists) |
| 366 | |
| 367 | Operations on mutable sequences |
| 368 | Operation Result Notes |
| 369 | s[i] =x item i of s is replaced by x |
| 370 | s[i:j] = t slice of s from i to j is replaced by t |
| 371 | del s[i:j] same as s[i:j] = [] |
| 372 | s.append(x) same as s[len(s) : len(s)] = [x] |
| 373 | s.extend(x) same as s[len(s):len(s)]= x (5) |
| 374 | s.count(x) return number of i's for which s[i] == x |
| 375 | s.index(x) return smallest i such that s[i] == x (1) |
| 376 | s.insert(i, x) same as s[i:i] = [x] if i >= 0 |
| 377 | s.remove(x) same as del s[s.index(x)] (1) |
| 378 | s.pop([i]) same as x = s[i]; del s[i]; return x (4) |
| 379 | s.reverse() reverse the items of s in place (3) |
| 380 | s.sort([cmpFct]) sort the items of s in place (2), (3) |
| 381 | |
| 382 | Notes : |
| 383 | (1) raise a ValueError exception when x is not found in s (i.e. out of |
| 384 | range). |
| 385 | (2) The sort() method takes an optional argument specifying a comparison |
| 386 | fct of 2 arguments (list items) which should |
| 387 | return -1, 0, or 1 depending on whether the 1st argument is |
| 388 | considered smaller than, equal to, or larger than the 2nd |
| 389 | argument. Note that this slows the sorting process down considerably. |
| 390 | (3) The sort() and reverse() methods modify the list in place for economy |
| 391 | of space when sorting or reversing a large list. |
| 392 | They don't return the sorted or reversed list to remind you of this |
| 393 | side effect. |
| 394 | (4) [New 1.5.2] The pop() method is experimental and not supported by |
| 395 | other mutable sequence types than lists. |
| 396 | The optional argument i defaults to -1, so that by default the last |
| 397 | item is removed and returned. |
| 398 | (5) [New 1.5.2] Experimental ! Raises an exception when x is not a list |
| 399 | object. |
| 400 | |
| 401 | |
| 402 | |
| 403 | Operations on mappings (dictionaries) |
| 404 | |
| 405 | Operations on mappings |
| 406 | Operation Result Notes |
| 407 | len(d) the number of items in d |
| 408 | d[k] the item of d with key k (1) |
| 409 | d[k] = x set d[k] to x |
| 410 | del d[k] remove d[k] from d (1) |
| 411 | d.clear() remove all items from d |
| 412 | d.copy() a shallow copy of d |
| 413 | d.has_key(k) 1 if d has key k, else 0 |
| 414 | d.items() a copy of d's list of (key, item) pairs (2) |
| 415 | d.keys() a copy of d's list of keys (2) |
| 416 | d1.update(d2) for k, v in d2.items(): d1[k] = v (3) |
| 417 | d.values() a copy of d's list of values (2) |
| 418 | d.get(k,defaultval) the item of d with key k (4) |
| 419 | d.setdefault(k,defaultval) the item of d with key k (5) |
| 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 | |
| 435 | Operations on strings |
| 436 | |
| 437 | Note that these string methods largely (but not completely) supersede the |
| 438 | functions available in the string module. |
| 439 | |
| 440 | |
| 441 | Operations on strings |
| 442 | Operation Result Notes |
| 443 | s.capitalize() return a copy of s with only its first character |
| 444 | capitalized. |
| 445 | s.center(width) return a copy of s centered in a string of length width (1) |
| 446 | . |
| 447 | s.count(sub[ return the number of occurrences of substring sub in (2) |
| 448 | ,start[,end]]) string s. |
| 449 | s.encode([ return an encoded version of s. Default encoding is the |
| 450 | encoding[,errors current default string encoding. (3) |
| 451 | ]]) |
| 452 | s.endswith(suffix return true if s ends with the specified suffix, (2) |
| 453 | [,start[,end]]) otherwise return false. |
| 454 | s.expandtabs([ return a copy of s where all tab characters are (4) |
| 455 | tabsize]) expanded using spaces. |
| 456 | s.find(sub[,start return the lowest index in s where substring sub is (2) |
| 457 | [,end]]) found. Return -1 if sub is not found. |
| 458 | s.index(sub[ like find(), but raise ValueError when the substring is (2) |
| 459 | ,start[,end]]) not found. |
| 460 | s.isalnum() return true if all characters in s are alphanumeric, (5) |
| 461 | false otherwise. |
| 462 | s.isalpha() return true if all characters in s are alphabetic, (5) |
| 463 | false otherwise. |
| 464 | s.isdigit() return true if all characters in s are digit (5) |
| 465 | characters, false otherwise. |
| 466 | s.islower() return true if all characters in s are lowercase, false (6) |
| 467 | otherwise. |
| 468 | s.isspace() return true if all characters in s are whitespace (5) |
| 469 | characters, false otherwise. |
| 470 | s.istitle() return true if string s is a titlecased string, false (7) |
| 471 | otherwise. |
| 472 | s.isupper() return true if all characters in s are uppercase, false (6) |
| 473 | otherwise. |
| 474 | s.join(seq) return a concatenation of the strings in the sequence |
| 475 | seq, seperated by 's's. |
| 476 | s.ljust(width) return s left justified in a string of length width. (1), |
| 477 | (8) |
| 478 | s.lower() return a copy of s converted to lowercase. |
| 479 | s.lstrip() return a copy of s with leading whitespace removed. |
| 480 | s.replace(old, return a copy of s with all occurrences of substring (9) |
| 481 | new[, maxsplit]) old replaced by new. |
| 482 | s.rfind(sub[ return the highest index in s where substring sub is (2) |
| 483 | ,start[,end]]) found. Return -1 if sub is not found. |
| 484 | s.rindex(sub[ like rfind(), but raise ValueError when the substring (2) |
| 485 | ,start[,end]]) is not found. |
| 486 | s.rjust(width) return s right justified in a string of length width. (1), |
| 487 | (8) |
| 488 | s.rstrip() return a copy of s with trailing whitespace removed. |
| 489 | s.split([sep[ return a list of the words in s, using sep as the (10) |
| 490 | ,maxsplit]]) delimiter string. |
| 491 | s.splitlines([ return a list of the lines in s, breaking at line (11) |
| 492 | keepends]) boundaries. |
| 493 | s.startswith return true if s starts with the specified prefix, |
| 494 | (prefix[,start[ otherwise return false. (2) |
| 495 | ,end]]) |
| 496 | s.strip() return a copy of s with leading and trailing whitespace |
| 497 | removed. |
| 498 | s.swapcase() return a copy of s with uppercase characters converted |
| 499 | to lowercase and vice versa. |
| 500 | return a titlecased copy of s, i.e. words start with |
| 501 | s.title() uppercase characters, all remaining cased characters |
| 502 | are lowercase. |
| 503 | s.translate(table return a copy of s mapped through translation table (12) |
| 504 | [,deletechars]) table. |
| 505 | s.upper() return a copy of s converted to uppercase. |
| 506 | |
| 507 | Notes : |
| 508 | (1) Padding is done using spaces. |
| 509 | (2) If optional argument start is supplied, substring s[start:] is |
| 510 | processed. If optional arguments start and end are supplied, substring s[start: |
| 511 | end] is processed. |
| 512 | (3) Optional argument errors may be given to set a different error handling |
| 513 | scheme. The default for errors is 'strict', meaning that encoding errors raise |
| 514 | a ValueError. Other possible values are 'ignore' and 'replace'. |
| 515 | (4) If optional argument tabsize is not given, a tab size of 8 characters |
| 516 | is 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 |
| 519 | character. |
| 520 | (7) A titlecased string is a string in which uppercase characters may only |
| 521 | follow uncased characters and lowercase characters only cased ones. |
| 522 | (8) s is returned if width is less than len(s). |
| 523 | (9) If the optional argument maxsplit is given, only the first maxsplit |
| 524 | occurrences are replaced. |
| 525 | (10) If sep is not specified or None, any whitespace string is a separator. |
| 526 | If maxsplit is given, at most maxsplit splits are done. |
| 527 | (11) Line breaks are not included in the resulting list unless keepends is |
| 528 | given and true. |
| 529 | (12) table must be a string of length 256. All characters occurring in the |
| 530 | optional argument deletechars are removed prior to translation. |
| 531 | |
| 532 | String formatting with the % operator |
| 533 | |
| 534 | formatString % 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 |
| 552 | Conversion Meaning |
| 553 | d Signed integer decimal. |
| 554 | i Signed integer decimal. |
| 555 | o Unsigned octal. |
| 556 | u Unsigned decimal. |
| 557 | x Unsigned hexidecimal (lowercase). |
| 558 | X Unsigned hexidecimal (uppercase). |
| 559 | e Floating point exponential format (lowercase). |
| 560 | E Floating point exponential format (uppercase). |
| 561 | f Floating point decimal format. |
| 562 | F Floating point decimal format. |
| 563 | g Same as "e" if exponent is greater than -4 or less than precision, |
| 564 | "f" otherwise. |
| 565 | G Same as "E" if exponent is greater than -4 or less than precision, |
| 566 | "F" otherwise. |
| 567 | c Single character (accepts integer or single character string). |
| 568 | r String (converts any python object using repr()). |
| 569 | s String (converts any python object using str()). |
| 570 | % No argument is converted, results in a "%" character in the result. |
| 571 | (The complete specification is %%.) |
| 572 | |
| 573 | Conversion flag characters |
| 574 | Flag Meaning |
| 575 | # The value conversion will use the ``alternate form''. |
| 576 | 0 The conversion will be zero padded. |
| 577 | - The converted value is left adjusted (overrides "-"). |
| 578 | (a space) A blank should be left before a positive number (or empty |
| 579 | string) produced by a signed conversion. |
| 580 | + A sign character ("+" or "-") will precede the conversion (overrides a |
| 581 | "space" flag). |
| 582 | |
| 583 | File Objects |
| 584 | |
| 585 | Created with built-in function open; may be created by other modules' functions |
| 586 | as well. |
| 587 | |
| 588 | Operators on file objects |
| 589 | |
| 590 | File operations |
| 591 | Operation Result |
| 592 | f.close() Close file f. |
| 593 | f.fileno() Get fileno (fd) for file f. |
| 594 | f.flush() Flush file f's internal buffer. |
| 595 | f.isatty() 1 if file f is connected to a tty-like dev, else 0. |
| 596 | f.read([size]) Read at most size bytes from file f and return as a string |
| 597 | object. If size omitted, read to EOF. |
| 598 | f.readline() Read one entire line from file f. |
| 599 | f.readlines() Read until EOF with readline() and return list of lines read. |
| 600 | Set file f's position, like "stdio's fseek()". |
| 601 | f.seek(offset[, whence == 0 then use absolute indexing. |
| 602 | whence=0]) whence == 1 then offset relative to current pos. |
| 603 | whence == 2 then offset relative to file end. |
| 604 | f.tell() Return file f's current position (byte offset). |
| 605 | f.write(str) Write string to file f. |
| 606 | f.writelines(list Write list of strings to file f. |
| 607 | ) |
| 608 | |
| 609 | File 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 |
| 742 | An 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 | |
| 752 | Exception 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 |
| 763 | When an error message is printed for an unhandled exception which is a |
| 764 | class, the class name is printed, then a colon and a space, and |
| 765 | finally the instance converted to a string using the built-in function |
| 766 | str(). |
| 767 | All built-in exception classes derives from StandardError, itself |
| 768 | derived from Exception. |
| 769 | |
| 770 | Name Space Statements |
| 771 | |
| 772 | [1.51: On Mac & Windows, the case of module file names must now match the case |
| 773 | as used |
| 774 | in the import statement] |
| 775 | Packages (>1.5): a package is a name space which maps to a directory including |
| 776 | module(s) and the special initialization module '__init__.py' |
| 777 | (possibly empty). Packages/dirs can be nested. You address a |
| 778 | module's symbol via '[package.[package...]module.symbol's. |
| 779 | import module1 [as name1] [, module2]* |
| 780 | -- imports modules. Members of module must be |
| 781 | referred to by qualifying with [package.]module name: |
| 782 | "import sys; print sys.argv:" |
| 783 | "import package1.subpackage.module; package1.subpackage.module.foo()" |
| 784 | module1 renamed as name1, if supplied. |
| 785 | from module import name1 [as othername1] [, name2]* |
| 786 | -- imports names from module module in current namespace. |
| 787 | "from sys import argv; print argv" |
| 788 | "from package1 import module; module.foo()" |
| 789 | "from package1.module import foo; foo()" |
| 790 | name1 renamed as othername1, if supplied. |
| 791 | from 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! |
| 799 | global name1 [, name2]* |
| 800 | -- names are from global scope (usually meaning from module) |
| 801 | rather than local (usually meaning only in function). |
| 802 | -- E.g. in fct without "global" statements, assuming |
| 803 | "a" is name that hasn't been used in fct or module |
| 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 | |
| 813 | Function Definition |
| 814 | |
| 815 | def 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 | |
| 824 | Example: |
| 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 | |
| 833 | Class Definition |
| 834 | |
| 835 | class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite> |
| 836 | -- Creates a class object and assigns it name <class_id> |
| 837 | <suite> may contain local "defs" of class methods and |
| 838 | assignments to class attributes. |
| 839 | Example: |
| 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. |
| 853 | Example: |
| 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 | |
| 869 | Documentation Strings |
| 870 | |
| 871 | Modules, classes and functions may be documented by placing a string literal by |
| 872 | itself as the first statement in the suite. The documentation can be retrieved |
| 873 | by getting the '__doc__' attribute from the module, class or function. |
| 874 | Example: |
| 875 | class C: |
| 876 | "A description of C" |
| 877 | def __init__(self): |
| 878 | "A description of the constructor" |
| 879 | # etc. |
| 880 | Then c.__doc__ == "A description of C". |
| 881 | Then c.__init__.__doc__ == "A description of the constructor". |
| 882 | |
| 883 | Others |
| 884 | |
| 885 | lambda [param_list]: returnedExpr |
| 886 | -- Creates an anonymous function. returnedExpr must be |
| 887 | an expression, not a statement (e.g., not "if xx:...", |
| 888 | "print xxx", etc.) and thus can't contain newlines. |
| 889 | Used mostly for filter(), map(), reduce() functions, and GUI callbacks.. |
| 890 | List comprehensions |
| 891 | result = [expression for item1 in sequence1 [if condition1] |
| 892 | [for item2 in sequence2 ... for itemN in sequenceN] |
| 893 | ] |
| 894 | is equivalent to: |
| 895 | result = [] |
| 896 | for 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 | |
| 905 | Built-In Functions |
| 906 | |
| 907 | Built-In Functions |
| 908 | Function Result |
| 909 | __import__(name[, Imports module within the given context (see lib ref for |
| 910 | globals[, locals[, more details) |
| 911 | fromlist]]]) |
| 912 | abs(x) Return the absolute value of number x. |
| 913 | apply(f, args[, Calls func/method f with arguments args and optional |
| 914 | keywords]) keywords. |
| 915 | callable(x) Returns 1 if x callable, else 0. |
| 916 | chr(i) Returns one-character string whose ASCII code isinteger i |
| 917 | cmp(x,y) Returns negative, 0, positive if x <, ==, > to y |
| 918 | coerce(x,y) Returns a tuple of the two numeric arguments converted to a |
| 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 |
| 922 | compile(string, from which the code was read, or eg. '<string>'if not read |
| 923 | filename, kind) from file.kind can be 'eval' if string is a single stmt, or |
| 924 | 'single' which prints the output of expression statements |
| 925 | thatevaluate to something else than None, or be 'exec'. |
| 926 | complex(real[, Builds a complex object (can also be done using J or j |
| 927 | image]) suffix,e.g. 1+3J) |
| 928 | delattr(obj, name) deletes attribute named name of object obj <=> del obj.name |
| 929 | If no args, returns the list of names in current |
| 930 | dir([object]) localsymbol table. With a module, class or class |
| 931 | instanceobject as arg, returns list of names in its attr. |
| 932 | dict. |
| 933 | divmod(a,b) Returns tuple of (a/b, a%b) |
| 934 | eval(s[, globals[, Eval string s in (optional) globals, locals contexts.s must |
| 935 | locals]]) have no NUL's or newlines. s can also be acode object. |
| 936 | Example: x = 1; incr_x = eval('x + 1') |
| 937 | execfile(file[, Executes a file without creating a new module, unlike |
| 938 | globals[, locals]]) import. |
| 939 | filter(function, Constructs a list from those elements of sequence for which |
| 940 | sequence) function returns true. function takes one parameter. |
| 941 | float(x) Converts a number or a string to floating point. |
| 942 | getattr(object, [<default> arg added in 1.5.2]Gets attribute called name |
| 943 | name[, default])) from object,e.g. getattr(x, 'f') <=> x.f). If not found, |
| 944 | raisesAttributeError or returns default if specified. |
| 945 | globals() Returns a dictionary containing current global variables. |
| 946 | hasattr(object, Returns true if object has attr called name. |
| 947 | name) |
| 948 | hash(object) Returns the hash value of the object (if it has one) |
| 949 | hex(x) Converts a number x to a hexadecimal string. |
| 950 | id(object) Returns a unique 'identity' integer for an object. |
| 951 | input([prompt]) Prints prompt if given. Reads input and evaluates it. |
| 952 | Converts a number or a string to a plain integer. Optional |
| 953 | int(x[, base]) base paramenter specifies base from which to convert string |
| 954 | values. |
| 955 | intern(aString) Enters aString in the table of "interned strings" |
| 956 | andreturns the string. Interned strings are 'immortals'. |
| 957 | isinstance(obj, returns true if obj is an instance of class. Ifissubclass |
| 958 | class) (A,B) then isinstance(x,A) => isinstance(x,B) |
| 959 | issubclass(class1, returns true if class1 is derived from class2 |
| 960 | class2) |
| 961 | Returns the length (the number of items) of an object |
| 962 | len(obj) (sequence, dictionary, or instance of class implementing |
| 963 | __len__). |
| 964 | list(sequence) Converts sequence into a list. If already a list,returns a |
| 965 | copy of it. |
| 966 | locals() Returns a dictionary containing current local variables. |
| 967 | Converts a number or a string to a long integer. Optional |
| 968 | long(x[, base]) base paramenter specifies base from which to convert string |
| 969 | values. |
| 970 | Applies function to every item of list and returns a listof |
| 971 | map(function, list, the results. If additional arguments are passed,function |
| 972 | ...) must take that many arguments and it is givento function on |
| 973 | each call. |
| 974 | max(seq) Returns the largest item of the non-empty sequence seq. |
| 975 | min(seq) Returns the smallest item of a non-empty sequence seq. |
| 976 | oct(x) Converts a number to an octal string. |
| 977 | open(filename [, Returns a new file object. First two args are same asthose |
| 978 | mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered, |
| 979 | implementation 1 for line-buffered, negative forsys-default, all else, of |
| 980 | dependent]]) (about) given size. |
| 981 | ord(c) Returns integer ASCII value of c (a string of len 1). Works |
| 982 | with Unicode char. |
| 983 | pow(x, y [, z]) Returns x to power y [modulo z]. See also ** operator. |
| 984 | range(start [,end Returns list of ints from >= start and < end.With 1 arg, |
| 985 | [, step]]) list from 0..arg-1With 2 args, list from start..end-1With 3 |
| 986 | args, list from start up to end by step |
| 987 | raw_input([prompt]) Prints prompt if given, then reads string from stdinput (no |
| 988 | trailing \n). See also input(). |
| 989 | reduce(f, list [, Applies the binary function f to the items oflist so as to |
| 990 | init]) reduce the list to a single value.If init given, it is |
| 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 |
| 994 | reload(module) after fixing it. If module was syntacticallycorrect but had |
| 995 | an error in initialization, mustimport it one more time |
| 996 | before calling reload(). |
| 997 | Returns a string containing a printable and if possible |
| 998 | repr(object) evaluable representation of an object. <=> `object` |
| 999 | (usingbackquotes). Class redefinissable (__repr__). See |
| 1000 | also str() |
| 1001 | round(x, n=0) Returns the floating point value x rounded to n digitsafter |
| 1002 | the decimal point. |
| 1003 | setattr(object, This is the counterpart of getattr().setattr(o, 'foobar', |
| 1004 | name, value) 3) <=> o.foobar = 3Creates attribute if it doesn't exist! |
| 1005 | slice([start,] stop Returns a slice object representing a range, with R/ |
| 1006 | [, step]) Oattributes: start, stop, step. |
| 1007 | Returns a string containing a nicely |
| 1008 | str(object) printablerepresentation of an object. Class overridable |
| 1009 | (__str__).See also repr(). |
| 1010 | tuple(sequence) Creates a tuple with same elements as sequence. If already |
| 1011 | a tuple, return itself (not a copy). |
| 1012 | Returns a type object [see module types] representing |
| 1013 | thetype of obj. Example: import typesif type(x) == |
| 1014 | type(obj) types.StringType: print 'It is a string'NB: it is |
| 1015 | recommanded to use the following form:if isinstance(x, |
| 1016 | types.StringType): etc... |
| 1017 | unichr(code) code. |
| 1018 | unicode(string[, Creates a Unicode string from a 8-bit string, using |
| 1019 | encoding[, error thegiven encoding name and error treatment ('strict', |
| 1020 | ]]]) 'ignore',or 'replace'}. |
| 1021 | Without arguments, returns a dictionary correspondingto the |
| 1022 | current local symbol table. With a module,class or class |
| 1023 | vars([object]) instance object as argumentreturns a dictionary |
| 1024 | corresponding to the object'ssymbol table. Useful with "%" |
| 1025 | formatting operator. |
| 1026 | xrange(start [, end Like range(), but doesn't actually store entire listall at |
| 1027 | [, step]]) once. Good to use in "for" loops when there is abig range |
| 1028 | and little memory. |
| 1029 | zip(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 | |
| 1035 | Built-In Exceptions |
| 1036 | |
| 1037 | Exception> |
| 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 | |
| 1098 | Standard methods & operators redefinition in classes |
| 1099 | |
| 1100 | Standard 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 | |
| 1108 | Special 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 | |
| 1126 | Operators |
| 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 | |
| 1182 | Special 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 | |
| 1274 | Important Modules |
| 1275 | |
| 1276 | sys |
| 1277 | |
| 1278 | Some sys variables |
| 1279 | Variable Content |
| 1280 | argv The list of command line arguments passed to aPython |
| 1281 | script. sys.argv[0] is the script name. |
| 1282 | builtin_module_names A list of strings giving the names of all moduleswritten |
| 1283 | in C that are linked into this interpreter. |
| 1284 | check_interval How often to check for thread switches or signals(measured |
| 1285 | in number of virtual machine instructions) |
| 1286 | exc_type, exc_value, Deprecated since release 1.5. Use exc_info() instead. |
| 1287 | exc_traceback |
| 1288 | exitfunc User can set to a parameterless fcn. It will getcalled |
| 1289 | before interpreter exits. |
| 1290 | last_type, Set only when an exception not handled andinterpreter |
| 1291 | last_value, prints an error. Used by debuggers. |
| 1292 | last_traceback |
| 1293 | maxint maximum positive value for integers |
| 1294 | modules Dictionary of modules that have already been loaded. |
| 1295 | path Search path for external modules. Can be modifiedby |
| 1296 | program. sys.path[0] == dir of script executing |
| 1297 | platform The current platform, e.g. "sunos5", "win32" |
| 1298 | ps1, ps2 prompts to use in interactive mode. |
| 1299 | File objects used for I/O. One can redirect byassigning a |
| 1300 | stdin, stdout, new file object to them (or any object:.with a method |
| 1301 | stderr write(string) for stdout/stderr,.with a method readline() |
| 1302 | for stdin) |
| 1303 | version string containing version info about Python interpreter. |
| 1304 | (and also: copyright, dllhandle, exec_prefix, prefix) |
| 1305 | version_info tuple containing Python version info - (major, minor, |
| 1306 | micro, level, serial). |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1307 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1308 | Some sys functions |
| 1309 | Function Result |
| 1310 | exit(n) Exits with status n. Raises SystemExit exception.(Hence can |
| 1311 | be caught and ignored by program) |
| 1312 | getrefcount(object Returns the reference count of the object. Generally 1 |
| 1313 | ) higherthan you might expect, because of object arg temp |
| 1314 | reference. |
| 1315 | setcheckinterval( Sets the interpreter's thread switching interval (in number |
| 1316 | interval) ofvirtualcode instructions, default:10). |
| 1317 | settrace(func) Sets a trace function: called before each line ofcode is |
| 1318 | exited. |
| 1319 | setprofile(func) Sets a profile function for performance profiling. |
| 1320 | Info on exception currently being handled; this is atuple |
| 1321 | (exc_type, exc_value, exc_traceback).Warning: assigning the |
| 1322 | exc_info() traceback return value to a loca variable in a |
| 1323 | functionhandling an exception will cause a circular |
| 1324 | reference. |
| 1325 | setdefaultencoding Change default Unicode encoding - defaults to 7-bit ASCII. |
| 1326 | (encoding) |
| 1327 | getrecursionlimit Retrieve maximum recursion depth. |
| 1328 | () |
| 1329 | setrecursionlimit Set maximum recursion depth. (Defaults to 1000.) |
| 1330 | () |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1331 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1332 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1333 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1334 | os |
| 1335 | "synonym" for whatever O/S-specific module is proper for current environment. |
| 1336 | this module uses posix whenever possible. |
| 1337 | (see also M.A. Lemburg's utility http://www.lemburg.com/files/python/ |
| 1338 | platform.py) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1339 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1340 | Some os variables |
| 1341 | Variable Meaning |
| 1342 | name name of O/S-specific module (e.g. "posix", "mac", "nt") |
| 1343 | path O/S-specific module for path manipulations. |
| 1344 | On Unix, os.path.split() <=> posixpath.split() |
| 1345 | curdir string used to represent current directory ('.') |
| 1346 | pardir string used to represent parent directory ('..') |
| 1347 | sep string used to separate directories ('/' or '\'). Tip: use |
| 1348 | os.path.join() to build portable paths. |
| 1349 | altsep Alternate sep |
| 1350 | if applicable (None |
| 1351 | otherwise) |
| 1352 | pathsep character used to separate search path components (as in |
| 1353 | $PATH), eg. ';' for windows. |
| 1354 | linesep line separator as used in binary files, ie '\n' on Unix, '\ |
| 1355 | r\n' on Dos/Win, '\r' |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1356 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1357 | Some os functions |
| 1358 | Function Result |
| 1359 | makedirs(path[, Recursive directory creation (create required intermediary |
| 1360 | mode=0777]) dirs); os.error if fails. |
| 1361 | removedirs(path) Recursive directory delete (delete intermediary empty |
| 1362 | dirs); if fails. |
| 1363 | renames(old, new) Recursive directory or file renaming; os.error if fails. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1364 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1365 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1366 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1367 | posix |
| 1368 | don't import this module directly, import os instead ! |
| 1369 | (see also module: shutil for file copy & remove fcts) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1370 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1371 | posix Variables |
| 1372 | Variable Meaning |
| 1373 | environ dictionary of environment variables, e.g.posix.environ['HOME']. |
| 1374 | error exception raised on POSIX-related error. |
| 1375 | Corresponding value is tuple of errno code and perror() string. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1376 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1377 | Some posix functions |
| 1378 | Function Result |
| 1379 | chdir(path) Changes current directory to path. |
| 1380 | chmod(path, Changes the mode of path to the numeric mode |
| 1381 | mode) |
| 1382 | close(fd) Closes file descriptor fd opened with posix.open. |
| 1383 | _exit(n) Immediate exit, with no cleanups, no SystemExit,etc. Should use |
| 1384 | this to exit a child process. |
| 1385 | execv(p, args) "Become" executable p with args args |
| 1386 | getcwd() Returns a string representing the current working directory |
| 1387 | getpid() Returns the current process id |
| 1388 | fork() Like C's fork(). Returns 0 to child, child pid to parent.[Not |
| 1389 | on Windows] |
| 1390 | kill(pid, Like C's kill [Not on Windows] |
| 1391 | signal) |
| 1392 | listdir(path) Lists (base)names of entries in directory path, excluding '.' |
| 1393 | and '..' |
| 1394 | lseek(fd, pos, Sets current position in file fd to position pos, expressedas |
| 1395 | how) an offset relative to beginning of file (how=0), tocurrent |
| 1396 | position (how=1), or to end of file (how=2) |
| 1397 | mkdir(path[, Creates a directory named path with numeric mode (default 0777) |
| 1398 | mode]) |
| 1399 | open(file, Like C's open(). Returns file descriptor. Use file object |
| 1400 | flags, mode) fctsrather than this low level ones. |
| 1401 | pipe() Creates a pipe. Returns pair of file descriptors (r, w) [Not on |
| 1402 | Windows]. |
| 1403 | popen(command, Opens a pipe to or from command. Result is a file object to |
| 1404 | mode='r', read to orwrite from, as indicated by mode being 'r' or 'w'. |
| 1405 | bufSize=0) Use it to catch acommand output ('r' mode) or to feed it ('w' |
| 1406 | mode). |
| 1407 | remove(path) See unlink. |
| 1408 | rename(src, dst Renames/moves the file or directory src to dst. [error iftarget |
| 1409 | ) name already exists] |
| 1410 | rmdir(path) Removes the empty directory path |
| 1411 | read(fd, n) Reads n bytes from file descriptor fd and return as string. |
| 1412 | Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid, |
| 1413 | stat(path) st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid |
| 1414 | are dummy on Windows] |
| 1415 | system(command) Executes string command in a subshell. Returns exitstatus of |
| 1416 | subshell (usually 0 means OK). |
| 1417 | Returns accumulated CPU times in sec (user, system, children's |
| 1418 | times() user,children's sys, elapsed real time). [3 last not on |
| 1419 | Windows] |
| 1420 | unlink(path) Unlinks ("deletes") the file (not dir!) path. same as: remove |
| 1421 | utime(path, ( Sets the access & modified time of the file to the given tuple |
| 1422 | aTime, mTime)) of values. |
| 1423 | wait() Waits for child process completion. Returns tuple ofpid, |
| 1424 | exit_status [Not on Windows] |
| 1425 | waitpid(pid, Waits for process pid to complete. Returns tuple ofpid, |
| 1426 | options) exit_status [Not on Windows] |
| 1427 | write(fd, str) Writes str to file fd. Returns nb of bytes written. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1428 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1429 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1430 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1431 | posixpath |
| 1432 | Do not import this module directly, import os instead and refer to this module |
| 1433 | as os.path. (e.g. os.path.exists(p)) ! |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1434 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1435 | Some posixpath functions |
| 1436 | Function Result |
| 1437 | abspath(p) Returns absolute path for path p, taking current working dir in |
| 1438 | account. |
| 1439 | dirname/ |
| 1440 | basename(p directory and name parts of the path p. See also split. |
| 1441 | ) |
| 1442 | exists(p) True if string p is an existing path (file or directory) |
| 1443 | expanduser Returns string that is (a copy of) p with "~" expansion done. |
| 1444 | (p) |
| 1445 | expandvars Returns string that is (a copy of) p with environment vars expanded. |
| 1446 | (p) [Windows: case significant; must use Unix: $var notation, not %var%] |
| 1447 | getsize( return the size in bytes of filename. raise os.error. |
| 1448 | filename) |
| 1449 | getmtime( return last modification time of filename (integer nb of seconds |
| 1450 | filename) since epoch). |
| 1451 | getatime( return last access time of filename (integer nb of seconds since |
| 1452 | filename) epoch). |
| 1453 | isabs(p) True if string p is an absolute path. |
| 1454 | isdir(p) True if string p is a directory. |
| 1455 | islink(p) True if string p is a symbolic link. |
| 1456 | ismount(p) True if string p is a mount point [true for all dirs on Windows]. |
| 1457 | join(p[,q Joins one or more path components intelligently. |
| 1458 | [,...]]) |
| 1459 | Splits p into (head, tail) where tail is lastpathname component and |
| 1460 | split(p) <head> is everything leadingup to that. <=> (dirname(p), basename |
| 1461 | (p)) |
| 1462 | splitdrive Splits path p in a pair ('drive:', tail) [Windows] |
| 1463 | (p) |
| 1464 | splitext(p Splits into (root, ext) where last comp of root contains no periods |
| 1465 | ) and ext is empty or startswith a period. |
| 1466 | Calls the function visit with arguments(arg, dirname, names) for |
| 1467 | each directory recursively inthe directory tree rooted at p |
| 1468 | walk(p, (including p itself if it's a dir)The argument dirname specifies the |
| 1469 | visit, arg visited directory, the argumentnames lists the files in the |
| 1470 | ) directory. The visit function maymodify names to influence the set |
| 1471 | of directories visited belowdirname, e.g., to avoid visiting certain |
| 1472 | parts of the tree. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1473 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1474 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1475 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1476 | shutil |
| 1477 | high-level file operations (copying, deleting). |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1478 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1479 | Main shutil functions |
| 1480 | Function Result |
| 1481 | copy(src, dst) Copies the contents of file src to file dst, retaining file |
| 1482 | permissions. |
| 1483 | copytree(src, dst Recursively copies an entire directory tree rooted at src |
| 1484 | [, symlinks]) into dst (which should not already exist). If symlinks is |
| 1485 | true, links insrc are kept as such in dst. |
| 1486 | rmtree(path[, Deletes an entire directory tree, ignoring errors if |
| 1487 | ignore_errors[, ignore_errors true,or calling onerror(func, path, |
| 1488 | onerror]]) sys.exc_info()) if supplied with |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1489 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1490 | (and also: copyfile, copymode, copystat, copy2) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1491 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1492 | time |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1493 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1494 | Variables |
| 1495 | Variable Meaning |
| 1496 | altzone signed offset of local DST timezone in sec west of the 0th meridian. |
| 1497 | daylight nonzero if a DST timezone is specified |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1498 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1499 | Functions |
| 1500 | Function Result |
| 1501 | time() return a float representing UTC time in seconds since the epoch. |
| 1502 | gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day |
| 1503 | localtime( (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is |
| 1504 | secs) monday), Julian day(1-366), daylight flag(-1,0 or 1)) |
| 1505 | asctime( |
| 1506 | timeTuple), |
| 1507 | strftime( |
| 1508 | format, return a formated string representing time. |
| 1509 | timeTuple) |
| 1510 | mktime(tuple) inverse of localtime(). Return a float. |
| 1511 | strptime( parse a formated string representing time, return tuple as in |
| 1512 | string[, gmtime(). |
| 1513 | format]) |
| 1514 | sleep(secs) Suspend execution for <secs> seconds. <secs> can be a float. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1515 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1516 | and also: clock, ctime. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1517 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1518 | string |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1519 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1520 | As of Python 2.0, much (though not all) of the functionality provided by the |
| 1521 | string module have been superseded by built-in string methods - see Operations |
| 1522 | on strings for details. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1523 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1524 | Some string variables |
| 1525 | Variable Meaning |
| 1526 | digits The string '0123456789' |
| 1527 | hexdigits, octdigits legal hexadecimal & octal digits |
| 1528 | letters, uppercase, lowercase, Strings containing the appropriate |
| 1529 | whitespace characters |
| 1530 | index_error Exception raised by index() if substr not |
| 1531 | found. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1532 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1533 | Some string functions |
| 1534 | Function Result |
| 1535 | expandtabs(s, returns a copy of string <s> with tabs expanded. |
| 1536 | tabSize) |
| 1537 | find/rfind(s, sub Return the lowest/highest index in <s> where the substring |
| 1538 | [, start=0[, end= <sub> is found such that <sub> is wholly contained ins |
| 1539 | 0]) [start:end]. Return -1 if <sub> not found. |
| 1540 | ljust/rjust/center Return a copy of string <s> left/right justified/centerd in |
| 1541 | (s, width) afield of given width, padded with spaces. <s> is |
| 1542 | nevertruncated. |
| 1543 | lower/upper(s) Return a string that is (a copy of) <s> in lowercase/ |
| 1544 | uppercase |
| 1545 | split(s[, sep= Return a list containing the words of the string <s>,using |
| 1546 | whitespace[, the string <sep> as a separator. |
| 1547 | maxsplit=0]]) |
| 1548 | join(words[, sep=' Concatenate a list or tuple of words with |
| 1549 | ']) interveningseparators; inverse of split. |
| 1550 | replace(s, old, Returns a copy of string <s> with all occurences of |
| 1551 | new[, maxsplit=0] substring<old> replaced by <new>. Limits to <maxsplit> |
| 1552 | firstsubstitutions if specified. |
| 1553 | strip(s) Return a string that is (a copy of) <s> without leadingand |
| 1554 | trailing whitespace. see also lstrip, rstrip. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1555 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1556 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1557 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1558 | re (sre) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1559 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1560 | Handles Unicode strings. Implemented in new module sre, re now a mere front-end |
| 1561 | for compatibility. |
| 1562 | Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to |
| 1563 | litteralize backslashes. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1564 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1565 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1566 | 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 Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1598 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1599 | Special sequences |
| 1600 | Sequence Description |
| 1601 | number 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 Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1613 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1614 | Variables |
| 1615 | Variable Meaning |
| 1616 | error Exception when pattern string isn't a valid regexp. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1617 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1618 | Functions |
| 1619 | Function Result |
| 1620 | Compile a RE pattern string into a regular expression object. |
| 1621 | Flags (combinable by |): |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1622 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1623 | I or IGNORECASE or (?i) |
| 1624 | case insensitive matching |
| 1625 | compile( L or LOCALE or (?L) |
| 1626 | pattern[, make \w, \W, \b, \B dependent on thecurrent locale |
| 1627 | flags=0]) M or MULTILINE or (?m) |
| 1628 | matches every new line and not onlystart/end of the whole |
| 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 |
| 1634 | escape(string) return (a copy of) string with all non-alphanumerics |
| 1635 | backslashed. |
| 1636 | match(pattern, if 0 or more chars at beginning of <string> match the RE pattern |
| 1637 | string[, flags string,return a corresponding MatchObject instance, or None if |
| 1638 | ]) no match. |
| 1639 | search(pattern scan thru <string> for a location matching <pattern>, return |
| 1640 | , string[, acorresponding MatchObject instance, or None if no match. |
| 1641 | flags]) |
| 1642 | split(pattern, split <string> by occurrences of <pattern>. If capturing () are |
| 1643 | string[, used inpattern, then occurrences of patterns or subpatterns are |
| 1644 | maxsplit=0]) also returned. |
| 1645 | findall( return a list of non-overlapping matches in <pattern>, either a |
| 1646 | pattern, list ofgroups or a list of tuples if the pattern has more than 1 |
| 1647 | string) group. |
| 1648 | return string obtained by replacing the (<count> first) lefmost |
| 1649 | sub(pattern, non-overlapping occurrences of <pattern> (a string or a RE |
| 1650 | repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct |
| 1651 | count=0]) called with a single MatchObj arg, which must return the |
| 1652 | replacement string. |
| 1653 | subn(pattern, |
| 1654 | repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade) |
| 1655 | count=0]) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1656 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1657 | Regular Expression Objects |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1658 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1659 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1660 | (RE objects are returned by the compile fct) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1661 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1662 | re object attributes |
| 1663 | Attribute Descrition |
| 1664 | flags flags arg used when RE obj was compiled, or 0 if none provided |
| 1665 | groupindex dictionary of {group name: group number} in pattern |
| 1666 | pattern pattern string from which RE obj was compiled |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1667 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1668 | 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 |
| 1675 | match( where the search is to start; it defaults to 0. This is not |
| 1676 | string[, completely equivalent to slicing the string; the '' pattern |
| 1677 | pos][, character matches at the real beginning of the string and at |
| 1678 | endpos]) positions just after a newline, but not necessarily at the index |
| 1679 | where the search is to start. |
| 1680 | The optional parameter endpos limits how far the string will be |
| 1681 | searched; it will be as if the string is endpos characters long, so |
| 1682 | only the characters from pos to endpos will be searched for a |
| 1683 | match. |
| 1684 | Scan through string looking for a location where this regular |
| 1685 | search( expression produces a match, and return a corresponding MatchObject |
| 1686 | string[, instance. Return None if no position in the string matches the |
| 1687 | pos][, pattern; note that this is different from finding a zero-length |
| 1688 | endpos]) match at some point in the string. |
| 1689 | The optional pos and endpos parameters have the same meaning as for |
| 1690 | the match() method. |
| 1691 | split( |
| 1692 | string[, Identical to the split() function, using the compiled pattern. |
| 1693 | maxsplit= |
| 1694 | 0]) |
| 1695 | findall( Identical to the findall() function, using the compiled pattern. |
| 1696 | string) |
| 1697 | sub(repl, |
| 1698 | string[, Identical to the sub() function, using the compiled pattern. |
| 1699 | count=0]) |
| 1700 | subn(repl, |
| 1701 | string[, Identical to the subn() function, using the compiled pattern. |
| 1702 | count=0]) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1703 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1704 | Match Objects |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1705 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1706 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1707 | (Match objects are returned by the match & search functions) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1708 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1709 | Match object attributes |
| 1710 | Attribute Description |
| 1711 | pos value of pos passed to search or match functions; index intostring at |
| 1712 | which RE engine started search. |
| 1713 | endpos value of endpos passed to search or match functions; index intostring |
| 1714 | beyond which RE engine won't go. |
| 1715 | re RE object whose match or search fct produced this MatchObj instance |
| 1716 | string string passed to match() or search() |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1717 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1718 | Match object functions |
| 1719 | Function Result |
| 1720 | returns one or more groups of the match. If one arg, result is a |
| 1721 | group([g1 string;if multiple args, result is a tuple with one item per arg. If |
| 1722 | , g2, gi is 0,return value is entire matching string; if 1 <= gi <= 99, |
| 1723 | ...]) returnstring matching group #gi (or None if no such group); gi may |
| 1724 | also bea group name. |
| 1725 | returns a tuple of all groups of the match; groups not |
| 1726 | groups() participatingto the match have a value of None. Returns a string |
| 1727 | instead of tupleif len(tuple)=1 |
| 1728 | start( |
| 1729 | group), returns indices of start & end of substring matched by group (or |
| 1730 | end(group Noneif group exists but doesn't contribute to the match) |
| 1731 | ) |
| 1732 | span( returns the 2-tuple (start(group), end(group)); can be (None, None)if |
| 1733 | group) group didn't contibute to the match. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1734 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1735 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1736 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1737 | math |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1738 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1739 | Variables: |
| 1740 | pi |
| 1741 | e |
| 1742 | Functions (see ordinary C man pages for info): |
| 1743 | acos(x) |
| 1744 | asin(x) |
| 1745 | atan(x) |
| 1746 | atan2(x, y) |
| 1747 | ceil(x) |
| 1748 | cos(x) |
| 1749 | cosh(x) |
| 1750 | exp(x) |
| 1751 | fabs(x) |
| 1752 | floor(x) |
| 1753 | fmod(x, y) |
| 1754 | frexp(x) -- Unlike C: (float, int) = frexp(float) |
| 1755 | ldexp(x, y) |
| 1756 | log(x) |
| 1757 | log10(x) |
| 1758 | modf(x) -- Unlike C: (float, float) = modf(float) |
| 1759 | pow(x, y) |
| 1760 | sin(x) |
| 1761 | sinh(x) |
| 1762 | sqrt(x) |
| 1763 | tan(x) |
| 1764 | tanh(x) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1765 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1766 | getopt |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1767 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1768 | Functions: |
| 1769 | getopt(list, optstr) -- Similar to C. <optstr> is option |
| 1770 | letters to look for. Put ':' after letter |
| 1771 | if option takes arg. E.g. |
| 1772 | # invocation was "python test.py -c hi -a arg1 arg2" |
| 1773 | opts, args = getopt.getopt(sys.argv[1:], 'ab:c:') |
| 1774 | # opts would be |
| 1775 | [('-c', 'hi'), ('-a', '')] |
| 1776 | # args would be |
| 1777 | ['arg1', 'arg2'] |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1778 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1779 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1780 | List of modules and packages in base distribution |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1781 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1782 | (built-ins and content of python Lib directory) |
| 1783 | (Python NT distribution, may be slightly different in other distributions) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1784 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1785 | Standard library modules |
| 1786 | Operation Result |
| 1787 | aifc Stuff to parse AIFF-C and AIFF files. |
| 1788 | anydbm Generic interface to all dbm clones. (dbhash, gdbm, |
| 1789 | dbm,dumbdbm) |
| 1790 | asynchat Support for 'chat' style protocols |
| 1791 | asyncore Asynchronous File I/O (in select style) |
| 1792 | atexit Register functions to be called at exit of Python interpreter. |
| 1793 | audiodev Audio support for a few platforms. |
| 1794 | base64 Conversions to/from base64 RFC-MIME transport encoding . |
| 1795 | BaseHTTPServer Base class forhttp services. |
| 1796 | Bastion "Bastionification" utility (control access to instance vars) |
| 1797 | bdb A generic Python debugger base class. |
| 1798 | binhex Macintosh binhex compression/decompression. |
| 1799 | bisect List bisection algorithms. |
| 1800 | calendar Calendar printing functions. |
| 1801 | cgi Wraps the WWW Forms Common Gateway Interface (CGI). |
| 1802 | CGIHTTPServer CGI http services. |
| 1803 | cmd A generic class to build line-oriented command interpreters. |
| 1804 | [DEL:cmp:DEL] [DEL:Efficiently compare files, boolean outcome only.:DEL] |
| 1805 | [DEL:cmpcache: [DEL:Same, but caches 'stat' results for speed.:DEL] |
| 1806 | DEL] |
| 1807 | code Utilities needed to emulate Python's interactive interpreter |
| 1808 | codecs Lookup existing Unicode encodings and register new ones. |
| 1809 | colorsys Conversion functions between RGB and other color systems. |
| 1810 | commands Tools for executing UNIX commands . |
| 1811 | compileall Force "compilation" of all .py files in a directory. |
| 1812 | ConfigParser Configuration file parser (much like windows .ini files) |
| 1813 | copy Generic shallow and deep copying operations. |
| 1814 | copy_reg Helper to provide extensibility for pickle/cPickle. |
| 1815 | dbhash (g)dbm-compatible interface to bsdhash.hashopen. |
| 1816 | dircache Sorted list of files in a dir, using a cache. |
| 1817 | [DEL:dircmp:DEL] [DEL:Defines a class to build directory diff tools on.:DEL] |
| 1818 | dis Bytecode disassembler. |
| 1819 | distutils Package installation system. |
| 1820 | dospath Common operations on DOS pathnames. |
| 1821 | dumbdbm A dumb and slow but simple dbm clone. |
| 1822 | [DEL:dump:DEL] [DEL:Print python code that reconstructs a variable.:DEL] |
| 1823 | exceptions Class based built-in exception hierarchy. |
| 1824 | filecmp File comparison. |
| 1825 | fileinput Helper class to quickly write a loop over all standard input |
| 1826 | files. |
| 1827 | [DEL:find:DEL] [DEL:Find files directory hierarchy matching a pattern.:DEL] |
| 1828 | fnmatch Filename matching with shell patterns. |
| 1829 | formatter A test formatter. |
| 1830 | fpformat General floating point formatting functions. |
| 1831 | ftplib An FTP client class. Based on RFC 959. |
| 1832 | gc Perform garbacge collection, obtain GC debug stats, and tune |
| 1833 | GC parameters. |
| 1834 | getopt Standard command line processing. See also ftp:// |
| 1835 | www.pauahtun.org/pub/getargspy.zip |
| 1836 | getpass Utilities to get a password and/or the current user name. |
| 1837 | glob filename globbing. |
| 1838 | gopherlib Gopher protocol client interface. |
| 1839 | [DEL:grep:DEL] [DEL:'grep' utilities.:DEL] |
| 1840 | gzip Read & write gzipped files. |
| 1841 | htmlentitydefs Proposed entity definitions for HTML. |
| 1842 | htmllib HTML parsing utilities. |
| 1843 | httplib HTTP client class. |
| 1844 | ihooks Hooks into the "import" mechanism. |
| 1845 | imaplib IMAP4 client.Based on RFC 2060. |
| 1846 | imghdr Recognizing image files based on their first few bytes. |
| 1847 | imputil Privides a way of writing customised import hooks. |
| 1848 | keyword List of Python keywords. |
| 1849 | knee A Python re-implementation of hierarchical module import. |
| 1850 | linecache Cache lines from files. |
| 1851 | linuxaudiodev Lunix /dev/audio support. |
| 1852 | locale Support for number formatting using the current locale |
| 1853 | settings. |
| 1854 | macpath Pathname (or related) operations for the Macintosh. |
| 1855 | macurl2path Mac specific module for conversion between pathnames and URLs. |
| 1856 | mailbox A class to handle a unix-style or mmdf-style mailbox. |
| 1857 | mailcap Mailcap file handling (RFC 1524). |
| 1858 | mhlib MH (mailbox) interface. |
| 1859 | mimetools Various tools used by MIME-reading or MIME-writing programs. |
| 1860 | mimetypes Guess the MIME type of a file. |
| 1861 | MimeWriter Generic MIME writer. |
| 1862 | mimify Mimification and unmimification of mail messages. |
| 1863 | mmap Interface to memory-mapped files - they behave like mutable |
| 1864 | strings./font> |
| 1865 | multifile Class to make multi-file messages easier to handle. |
| 1866 | mutex Mutual exclusion -- for use with module sched. |
| 1867 | netrc |
| 1868 | nntplib An NNTP client class. Based on RFC 977. |
| 1869 | ntpath Common operations on DOS pathnames. |
| 1870 | nturl2path Mac specific module for conversion between pathnames and URLs. |
| 1871 | os Either mac, dos or posix depending system. |
| 1872 | [DEL:packmail: [DEL:Create a self-unpacking shell archive.:DEL] |
| 1873 | DEL] |
| 1874 | pdb A Python debugger. |
| 1875 | pickle Pickling (save and restore) of Python objects (a faster |
| 1876 | Cimplementation exists in built-in module: cPickle). |
| 1877 | pipes Conversion pipeline templates. |
| 1878 | [DEL:poly:DEL] [DEL:Polynomials.:DEL] |
| 1879 | popen2 variations on pipe open. |
| 1880 | poplib A POP3 client class. Based on the J. Myers POP3 draft. |
| 1881 | posixfile Extended (posix) file operations. |
| 1882 | posixpath Common operations on POSIX pathnames. |
| 1883 | pprint Support to pretty-print lists, tuples, & dictionaries |
| 1884 | recursively. |
| 1885 | profile Class for profiling python code. |
| 1886 | pstats Class for printing reports on profiled python code. |
| 1887 | pty Pseudo terminal utilities. |
| 1888 | pyexpat Interface to the Expay XML parser. |
| 1889 | py_compile Routine to "compile" a .py file to a .pyc file. |
| 1890 | pyclbr Parse a Python file and retrieve classes and methods. |
| 1891 | Queue A multi-producer, multi-consumer queue. |
| 1892 | quopri Conversions to/from quoted-printable transport encoding. |
| 1893 | rand Don't use unless you want compatibility with C's rand(). |
| 1894 | random Random variable generators (obsolete, use whrandom) |
| 1895 | re Regular Expressions. |
| 1896 | reconvert Convert old ("regex") regular expressions to new syntax |
| 1897 | ("re"). |
| 1898 | regex_syntax Flags for regex.set_syntax(). |
| 1899 | regexp Backward compatibility for module "regexp" using "regex". |
| 1900 | regsub Regular expression subroutines. |
| 1901 | repr Redo repr() but with limits on most sizes. |
| 1902 | rexec Restricted execution facilities ("safe" exec, eval, etc). |
| 1903 | rfc822 RFC-822 message manipulation class. |
| 1904 | rlcompleter Word completion for GNU readline 2.0. |
| 1905 | robotparser Parse robot.txt files, useful for web spiders. |
| 1906 | sched A generally useful event scheduler class. |
| 1907 | sgmllib A parser for SGML. |
| 1908 | shelve Manage shelves of pickled objects. |
| 1909 | shlex Lexical analyzer class for simple shell-like syntaxes. |
| 1910 | shutil Utility functions usable in a shell-like program. |
| 1911 | SimpleHTTPServer Simple extension to base http class |
| 1912 | site Append module search paths for third-party packages to |
| 1913 | sys.path. |
| 1914 | smtplib SMTP Client class (RFC 821) |
| 1915 | sndhdr Several routines that help recognizing sound. |
| 1916 | SocketServer Generic socket server classes. |
| 1917 | stat Constants and functions for interpreting stat/lstat struct. |
| 1918 | statcache Maintain a cache of file stats. |
| 1919 | statvfs Constants for interpreting statvfs struct as returned by |
| 1920 | os.statvfs()and os.fstatvfs() (if they exist). |
| 1921 | string A collection of string operations. |
| 1922 | StringIO File-like objects that read/write a string buffer (a fasterC |
| 1923 | implementation exists in built-in module: cStringIO). |
| 1924 | sunau Stuff to parse Sun and NeXT audio files. |
| 1925 | sunaudio Interpret sun audio headers. |
| 1926 | symbol Non-terminal symbols of Python grammar (from "graminit.h"). |
| 1927 | tabnanny,/font> Check Python source for ambiguous indentation. |
| 1928 | telnetlib TELNET client class. Based on RFC 854. |
| 1929 | tempfile Temporary file name allocation. |
| 1930 | threading Proposed new higher-level threading interfaces |
| 1931 | threading_api (doc of the threading module) |
| 1932 | toaiff Convert "arbitrary" sound files to AIFF files . |
| 1933 | token Tokens (from "token.h"). |
| 1934 | tokenize Compiles a regular expression that recognizes Python tokens. |
| 1935 | traceback Format and print Python stack traces. |
| 1936 | tty Terminal utilities. |
| 1937 | turtle LogoMation-like turtle graphics |
| 1938 | types Define names for all type symbols in the std interpreter. |
| 1939 | tzparse Parse a timezone specification. |
| 1940 | unicodedata Interface to unicode properties. |
| 1941 | urllib Open an arbitrary URL. |
| 1942 | urlparse Parse URLs according to latest draft of standard. |
| 1943 | user Hook to allow user-specified customization code to run. |
| 1944 | UserDict A wrapper to allow subclassing of built-in dict class. |
| 1945 | UserList A wrapper to allow subclassing of built-in list class. |
| 1946 | UserString A wrapper to allow subclassing of built-in string class. |
| 1947 | [DEL:util:DEL] [DEL:some useful functions that don't fit elsewhere !!:DEL] |
| 1948 | uu UUencode/UUdecode. |
| 1949 | wave Stuff to parse WAVE files. |
| 1950 | webbrowser Platform independent URL launcher. |
| 1951 | [DEL:whatsound: [DEL:Several routines that help recognizing sound files.:DEL] |
| 1952 | DEL] |
| 1953 | whichdb Guess which db package to use to open a db file. |
| 1954 | whrandom Wichmann-Hill random number generator. |
| 1955 | xdrlib Implements (a subset of) Sun XDR (eXternal Data |
| 1956 | Representation) |
| 1957 | xmllib A parser for XML, using the derived class as static DTD. |
| 1958 | xml.dom Classes for processing XML using the Document Object Model. |
| 1959 | xml.sax Classes for processing XML using the SAX API. |
| 1960 | zipfile Read & write PK zipped files. |
| 1961 | [DEL:zmod:DEL] [DEL:Demonstration of abstruse mathematical concepts.:DEL] |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1962 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1963 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1964 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1965 | (following list not revised) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1966 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1967 | * Built-ins * |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1968 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1969 | sys Interpreter state vars and functions |
| 1970 | __built-in__ Access to all built-in python identifiers |
| 1971 | __main__ Scope of the interpreters main program, script or stdin |
| 1972 | array Obj efficiently representing arrays of basic values |
| 1973 | math Math functions of C standard |
| 1974 | time Time-related functions |
| 1975 | regex Regular expression matching operations |
| 1976 | marshal Read and write some python values in binary format |
| 1977 | struct Convert between python values and C structs |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1978 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1979 | * Standard * |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1980 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1981 | getopt Parse cmd line args in sys.argv. A la UNIX 'getopt'. |
| 1982 | os A more portable interface to OS dependent functionality |
| 1983 | re Functions useful for working with regular expressions |
| 1984 | string Useful string and characters functions and exceptions |
| 1985 | whrandom Wichmann-Hill pseudo-random number generator |
| 1986 | thread Low-level primitives for working with process threads |
| 1987 | threading idem, new recommanded interface. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1988 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1989 | * Unix/Posix * |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1990 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1991 | dbm Interface to Unix ndbm database library |
| 1992 | grp Interface to Unix group database |
| 1993 | posix OS functionality standardized by C and POSIX standards |
| 1994 | posixpath POSIX pathname functions |
| 1995 | pwd Access to the Unix password database |
| 1996 | select Access to Unix select multiplex file synchronization |
| 1997 | socket Access to BSD socket interface |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 1998 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 1999 | * Tk User-interface Toolkit * |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2000 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2001 | tkinter Main interface to Tk |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2002 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2003 | * Multimedia * |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2004 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2005 | audioop Useful operations on sound fragments |
| 2006 | imageop Useful operations on images |
| 2007 | jpeg Access to jpeg image compressor and decompressor |
| 2008 | rgbimg Access SGI imglib image files |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2009 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2010 | * Cryptographic Extensions * |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2011 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2012 | md5 Interface to RSA's MD5 message digest algorithm |
| 2013 | mpz Interface to int part of GNU multiple precision library |
| 2014 | rotor Implementation of a rotor-based encryption algorithm |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2015 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2016 | * Stdwin * Standard Window System |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2017 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2018 | stdwin Standard Window System interface |
| 2019 | stdwinevents Stdwin event, command, and selection constants |
| 2020 | rect Rectangle manipulation operations |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2021 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2022 | * SGI IRIX * (4 & 5) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2023 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2024 | 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 Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2034 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2035 | * Suns * |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2036 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2037 | sunaudiodev Access to sun audio interface |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2038 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2039 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2040 | Workspace exploration and idiom hints |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2041 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2042 | dir(<module>) list functions, variables in <module> |
| 2043 | dir() get object keys, defaults to local name space |
| 2044 | X.__methods__ list of methods supported by X (if any) |
| 2045 | X.__members__ List of X's data attributes |
| 2046 | if __name__ == '__main__': main() invoke main if running as script |
| 2047 | map(None, lst1, lst2, ...) merge lists |
| 2048 | b = a[:] create copy of seq structure |
| 2049 | _ in interactive mode, is last value printed |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2050 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2051 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2052 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2053 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2054 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2055 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2056 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2057 | Python Mode for Emacs |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2058 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2059 | (Not revised, possibly not up to date) |
| 2060 | Type C-c ? when in python-mode for extensive help. |
| 2061 | INDENTATION |
| 2062 | Primarily for entering new code: |
| 2063 | TAB indent line appropriately |
| 2064 | LFD insert newline, then indent |
| 2065 | DEL reduce indentation, or delete single character |
| 2066 | Primarily for reindenting existing code: |
| 2067 | C-c : guess py-indent-offset from file content; change locally |
| 2068 | C-u C-c : ditto, but change globally |
| 2069 | C-c TAB reindent region to match its context |
| 2070 | C-c < shift region left by py-indent-offset |
| 2071 | C-c > shift region right by py-indent-offset |
| 2072 | MARKING & MANIPULATING REGIONS OF CODE |
| 2073 | C-c C-b mark block of lines |
| 2074 | M-C-h mark smallest enclosing def |
| 2075 | C-u M-C-h mark smallest enclosing class |
| 2076 | C-c # comment out region of code |
| 2077 | C-u C-c # uncomment region of code |
| 2078 | MOVING POINT |
| 2079 | C-c C-p move to statement preceding point |
| 2080 | C-c C-n move to statement following point |
| 2081 | C-c C-u move up to start of current block |
| 2082 | M-C-a move to start of def |
| 2083 | C-u M-C-a move to start of class |
| 2084 | M-C-e move to end of def |
| 2085 | C-u M-C-e move to end of class |
| 2086 | EXECUTING PYTHON CODE |
| 2087 | C-c C-c sends the entire buffer to the Python interpreter |
| 2088 | C-c | sends the current region |
| 2089 | C-c ! starts a Python interpreter window; this will be used by |
| 2090 | subsequent C-c C-c or C-c | commands |
| 2091 | VARIABLES |
| 2092 | py-indent-offset indentation increment |
| 2093 | py-block-comment-prefix comment string used by py-comment-region |
| 2094 | py-python-command shell command to invoke Python interpreter |
| 2095 | py-scroll-process-buffer t means always scroll Python process buffer |
| 2096 | py-temp-directory directory used for temp files (if needed) |
| 2097 | py-beep-if-tab-change ring the bell if tab-width is changed |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2098 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2099 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2100 | The Python Debugger |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2101 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2102 | (Not revised, possibly not up to date, see 1.5.2 Library Ref section 9.1; in 1.5.2, you may also use debugger integrated in IDLE) |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2103 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2104 | Accessing |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2105 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2106 | import pdb (it's a module written in Python) |
| 2107 | -- defines functions : |
| 2108 | run(statement[,globals[, locals]]) |
| 2109 | -- execute statement string under debugger control, with optional |
| 2110 | global & local environment. |
| 2111 | runeval(expression[,globals[, locals]]) |
| 2112 | -- same as run, but evaluate expression and return value. |
| 2113 | runcall(function[, argument, ...]) |
| 2114 | -- run function object with given arg(s) |
| 2115 | pm() -- run postmortem on last exception (like debugging a core file) |
| 2116 | post_mortem(t) |
| 2117 | -- run postmortem on traceback object <t> |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2118 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2119 | -- defines class Pdb : |
| 2120 | use Pdb to create reusable debugger objects. Object |
| 2121 | preserves state (i.e. break points) between calls. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2122 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2123 | runs until a breakpoint hit, exception, or end of program |
| 2124 | If exception, variable '__exception__' holds (exception,value). |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2125 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2126 | Commands |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2127 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2128 | h, help |
| 2129 | brief reminder of commands |
| 2130 | b, 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 |
| 2134 | cl, clear [<arg>] |
| 2135 | if <arg> numeric, clear breakpoint at <arg> in current file |
| 2136 | if no arg, clear all breakpoints after confirmation |
| 2137 | w, where |
| 2138 | print current call stack |
| 2139 | u, up |
| 2140 | move up one stack frame (to top-level caller) |
| 2141 | d, down |
| 2142 | move down one stack frame |
| 2143 | s, step |
| 2144 | advance one line in the program, stepping into calls |
| 2145 | n, next |
| 2146 | advance one line, stepping over calls |
| 2147 | r, 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) |
| 2151 | c, continue |
| 2152 | continue until next breakpoint |
| 2153 | a, args |
| 2154 | print args to current function |
| 2155 | rv, retval |
| 2156 | prints return value from last function that returned |
| 2157 | p, print <arg> |
| 2158 | prints value of <arg> in current stack frame |
| 2159 | l, list [<first> [, <last>]] |
| 2160 | List source code for the current file. |
| 2161 | Without arguments, list 11 lines around the current line |
| 2162 | or continue the previous listing. |
| 2163 | With one argument, list 11 lines starting at that line. |
| 2164 | With two arguments, list the given range; |
| 2165 | if the second argument is less than the first, it is a count. |
| 2166 | whatis <arg> |
| 2167 | prints type of <arg> |
| 2168 | ! |
| 2169 | executes rest of line as a Python statement in the current stack frame |
| 2170 | q quit |
| 2171 | immediately stop execution and leave debugger |
| 2172 | <return> |
| 2173 | executes last command again |
| 2174 | Any input debugger doesn't recognize as a command is assumed to be a |
| 2175 | Python statement to execute in the current stack frame, the same way |
| 2176 | the exclamation mark ("!") command does. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2177 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2178 | Example |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2179 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2180 | (1394) python |
| 2181 | Python 1.0.3 (Sep 26 1994) |
| 2182 | Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam |
| 2183 | >>> import rm |
| 2184 | >>> rm.run() |
| 2185 | Traceback (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 |
| 2191 | ZeroDivisionError: 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 |
| 2206 | 0 |
| 2207 | (Pdb) q |
| 2208 | >>> pdb.runcall(rm.run) |
| 2209 | etc. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2210 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2211 | Quirks |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2212 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2213 | Breakpoints are stored as filename, line number tuples. If a module is reloaded |
| 2214 | after editing, any remembered breakpoints are likely to be wrong. |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2215 | |
Andrew M. Kuchling | 13423f3 | 2001-08-06 17:43:49 +0000 | [diff] [blame] | 2216 | Always single-steps through top-most stack frame. That is, "c" acts like "n". |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2217 | |
Guido van Rossum | c8180cc | 1994-08-05 15:57:31 +0000 | [diff] [blame] | 2218 | |