| 1 |
Python 2.3 Quick Reference |
| 2 |
|
| 3 |
|
| 4 |
25 Jan 2003 upgraded by Raymond Hettinger for Python 2.3 |
| 5 |
16 May 2001 upgraded by Richard Gruet and Simon Brunning for Python 2.0 |
| 6 |
2000/07/18 upgraded by Richard Gruet, [email protected] for Python 1.5.2 |
| 7 |
from V1.3 ref |
| 8 |
1995/10/30, by Chris Hoffmann, [email protected] |
| 9 |
|
| 10 |
Based on: |
| 11 |
Python Bestiary, Author: Ken Manheimer, [email protected] |
| 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, [email protected] |
| 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: [email protected] |
| 22 |
Resources: http://starship.python.net/ |
| 23 |
http://www.vex.net/parnassus/ |
| 24 |
http://aspn.activestate.com/ASPN/Cookbook/Python |
| 25 |
FAQ: http://www.python.org/cgi-bin/faqw.py |
| 26 |
Full documentation: http://www.python.org/doc/ |
| 27 |
Excellent reference books: |
| 28 |
Python Essential Reference by David Beazley (New Riders) |
| 29 |
Python Pocket Reference by Mark Lutz (O'Reilly) |
| 30 |
|
| 31 |
|
| 32 |
Invocation Options |
| 33 |
|
| 34 |
python [-diOStuUvxX?] [-c command | script | - ] [args] |
| 35 |
|
| 36 |
Invocation Options |
| 37 |
Option Effect |
| 38 |
-c cmd program passed in as string (terminates option list) |
| 39 |
-d Outputs parser debugging information (also PYTHONDEBUG=x) |
| 40 |
-E ignore environment variables (such as PYTHONPATH) |
| 41 |
-h print this help message and exit |
| 42 |
-i Inspect interactively after running script (also PYTHONINSPECT=x) and |
| 43 |
force prompts, even if stdin appears not to be a terminal |
| 44 |
-m mod run library module as a script (terminates option list |
| 45 |
-O optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) |
| 46 |
-OO remove doc-strings in addition to the -O optimizations |
| 47 |
-Q arg division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew |
| 48 |
-S Don't perform 'import site' on initialization |
| 49 |
-t Issue warnings about inconsistent tab usage (-tt: issue errors) |
| 50 |
-u Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x). |
| 51 |
-v Verbose (trace import statements) (also PYTHONVERBOSE=x) |
| 52 |
-W arg : warning control (arg is action:message:category:module:lineno) |
| 53 |
-x Skip first line of source, allowing use of non-unix Forms of #!cmd |
| 54 |
-? Help! |
| 55 |
-3 warn about Python 3.x incompatibilities |
| 56 |
-c Specify the command to execute (see next section). This terminates the |
| 57 |
command option list (following options are passed as arguments to the command). |
| 58 |
the name of a python file (.py) to execute read from stdin. |
| 59 |
script Anything afterward is passed as options to python script or command, |
| 60 |
not interpreted as an option to interpreter itself. |
| 61 |
args passed to script or command (in sys.argv[1:]) |
| 62 |
If no script or command, Python enters interactive mode. |
| 63 |
|
| 64 |
* Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin |
| 65 |
(Windows). |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
Environment variables |
| 70 |
|
| 71 |
Environment variables |
| 72 |
Variable Effect |
| 73 |
PYTHONHOME Alternate prefix directory (or prefix;exec_prefix). The |
| 74 |
default module search path uses prefix/lib |
| 75 |
Augments the default search path for module files. The format |
| 76 |
is the same as the shell's $PATH: one or more directory |
| 77 |
pathnames separated by ':' or ';' without spaces around |
| 78 |
(semi-)colons! |
| 79 |
PYTHONPATH On Windows first search for Registry key HKEY_LOCAL_MACHINE\ |
| 80 |
Software\Python\PythonCore\x.y\PythonPath (default value). You |
| 81 |
may also define a key named after your application with a |
| 82 |
default string value giving the root directory path of your |
| 83 |
app. |
| 84 |
If this is the name of a readable file, the Python commands in |
| 85 |
PYTHONSTARTUP that file are executed before the first prompt is displayed in |
| 86 |
interactive mode (no default). |
| 87 |
PYTHONDEBUG If non-empty, same as -d option |
| 88 |
PYTHONINSPECT If non-empty, same as -i option |
| 89 |
PYTHONSUPPRESS If non-empty, same as -s option |
| 90 |
PYTHONUNBUFFERED If non-empty, same as -u option |
| 91 |
PYTHONVERBOSE If non-empty, same as -v option |
| 92 |
PYTHONCASEOK If non-empty, ignore case in file/module names (imports) |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
Notable lexical entities |
| 98 |
|
| 99 |
Keywords |
| 100 |
|
| 101 |
and del for is raise |
| 102 |
assert elif from lambda return |
| 103 |
break else global not try |
| 104 |
class except if or while |
| 105 |
continue exec import pass yield |
| 106 |
def finally in print |
| 107 |
|
| 108 |
* (list of keywords in std module: keyword) |
| 109 |
* Illegitimate Tokens (only valid in strings): @ $ ? |
| 110 |
* A statement must all be on a single line. To break a statement over |
| 111 |
multiple lines use "\", as with the C preprocessor. |
| 112 |
Exception: can always break when inside any (), [], or {} pair, or in |
| 113 |
triple-quoted strings. |
| 114 |
* More than one statement can appear on a line if they are separated with |
| 115 |
semicolons (";"). |
| 116 |
* Comments start with "#" and continue to end of line. |
| 117 |
|
| 118 |
Identifiers |
| 119 |
|
| 120 |
(letter | "_") (letter | digit | "_")* |
| 121 |
|
| 122 |
* Python identifiers keywords, attributes, etc. are case-sensitive. |
| 123 |
* Special forms: _ident (not imported by 'from module import *'); __ident__ |
| 124 |
(system defined name); |
| 125 |
__ident (class-private name mangling) |
| 126 |
|
| 127 |
Strings |
| 128 |
|
| 129 |
"a string enclosed by double quotes" |
| 130 |
'another string delimited by single quotes and with a " inside' |
| 131 |
'''a string containing embedded newlines and quote (') marks, can be |
| 132 |
delimited with triple quotes.''' |
| 133 |
""" may also use 3- double quotes as delimiters """ |
| 134 |
u'a unicode string' U"Another unicode string" |
| 135 |
r'a raw string where \ are kept (literalized): handy for regular |
| 136 |
expressions and windows paths!' |
| 137 |
R"another raw string" -- raw strings cannot end with a \ |
| 138 |
ur'a unicode raw string' UR"another raw unicode" |
| 139 |
|
| 140 |
Use \ at end of line to continue a string on next line. |
| 141 |
adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as |
| 142 |
'Monty Python'. |
| 143 |
u'hello' + ' world' --> u'hello world' (coerced to unicode) |
| 144 |
|
| 145 |
String Literal Escapes |
| 146 |
|
| 147 |
\newline Ignored (escape newline) |
| 148 |
\\ Backslash (\) \e Escape (ESC) \v Vertical Tab (VT) |
| 149 |
\' Single quote (') \f Formfeed (FF) \OOO char with octal value OOO |
| 150 |
\" Double quote (") \n Linefeed (LF) |
| 151 |
\a Bell (BEL) \r Carriage Return (CR) \xHH char with hex value HH |
| 152 |
\b Backspace (BS) \t Horizontal Tab (TAB) |
| 153 |
\uHHHH unicode char with hex value HHHH, can only be used in unicode string |
| 154 |
\UHHHHHHHH unicode char with hex value HHHHHHHH, can only be used in unicode string |
| 155 |
\AnyOtherChar is left as-is |
| 156 |
|
| 157 |
* NUL byte (\000) is NOT an end-of-string marker; NULs may be embedded in |
| 158 |
strings. |
| 159 |
* Strings (and tuples) are immutable: they cannot be modified. |
| 160 |
|
| 161 |
Numbers |
| 162 |
|
| 163 |
Decimal integer: 1234, 1234567890546378940L (or l) |
| 164 |
Octal integer: 0177, 0177777777777777777 (begin with a 0) |
| 165 |
Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFF (begin with 0x or 0X) |
| 166 |
Long integer (unlimited precision): 1234567890123456 |
| 167 |
Float (double precision): 3.14e-10, .001, 10., 1E3 |
| 168 |
Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and |
| 169 |
imaginary parts) |
| 170 |
|
| 171 |
Sequences |
| 172 |
|
| 173 |
* String of length 0, 1, 2 (see above) |
| 174 |
'', '1', "12", 'hello\n' |
| 175 |
* Tuple of length 0, 1, 2, etc: |
| 176 |
() (1,) (1,2) # parentheses are optional if len > 0 |
| 177 |
* List of length 0, 1, 2, etc: |
| 178 |
[] [1] [1,2] |
| 179 |
|
| 180 |
Indexing is 0-based. Negative indices (usually) mean count backwards from end |
| 181 |
of sequence. |
| 182 |
|
| 183 |
Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to |
| 184 |
'0'; End defaults to 'sequence-length'. |
| 185 |
|
| 186 |
a = (0,1,2,3,4,5,6,7) |
| 187 |
a[3] ==> 3 |
| 188 |
a[-1] ==> 7 |
| 189 |
a[2:4] ==> (2, 3) |
| 190 |
a[1:] ==> (1, 2, 3, 4, 5, 6, 7) |
| 191 |
a[:3] ==> (0, 1, 2) |
| 192 |
a[:] ==> (0,1,2,3,4,5,6,7) # makes a copy of the sequence. |
| 193 |
|
| 194 |
Dictionaries (Mappings) |
| 195 |
|
| 196 |
{} # Zero length empty dictionary |
| 197 |
{1 : 'first'} # Dictionary with one (key, value) pair |
| 198 |
{1 : 'first', 'next': 'second'} |
| 199 |
dict([('one',1),('two',2)]) # Construct a dict from an item list |
| 200 |
dict('one'=1, 'two'=2) # Construct a dict using keyword args |
| 201 |
dict.fromkeys(['one', 'keys']) # Construct a dict from a sequence |
| 202 |
|
| 203 |
Operators and their evaluation order |
| 204 |
|
| 205 |
Operators and their evaluation order |
| 206 |
Highest Operator Comment |
| 207 |
(...) [...] {...} `...` Tuple, list & dict. creation; string |
| 208 |
conv. |
| 209 |
s[i] s[i:j] s.attr f(...) indexing & slicing; attributes, fct |
| 210 |
calls |
| 211 |
+x, -x, ~x Unary operators |
| 212 |
x**y Power |
| 213 |
x*y x/y x%y x//y mult, division, modulo, floor division |
| 214 |
x+y x-y addition, subtraction |
| 215 |
x<<y x>>y Bit shifting |
| 216 |
x&y Bitwise and |
| 217 |
x^y Bitwise exclusive or |
| 218 |
x|y Bitwise or |
| 219 |
x<y x<=y x>y x>=y x==y x!=y Comparison, |
| 220 |
x<>y identity, |
| 221 |
x is y x is not y membership |
| 222 |
x in s x not in s |
| 223 |
not x boolean negation |
| 224 |
x and y boolean and |
| 225 |
x or y boolean or |
| 226 |
Lowest lambda args: expr anonymous function |
| 227 |
|
| 228 |
Alternate names are defined in module operator (e.g. __add__ and add for +) |
| 229 |
Most operators are overridable. |
| 230 |
|
| 231 |
Many binary operators also support augmented assignment: |
| 232 |
x += 1 # Same as x = x + 1 |
| 233 |
|
| 234 |
|
| 235 |
Basic Types and Their Operations |
| 236 |
|
| 237 |
Comparisons (defined between *any* types) |
| 238 |
|
| 239 |
Comparisons |
| 240 |
Comparison Meaning Notes |
| 241 |
< strictly less than (1) |
| 242 |
<= less than or equal to |
| 243 |
> strictly greater than |
| 244 |
>= greater than or equal to |
| 245 |
== equal to |
| 246 |
!= or <> not equal to |
| 247 |
is object identity (2) |
| 248 |
is not negated object identity (2) |
| 249 |
|
| 250 |
Notes : |
| 251 |
Comparison behavior can be overridden for a given class by defining special |
| 252 |
method __cmp__. |
| 253 |
The above comparisons return True or False which are of type bool |
| 254 |
(a subclass of int) and behave exactly as 1 or 0 except for their type and |
| 255 |
that they print as True or False instead of 1 or 0. |
| 256 |
(1) X < Y < Z < W has expected meaning, unlike C |
| 257 |
(2) Compare object identities (i.e. id(object)), not object values. |
| 258 |
|
| 259 |
Boolean values and operators |
| 260 |
|
| 261 |
Boolean values and operators |
| 262 |
Value or Operator Returns Notes |
| 263 |
None, numeric zeros, empty sequences and False |
| 264 |
mappings |
| 265 |
all other values True |
| 266 |
not x True if x is False, else |
| 267 |
True |
| 268 |
x or y if x is False then y, else (1) |
| 269 |
x |
| 270 |
x and y if x is False then x, else (1) |
| 271 |
y |
| 272 |
|
| 273 |
Notes : |
| 274 |
Truth testing behavior can be overridden for a given class by defining |
| 275 |
special method __nonzero__. |
| 276 |
(1) Evaluate second arg only if necessary to determine outcome. |
| 277 |
|
| 278 |
None |
| 279 |
|
| 280 |
None is used as default return value on functions. Built-in single object |
| 281 |
with type NoneType. |
| 282 |
Input that evaluates to None does not print when running Python |
| 283 |
interactively. |
| 284 |
|
| 285 |
Numeric types |
| 286 |
|
| 287 |
Floats, integers and long integers. |
| 288 |
|
| 289 |
Floats are implemented with C doubles. |
| 290 |
Integers are implemented with C longs. |
| 291 |
Long integers have unlimited size (only limit is system resources) |
| 292 |
|
| 293 |
Operators on all numeric types |
| 294 |
|
| 295 |
Operators on all numeric types |
| 296 |
Operation Result |
| 297 |
abs(x) the absolute value of x |
| 298 |
int(x) x converted to integer |
| 299 |
long(x) x converted to long integer |
| 300 |
float(x) x converted to floating point |
| 301 |
-x x negated |
| 302 |
+x x unchanged |
| 303 |
x + y the sum of x and y |
| 304 |
x - y difference of x and y |
| 305 |
x * y product of x and y |
| 306 |
x / y quotient of x and y |
| 307 |
x % y remainder of x / y |
| 308 |
divmod(x, y) the tuple (x/y, x%y) |
| 309 |
x ** y x to the power y (the same as pow(x, y)) |
| 310 |
|
| 311 |
Bit operators on integers and long integers |
| 312 |
|
| 313 |
Bit operators |
| 314 |
Operation >Result |
| 315 |
~x the bits of x inverted |
| 316 |
x ^ y bitwise exclusive or of x and y |
| 317 |
x & y bitwise and of x and y |
| 318 |
x | y bitwise or of x and y |
| 319 |
x << n x shifted left by n bits |
| 320 |
x >> n x shifted right by n bits |
| 321 |
|
| 322 |
Complex Numbers |
| 323 |
|
| 324 |
* represented as a pair of machine-level double precision floating point |
| 325 |
numbers. |
| 326 |
* The real and imaginary value of a complex number z can be retrieved through |
| 327 |
the attributes z.real and z.imag. |
| 328 |
|
| 329 |
Numeric exceptions |
| 330 |
|
| 331 |
TypeError |
| 332 |
raised on application of arithmetic operation to non-number |
| 333 |
OverflowError |
| 334 |
numeric bounds exceeded |
| 335 |
ZeroDivisionError |
| 336 |
raised when zero second argument of div or modulo op |
| 337 |
FloatingPointError |
| 338 |
raised when a floating point operation fails |
| 339 |
|
| 340 |
Operations on all sequence types (lists, tuples, strings) |
| 341 |
|
| 342 |
Operations on all sequence types |
| 343 |
Operation Result Notes |
| 344 |
x in s True if an item of s is equal to x, else False |
| 345 |
x not in s False if an item of s is equal to x, else True |
| 346 |
for x in s: loops over the sequence |
| 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 |
iter(s) returns an iterator over s. iterators define __iter__ and next() |
| 355 |
|
| 356 |
Notes : |
| 357 |
(1) if i or j is negative, the index is relative to the end of the string, |
| 358 |
ie len(s)+ i or len(s)+j is |
| 359 |
substituted. But note that -0 is still 0. |
| 360 |
(2) The slice of s from i to j is defined as the sequence of items with |
| 361 |
index k such that i <= k < j. |
| 362 |
If i or j is greater than len(s), use len(s). If i is omitted, use |
| 363 |
len(s). If i is greater than or |
| 364 |
equal to j, the slice is empty. |
| 365 |
|
| 366 |
Operations on mutable (=modifiable) sequences (lists) |
| 367 |
|
| 368 |
Operations on mutable sequences |
| 369 |
Operation Result Notes |
| 370 |
s[i] =x item i of s is replaced by x |
| 371 |
s[i:j] = t slice of s from i to j is replaced by t |
| 372 |
del s[i:j] same as s[i:j] = [] |
| 373 |
s.append(x) same as s[len(s) : len(s)] = [x] |
| 374 |
s.count(x) return number of i's for which s[i] == x |
| 375 |
s.extend(x) same as s[len(s):len(s)]= x |
| 376 |
s.index(x) return smallest i such that s[i] == x (1) |
| 377 |
s.insert(i, x) same as s[i:i] = [x] if i >= 0 |
| 378 |
s.pop([i]) same as x = s[i]; del s[i]; return x (4) |
| 379 |
s.remove(x) same as del s[s.index(x)] (1) |
| 380 |
s.reverse() reverse the items of s in place (3) |
| 381 |
s.sort([cmpFct]) sort the items of s in place (2), (3) |
| 382 |
|
| 383 |
Notes : |
| 384 |
(1) raise a ValueError exception when x is not found in s (i.e. out of |
| 385 |
range). |
| 386 |
(2) The sort() method takes an optional argument specifying a comparison |
| 387 |
fct of 2 arguments (list items) which should |
| 388 |
return -1, 0, or 1 depending on whether the 1st argument is |
| 389 |
considered smaller than, equal to, or larger than the 2nd |
| 390 |
argument. Note that this slows the sorting process down considerably. |
| 391 |
(3) The sort() and reverse() methods modify the list in place for economy |
| 392 |
of space when sorting or reversing a large list. |
| 393 |
They don't return the sorted or reversed list to remind you of this |
| 394 |
side effect. |
| 395 |
(4) [New 1.5.2] The optional argument i defaults to -1, so that by default the last |
| 396 |
item is removed and returned. |
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
Operations on mappings (dictionaries) |
| 401 |
|
| 402 |
Operations on mappings |
| 403 |
Operation Result Notes |
| 404 |
len(d) the number of items in d |
| 405 |
d[k] the item of d with key k (1) |
| 406 |
d[k] = x set d[k] to x |
| 407 |
del d[k] remove d[k] from d (1) |
| 408 |
d.clear() remove all items from d |
| 409 |
d.copy() a shallow copy of d |
| 410 |
d.get(k,defaultval) the item of d with key k (4) |
| 411 |
d.has_key(k) True if d has key k, else False |
| 412 |
d.items() a copy of d's list of (key, item) pairs (2) |
| 413 |
d.iteritems() an iterator over (key, value) pairs (7) |
| 414 |
d.iterkeys() an iterator over the keys of d (7) |
| 415 |
d.itervalues() an iterator over the values of d (7) |
| 416 |
d.keys() a copy of d's list of keys (2) |
| 417 |
d1.update(d2) for k, v in d2.items(): d1[k] = v (3) |
| 418 |
d.values() a copy of d's list of values (2) |
| 419 |
d.pop(k) remove d[k] and return its value |
| 420 |
d.popitem() remove and return an arbitrary (6) |
| 421 |
(key, item) pair |
| 422 |
d.setdefault(k,defaultval) the item of d with key k (5) |
| 423 |
|
| 424 |
Notes : |
| 425 |
TypeError is raised if key is not acceptable |
| 426 |
(1) KeyError is raised if key k is not in the map |
| 427 |
(2) Keys and values are listed in random order |
| 428 |
(3) d2 must be of the same type as d1 |
| 429 |
(4) Never raises an exception if k is not in the map, instead it returns |
| 430 |
defaultVal. |
| 431 |
defaultVal is optional, when not provided and k is not in the map, |
| 432 |
None is returned. |
| 433 |
(5) Never raises an exception if k is not in the map, instead it returns |
| 434 |
defaultVal, and adds k to map with value defaultVal. defaultVal is |
| 435 |
optional. When not provided and k is not in the map, None is returned and |
| 436 |
added to map. |
| 437 |
(6) Raises a KeyError if the dictionary is empty. |
| 438 |
(7) While iterating over a dictionary, the values may be updated but |
| 439 |
the keys cannot be changed. |
| 440 |
|
| 441 |
Operations on strings |
| 442 |
|
| 443 |
Note that these string methods largely (but not completely) supersede the |
| 444 |
functions available in the string module. |
| 445 |
|
| 446 |
|
| 447 |
Operations on strings |
| 448 |
Operation Result Notes |
| 449 |
s.capitalize() return a copy of s with only its first character |
| 450 |
capitalized. |
| 451 |
s.center(width) return a copy of s centered in a string of length width (1) |
| 452 |
. |
| 453 |
s.count(sub[ return the number of occurrences of substring sub in (2) |
| 454 |
,start[,end]]) string s. |
| 455 |
s.decode(([ return a decoded version of s. (3) |
| 456 |
encoding |
| 457 |
[,errors]]) |
| 458 |
s.encode([ return an encoded version of s. Default encoding is the |
| 459 |
encoding current default string encoding. (3) |
| 460 |
[,errors]]) |
| 461 |
s.endswith(suffix return true if s ends with the specified suffix, (2) |
| 462 |
[,start[,end]]) otherwise return False. |
| 463 |
s.expandtabs([ return a copy of s where all tab characters are (4) |
| 464 |
tabsize]) expanded using spaces. |
| 465 |
s.find(sub[,start return the lowest index in s where substring sub is (2) |
| 466 |
[,end]]) found. Return -1 if sub is not found. |
| 467 |
s.index(sub[ like find(), but raise ValueError when the substring is (2) |
| 468 |
,start[,end]]) not found. |
| 469 |
s.isalnum() return True if all characters in s are alphanumeric, (5) |
| 470 |
False otherwise. |
| 471 |
s.isalpha() return True if all characters in s are alphabetic, (5) |
| 472 |
False otherwise. |
| 473 |
s.isdigit() return True if all characters in s are digit (5) |
| 474 |
characters, False otherwise. |
| 475 |
s.islower() return True if all characters in s are lowercase, False (6) |
| 476 |
otherwise. |
| 477 |
s.isspace() return True if all characters in s are whitespace (5) |
| 478 |
characters, False otherwise. |
| 479 |
s.istitle() return True if string s is a titlecased string, False (7) |
| 480 |
otherwise. |
| 481 |
s.isupper() return True if all characters in s are uppercase, False (6) |
| 482 |
otherwise. |
| 483 |
s.join(seq) return a concatenation of the strings in the sequence |
| 484 |
seq, separated by 's's. |
| 485 |
s.ljust(width) return s left justified in a string of length width. (1), |
| 486 |
(8) |
| 487 |
s.lower() return a copy of s converted to lowercase. |
| 488 |
s.lstrip() return a copy of s with leading whitespace removed. |
| 489 |
s.replace(old, return a copy of s with all occurrences of substring (9) |
| 490 |
new[, maxsplit]) old replaced by new. |
| 491 |
s.rfind(sub[ return the highest index in s where substring sub is (2) |
| 492 |
,start[,end]]) found. Return -1 if sub is not found. |
| 493 |
s.rindex(sub[ like rfind(), but raise ValueError when the substring (2) |
| 494 |
,start[,end]]) is not found. |
| 495 |
s.rjust(width) return s right justified in a string of length width. (1), |
| 496 |
(8) |
| 497 |
s.rstrip() return a copy of s with trailing whitespace removed. |
| 498 |
s.split([sep[ return a list of the words in s, using sep as the (10) |
| 499 |
,maxsplit]]) delimiter string. |
| 500 |
s.splitlines([ return a list of the lines in s, breaking at line (11) |
| 501 |
keepends]) boundaries. |
| 502 |
s.startswith return true if s starts with the specified prefix, |
| 503 |
(prefix[,start[ otherwise return false. (2) |
| 504 |
,end]]) |
| 505 |
s.strip() return a copy of s with leading and trailing whitespace |
| 506 |
removed. |
| 507 |
s.swapcase() return a copy of s with uppercase characters converted |
| 508 |
to lowercase and vice versa. |
| 509 |
return a titlecased copy of s, i.e. words start with |
| 510 |
s.title() uppercase characters, all remaining cased characters |
| 511 |
are lowercase. |
| 512 |
s.translate(table return a copy of s mapped through translation table (12) |
| 513 |
[,deletechars]) table. |
| 514 |
s.upper() return a copy of s converted to uppercase. |
| 515 |
s.zfill(width) return a string padded with zeroes on the left side and |
| 516 |
sliding a minus sign left if necessary. never truncates. |
| 517 |
|
| 518 |
Notes : |
| 519 |
(1) Padding is done using spaces. |
| 520 |
(2) If optional argument start is supplied, substring s[start:] is |
| 521 |
processed. If optional arguments start and end are supplied, substring s[start: |
| 522 |
end] is processed. |
| 523 |
(3) Optional argument errors may be given to set a different error handling |
| 524 |
scheme. The default for errors is 'strict', meaning that encoding errors raise |
| 525 |
a ValueError. Other possible values are 'ignore' and 'replace'. |
| 526 |
(4) If optional argument tabsize is not given, a tab size of 8 characters |
| 527 |
is assumed. |
| 528 |
(5) Returns false if string s does not contain at least one character. |
| 529 |
(6) Returns false if string s does not contain at least one cased |
| 530 |
character. |
| 531 |
(7) A titlecased string is a string in which uppercase characters may only |
| 532 |
follow uncased characters and lowercase characters only cased ones. |
| 533 |
(8) s is returned if width is less than len(s). |
| 534 |
(9) If the optional argument maxsplit is given, only the first maxsplit |
| 535 |
occurrences are replaced. |
| 536 |
(10) If sep is not specified or None, any whitespace string is a separator. |
| 537 |
If maxsplit is given, at most maxsplit splits are done. |
| 538 |
(11) Line breaks are not included in the resulting list unless keepends is |
| 539 |
given and true. |
| 540 |
(12) table must be a string of length 256. All characters occurring in the |
| 541 |
optional argument deletechars are removed prior to translation. |
| 542 |
|
| 543 |
String formatting with the % operator |
| 544 |
|
| 545 |
formatString % args--> evaluates to a string |
| 546 |
|
| 547 |
* formatString uses C printf format codes : %, c, s, i, d, u, o, x, X, e, E, |
| 548 |
f, g, G, r (details below). |
| 549 |
* Width and precision may be a * to specify that an integer argument gives |
| 550 |
the actual width or precision. |
| 551 |
* The flag characters -, +, blank, # and 0 are understood. (details below) |
| 552 |
* %s will convert any type argument to string (uses str() function) |
| 553 |
* args may be a single arg or a tuple of args |
| 554 |
|
| 555 |
'%s has %03d quote types.' % ('Python', 2) # => 'Python has 002 quote types.' |
| 556 |
|
| 557 |
* Right-hand-side can also be a mapping: |
| 558 |
|
| 559 |
a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python} |
| 560 |
(vars() function very handy to use on right-hand-side.) |
| 561 |
|
| 562 |
Format codes |
| 563 |
Conversion Meaning |
| 564 |
d Signed integer decimal. |
| 565 |
i Signed integer decimal. |
| 566 |
o Unsigned octal. |
| 567 |
u Unsigned decimal. |
| 568 |
x Unsigned hexadecimal (lowercase). |
| 569 |
X Unsigned hexadecimal (uppercase). |
| 570 |
e Floating point exponential format (lowercase). |
| 571 |
E Floating point exponential format (uppercase). |
| 572 |
f Floating point decimal format. |
| 573 |
F Floating point decimal format. |
| 574 |
g Same as "e" if exponent is greater than -4 or less than precision, |
| 575 |
"f" otherwise. |
| 576 |
G Same as "E" if exponent is greater than -4 or less than precision, |
| 577 |
"F" otherwise. |
| 578 |
c Single character (accepts integer or single character string). |
| 579 |
r String (converts any python object using repr()). |
| 580 |
s String (converts any python object using str()). |
| 581 |
% No argument is converted, results in a "%" character in the result. |
| 582 |
(The complete specification is %%.) |
| 583 |
|
| 584 |
Conversion flag characters |
| 585 |
Flag Meaning |
| 586 |
# The value conversion will use the ``alternate form''. |
| 587 |
0 The conversion will be zero padded. |
| 588 |
- The converted value is left adjusted (overrides "-"). |
| 589 |
(a space) A blank should be left before a positive number (or empty |
| 590 |
string) produced by a signed conversion. |
| 591 |
+ A sign character ("+" or "-") will precede the conversion (overrides a |
| 592 |
"space" flag). |
| 593 |
|
| 594 |
File Objects |
| 595 |
|
| 596 |
Created with built-in function open; may be created by other modules' functions |
| 597 |
as well. |
| 598 |
|
| 599 |
Operators on file objects |
| 600 |
|
| 601 |
File operations |
| 602 |
Operation Result |
| 603 |
f.close() Close file f. |
| 604 |
f.fileno() Get fileno (fd) for file f. |
| 605 |
f.flush() Flush file f's internal buffer. |
| 606 |
f.isatty() True if file f is connected to a tty-like dev, else False. |
| 607 |
f.read([size]) Read at most size bytes from file f and return as a string |
| 608 |
object. If size omitted, read to EOF. |
| 609 |
f.readline() Read one entire line from file f. |
| 610 |
f.readlines() Read until EOF with readline() and return list of lines read. |
| 611 |
Set file f's position, like "stdio's fseek()". |
| 612 |
f.seek(offset[, whence == 0 then use absolute indexing. |
| 613 |
whence=0]) whence == 1 then offset relative to current pos. |
| 614 |
whence == 2 then offset relative to file end. |
| 615 |
f.tell() Return file f's current position (byte offset). |
| 616 |
f.write(str) Write string to file f. |
| 617 |
f.writelines(list Write list of strings to file f. |
| 618 |
) |
| 619 |
|
| 620 |
File Exceptions |
| 621 |
|
| 622 |
EOFError |
| 623 |
End-of-file hit when reading (may be raised many times, e.g. if f is a |
| 624 |
tty). |
| 625 |
IOError |
| 626 |
Other I/O-related I/O operation failure. |
| 627 |
OSError |
| 628 |
OS system call failed. |
| 629 |
|
| 630 |
|
| 631 |
Advanced Types |
| 632 |
|
| 633 |
-See manuals for more details - |
| 634 |
+ Module objects |
| 635 |
+ Class objects |
| 636 |
+ Class instance objects |
| 637 |
+ Type objects (see module: types) |
| 638 |
+ File objects (see above) |
| 639 |
+ Slice objects |
| 640 |
+ XRange objects |
| 641 |
+ Callable types: |
| 642 |
o User-defined (written in Python): |
| 643 |
# User-defined Function objects |
| 644 |
# User-defined Method objects |
| 645 |
o Built-in (written in C): |
| 646 |
# Built-in Function objects |
| 647 |
# Built-in Method objects |
| 648 |
+ Internal Types: |
| 649 |
o Code objects (byte-compile executable Python code: bytecode) |
| 650 |
o Frame objects (execution frames) |
| 651 |
o Traceback objects (stack trace of an exception) |
| 652 |
|
| 653 |
|
| 654 |
Statements |
| 655 |
|
| 656 |
pass -- Null statement |
| 657 |
del name[,name]* -- Unbind name(s) from object. Object will be indirectly |
| 658 |
(and automatically) deleted only if no longer referenced. |
| 659 |
print [>> fileobject,] [s1 [, s2 ]* [,] |
| 660 |
-- Writes to sys.stdout, or to fileobject if supplied. |
| 661 |
Puts spaces between arguments. Puts newline at end |
| 662 |
unless statement ends with comma. |
| 663 |
Print is not required when running interactively, |
| 664 |
simply typing an expression will print its value, |
| 665 |
unless the value is None. |
| 666 |
exec x [in globals [,locals]] |
| 667 |
-- Executes x in namespaces provided. Defaults |
| 668 |
to current namespaces. x can be a string, file |
| 669 |
object or a function object. |
| 670 |
callable(value,... [id=value], [*args], [**kw]) |
| 671 |
-- Call function callable with parameters. Parameters can |
| 672 |
be passed by name or be omitted if function |
| 673 |
defines default values. E.g. if callable is defined as |
| 674 |
"def callable(p1=1, p2=2)" |
| 675 |
"callable()" <=> "callable(1, 2)" |
| 676 |
"callable(10)" <=> "callable(10, 2)" |
| 677 |
"callable(p2=99)" <=> "callable(1, 99)" |
| 678 |
*args is a tuple of positional arguments. |
| 679 |
**kw is a dictionary of keyword arguments. |
| 680 |
|
| 681 |
Assignment operators |
| 682 |
|
| 683 |
Caption |
| 684 |
Operator Result Notes |
| 685 |
a = b Basic assignment - assign object b to label a (1) |
| 686 |
a += b Roughly equivalent to a = a + b (2) |
| 687 |
a -= b Roughly equivalent to a = a - b (2) |
| 688 |
a *= b Roughly equivalent to a = a * b (2) |
| 689 |
a /= b Roughly equivalent to a = a / b (2) |
| 690 |
a %= b Roughly equivalent to a = a % b (2) |
| 691 |
a **= b Roughly equivalent to a = a ** b (2) |
| 692 |
a &= b Roughly equivalent to a = a & b (2) |
| 693 |
a |= b Roughly equivalent to a = a | b (2) |
| 694 |
a ^= b Roughly equivalent to a = a ^ b (2) |
| 695 |
a >>= b Roughly equivalent to a = a >> b (2) |
| 696 |
a <<= b Roughly equivalent to a = a << b (2) |
| 697 |
|
| 698 |
Notes : |
| 699 |
(1) Can unpack tuples, lists, and strings. |
| 700 |
first, second = a[0:2]; [f, s] = range(2); c1,c2,c3='abc' |
| 701 |
Tip: x,y = y,x swaps x and y. |
| 702 |
(2) Not exactly equivalent - a is evaluated only once. Also, where |
| 703 |
possible, operation performed in-place - a is modified rather than |
| 704 |
replaced. |
| 705 |
|
| 706 |
Control Flow |
| 707 |
|
| 708 |
if condition: suite |
| 709 |
[elif condition: suite]* |
| 710 |
[else: suite] -- usual if/else_if/else statement |
| 711 |
while condition: suite |
| 712 |
[else: suite] |
| 713 |
-- usual while statement. "else" suite is executed |
| 714 |
after loop exits, unless the loop is exited with |
| 715 |
"break" |
| 716 |
for element in sequence: suite |
| 717 |
[else: suite] |
| 718 |
-- iterates over sequence, assigning each element to element. |
| 719 |
Use built-in range function to iterate a number of times. |
| 720 |
"else" suite executed at end unless loop exited |
| 721 |
with "break" |
| 722 |
break -- immediately exits "for" or "while" loop |
| 723 |
continue -- immediately does next iteration of "for" or "while" loop |
| 724 |
return [result] -- Exits from function (or method) and returns result (use a tuple to |
| 725 |
return more than one value). If no result given, then returns None. |
| 726 |
yield result -- Freezes the execution frame of a generator and returns the result |
| 727 |
to the iterator's .next() method. Upon the next call to next(), |
| 728 |
resumes execution at the frozen point with all of the local variables |
| 729 |
still intact. |
| 730 |
|
| 731 |
Exception Statements |
| 732 |
|
| 733 |
assert expr[, message] |
| 734 |
-- expr is evaluated. if false, raises exception AssertionError |
| 735 |
with message. Inhibited if __debug__ is 0. |
| 736 |
try: suite1 |
| 737 |
[except [exception [, value]: suite2]+ |
| 738 |
[else: suite3] |
| 739 |
-- statements in suite1 are executed. If an exception occurs, look |
| 740 |
in "except" clauses for matching <exception>. If matches or bare |
| 741 |
"except" execute suite of that clause. If no exception happens |
| 742 |
suite in "else" clause is executed after suite1. |
| 743 |
If exception has a value, it is put in value. |
| 744 |
exception can also be tuple of exceptions, e.g. |
| 745 |
"except (KeyError, NameError), val: print val" |
| 746 |
try: suite1 |
| 747 |
finally: suite2 |
| 748 |
-- statements in suite1 are executed. If no |
| 749 |
exception, execute suite2 (even if suite1 is |
| 750 |
exited with a "return", "break" or "continue" |
| 751 |
statement). If exception did occur, executes |
| 752 |
suite2 and then immediately reraises exception. |
| 753 |
raise exception [,value [, traceback]] |
| 754 |
-- raises exception with optional value |
| 755 |
value. Arg traceback specifies a traceback object to |
| 756 |
use when printing the exception's backtrace. |
| 757 |
raise -- a raise statement without arguments re-raises |
| 758 |
the last exception raised in the current function |
| 759 |
An exception is either a string (object) or a class instance. |
| 760 |
Can create a new one simply by creating a new string: |
| 761 |
|
| 762 |
my_exception = 'You did something wrong' |
| 763 |
try: |
| 764 |
if bad: |
| 765 |
raise my_exception, bad |
| 766 |
except my_exception, value: |
| 767 |
print 'Oops', value |
| 768 |
|
| 769 |
Exception classes must be derived from the predefined class: Exception, e.g.: |
| 770 |
class text_exception(Exception): pass |
| 771 |
try: |
| 772 |
if bad: |
| 773 |
raise text_exception() |
| 774 |
# This is a shorthand for the form |
| 775 |
# "raise <class>, <instance>" |
| 776 |
except Exception: |
| 777 |
print 'Oops' |
| 778 |
# This will be printed because |
| 779 |
# text_exception is a subclass of Exception |
| 780 |
When an error message is printed for an unhandled exception which is a |
| 781 |
class, the class name is printed, then a colon and a space, and |
| 782 |
finally the instance converted to a string using the built-in function |
| 783 |
str(). |
| 784 |
All built-in exception classes derives from StandardError, itself |
| 785 |
derived from Exception. |
| 786 |
|
| 787 |
Name Space Statements |
| 788 |
|
| 789 |
[1.51: On Mac & Windows, the case of module file names must now match the case |
| 790 |
as used |
| 791 |
in the import statement] |
| 792 |
Packages (>1.5): a package is a name space which maps to a directory including |
| 793 |
module(s) and the special initialization module '__init__.py' |
| 794 |
(possibly empty). Packages/dirs can be nested. You address a |
| 795 |
module's symbol via '[package.[package...]module.symbol's. |
| 796 |
import module1 [as name1] [, module2]* |
| 797 |
-- imports modules. Members of module must be |
| 798 |
referred to by qualifying with [package.]module name: |
| 799 |
"import sys; print sys.argv:" |
| 800 |
"import package1.subpackage.module; package1.subpackage.module.foo()" |
| 801 |
module1 renamed as name1, if supplied. |
| 802 |
from module import name1 [as othername1] [, name2]* |
| 803 |
-- imports names from module module in current namespace. |
| 804 |
"from sys import argv; print argv" |
| 805 |
"from package1 import module; module.foo()" |
| 806 |
"from package1.module import foo; foo()" |
| 807 |
name1 renamed as othername1, if supplied. |
| 808 |
from module import * |
| 809 |
-- imports all names in module, except those starting with "_"; |
| 810 |
*to be used sparsely, beware of name clashes* : |
| 811 |
"from sys import *; print argv" |
| 812 |
"from package.module import *; print x' |
| 813 |
NB: "from package import *" only imports the symbols defined |
| 814 |
in the package's __init__.py file, not those in the |
| 815 |
template modules! |
| 816 |
global name1 [, name2]* |
| 817 |
-- names are from global scope (usually meaning from module) |
| 818 |
rather than local (usually meaning only in function). |
| 819 |
-- E.g. in fct without "global" statements, assuming |
| 820 |
"a" is name that hasn't been used in fct or module |
| 821 |
so far: |
| 822 |
-Try to read from "a" -> NameError |
| 823 |
-Try to write to "a" -> creates "a" local to fcn |
| 824 |
-If "a" not defined in fct, but is in module, then |
| 825 |
-Try to read from "a", gets value from module |
| 826 |
-Try to write to "a", creates "a" local to fct |
| 827 |
But note "a[0]=3" starts with search for "a", |
| 828 |
will use to global "a" if no local "a". |
| 829 |
|
| 830 |
Function Definition |
| 831 |
|
| 832 |
def func_id ([param_list]): suite |
| 833 |
-- Creates a function object & binds it to name func_id. |
| 834 |
|
| 835 |
param_list ::= [id [, id]*] |
| 836 |
id ::= value | id = value | *id | **id |
| 837 |
[Args are passed by value.Thus only args representing a mutable object |
| 838 |
can be modified (are inout parameters). Use a tuple to return more than |
| 839 |
one value] |
| 840 |
|
| 841 |
Example: |
| 842 |
def test (p1, p2 = 1+1, *rest, **keywords): |
| 843 |
-- Parameters with "=" have default value (v is |
| 844 |
evaluated when function defined). |
| 845 |
If list has "*id" then id is assigned a tuple of |
| 846 |
all remaining args passed to function (like C vararg) |
| 847 |
If list has "**id" then id is assigned a dictionary of |
| 848 |
all extra arguments passed as keywords. |
| 849 |
|
| 850 |
Class Definition |
| 851 |
|
| 852 |
class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite> |
| 853 |
-- Creates a class object and assigns it name <class_id> |
| 854 |
<suite> may contain local "defs" of class methods and |
| 855 |
assignments to class attributes. |
| 856 |
Example: |
| 857 |
class my_class (class1, class_list[3]): ... |
| 858 |
Creates a class object inheriting from both "class1" and whatever |
| 859 |
class object "class_list[3]" evaluates to. Assigns new |
| 860 |
class object to name "my_class". |
| 861 |
- First arg to class methods is always instance object, called 'self' |
| 862 |
by convention. |
| 863 |
- Special method __init__() is called when instance is created. |
| 864 |
- Special method __del__() called when no more reference to object. |
| 865 |
- Create instance by "calling" class object, possibly with arg |
| 866 |
(thus instance=apply(aClassObject, args...) creates an instance!) |
| 867 |
- In current implementation, can't subclass off built-in |
| 868 |
classes. But can "wrap" them, see UserDict & UserList modules, |
| 869 |
and see __getattr__() below. |
| 870 |
Example: |
| 871 |
class c (c_parent): |
| 872 |
def __init__(self, name): self.name = name |
| 873 |
def print_name(self): print "I'm", self.name |
| 874 |
def call_parent(self): c_parent.print_name(self) |
| 875 |
instance = c('tom') |
| 876 |
print instance.name |
| 877 |
'tom' |
| 878 |
instance.print_name() |
| 879 |
"I'm tom" |
| 880 |
Call parent's super class by accessing parent's method |
| 881 |
directly and passing "self" explicitly (see "call_parent" |
| 882 |
in example above). |
| 883 |
Many other special methods available for implementing |
| 884 |
arithmetic operators, sequence, mapping indexing, etc. |
| 885 |
|
| 886 |
Documentation Strings |
| 887 |
|
| 888 |
Modules, classes and functions may be documented by placing a string literal by |
| 889 |
itself as the first statement in the suite. The documentation can be retrieved |
| 890 |
by getting the '__doc__' attribute from the module, class or function. |
| 891 |
Example: |
| 892 |
class C: |
| 893 |
"A description of C" |
| 894 |
def __init__(self): |
| 895 |
"A description of the constructor" |
| 896 |
# etc. |
| 897 |
Then c.__doc__ == "A description of C". |
| 898 |
Then c.__init__.__doc__ == "A description of the constructor". |
| 899 |
|
| 900 |
Others |
| 901 |
|
| 902 |
lambda [param_list]: returnedExpr |
| 903 |
-- Creates an anonymous function. returnedExpr must be |
| 904 |
an expression, not a statement (e.g., not "if xx:...", |
| 905 |
"print xxx", etc.) and thus can't contain newlines. |
| 906 |
Used mostly for filter(), map(), reduce() functions, and GUI callbacks.. |
| 907 |
List comprehensions |
| 908 |
result = [expression for item1 in sequence1 [if condition1] |
| 909 |
[for item2 in sequence2 ... for itemN in sequenceN] |
| 910 |
] |
| 911 |
is equivalent to: |
| 912 |
result = [] |
| 913 |
for item1 in sequence1: |
| 914 |
for item2 in sequence2: |
| 915 |
... |
| 916 |
for itemN in sequenceN: |
| 917 |
if (condition1) and furthur conditions: |
| 918 |
result.append(expression) |
| 919 |
|
| 920 |
|
| 921 |
|
| 922 |
Built-In Functions |
| 923 |
|
| 924 |
Built-In Functions |
| 925 |
Function Result |
| 926 |
__import__(name[, Imports module within the given context (see lib ref for |
| 927 |
globals[, locals[, more details) |
| 928 |
fromlist]]]) |
| 929 |
abs(x) Return the absolute value of number x. |
| 930 |
apply(f, args[, Calls func/method f with arguments args and optional |
| 931 |
keywords]) keywords. |
| 932 |
bool(x) Returns True when the argument x is true and False otherwise. |
| 933 |
buffer(obj) Creates a buffer reference to an object. |
| 934 |
callable(x) Returns True if x callable, else False. |
| 935 |
chr(i) Returns one-character string whose ASCII code isinteger i |
| 936 |
classmethod(f) Converts a function f, into a method with the class as the |
| 937 |
first argument. Useful for creating alternative constructors. |
| 938 |
cmp(x,y) Returns negative, 0, positive if x <, ==, > to y |
| 939 |
coerce(x,y) Returns a tuple of the two numeric arguments converted to a |
| 940 |
common type. |
| 941 |
Compiles string into a code object.filename is used in |
| 942 |
error message, can be any string. It isusually the file |
| 943 |
compile(string, from which the code was read, or eg. '<string>'if not read |
| 944 |
filename, kind) from file.kind can be 'eval' if string is a single stmt, or |
| 945 |
'single' which prints the output of expression statements |
| 946 |
thatevaluate to something else than None, or be 'exec'. |
| 947 |
complex(real[, Builds a complex object (can also be done using J or j |
| 948 |
image]) suffix,e.g. 1+3J) |
| 949 |
delattr(obj, name) deletes attribute named name of object obj <=> del obj.name |
| 950 |
If no args, returns the list of names in current |
| 951 |
dict([items]) Create a new dictionary from the specified item list. |
| 952 |
dir([object]) localsymbol table. With a module, class or class |
| 953 |
instanceobject as arg, returns list of names in its attr. |
| 954 |
dict. |
| 955 |
divmod(a,b) Returns tuple of (a/b, a%b) |
| 956 |
enumerate(seq) Return an iterator giving: (0, seq[0]), (1, seq[1]), ... |
| 957 |
eval(s[, globals[, Eval string s in (optional) globals, locals contexts.s must |
| 958 |
locals]]) have no NUL's or newlines. s can also be acode object. |
| 959 |
Example: x = 1; incr_x = eval('x + 1') |
| 960 |
execfile(file[, Executes a file without creating a new module, unlike |
| 961 |
globals[, locals]]) import. |
| 962 |
file() Synonym for open(). |
| 963 |
filter(function, Constructs a list from those elements of sequence for which |
| 964 |
sequence) function returns true. function takes one parameter. |
| 965 |
float(x) Converts a number or a string to floating point. |
| 966 |
getattr(object, [<default> arg added in 1.5.2]Gets attribute called name |
| 967 |
name[, default])) from object,e.g. getattr(x, 'f') <=> x.f). If not found, |
| 968 |
raisesAttributeError or returns default if specified. |
| 969 |
globals() Returns a dictionary containing current global variables. |
| 970 |
hasattr(object, Returns true if object has attr called name. |
| 971 |
name) |
| 972 |
hash(object) Returns the hash value of the object (if it has one) |
| 973 |
help(f) Display documentation on object f. |
| 974 |
hex(x) Converts a number x to a hexadecimal string. |
| 975 |
id(object) Returns a unique 'identity' integer for an object. |
| 976 |
input([prompt]) Prints prompt if given. Reads input and evaluates it. |
| 977 |
Converts a number or a string to a plain integer. Optional |
| 978 |
int(x[, base]) base parameter specifies base from which to convert string |
| 979 |
values. |
| 980 |
intern(aString) Enters aString in the table of "interned strings" |
| 981 |
andreturns the string. Interned strings are 'immortals'. |
| 982 |
isinstance(obj, returns true if obj is an instance of class. Ifissubclass |
| 983 |
class) (A,B) then isinstance(x,A) => isinstance(x,B) |
| 984 |
issubclass(class1, returns true if class1 is derived from class2 |
| 985 |
class2) |
| 986 |
Returns the length (the number of items) of an object |
| 987 |
iter(collection) Returns an iterator over the collection. |
| 988 |
len(obj) (sequence, dictionary, or instance of class implementing |
| 989 |
__len__). |
| 990 |
list(sequence) Converts sequence into a list. If already a list,returns a |
| 991 |
copy of it. |
| 992 |
locals() Returns a dictionary containing current local variables. |
| 993 |
Converts a number or a string to a long integer. Optional |
| 994 |
long(x[, base]) base parameter specifies base from which to convert string |
| 995 |
values. |
| 996 |
Applies function to every item of list and returns a listof |
| 997 |
map(function, list, the results. If additional arguments are passed,function |
| 998 |
...) must take that many arguments and it is givento function on |
| 999 |
each call. |
| 1000 |
max(seq) Returns the largest item of the non-empty sequence seq. |
| 1001 |
min(seq) Returns the smallest item of a non-empty sequence seq. |
| 1002 |
oct(x) Converts a number to an octal string. |
| 1003 |
open(filename [, Returns a new file object. First two args are same asthose |
| 1004 |
mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered, |
| 1005 |
implementation 1 for line-buffered, negative forsys-default, all else, of |
| 1006 |
dependent]]) (about) given size. |
| 1007 |
ord(c) Returns integer ASCII value of c (a string of len 1). Works |
| 1008 |
with Unicode char. |
| 1009 |
object() Create a base type. Used as a superclass for new-style objects. |
| 1010 |
open(name Open a file. |
| 1011 |
[, mode |
| 1012 |
[, buffering]]) |
| 1013 |
pow(x, y [, z]) Returns x to power y [modulo z]. See also ** operator. |
| 1014 |
property() Created a property with access controlled by functions. |
| 1015 |
range(start [,end Returns list of ints from >= start and < end.With 1 arg, |
| 1016 |
[, step]]) list from 0..arg-1With 2 args, list from start..end-1With 3 |
| 1017 |
args, list from start up to end by step |
| 1018 |
raw_input([prompt]) Prints prompt if given, then reads string from stdinput (no |
| 1019 |
trailing \n). See also input(). |
| 1020 |
reduce(f, list [, Applies the binary function f to the items oflist so as to |
| 1021 |
init]) reduce the list to a single value.If init given, it is |
| 1022 |
"prepended" to list. |
| 1023 |
Re-parses and re-initializes an already imported module. |
| 1024 |
Useful in interactive mode, if you want to reload amodule |
| 1025 |
reload(module) after fixing it. If module was syntacticallycorrect but had |
| 1026 |
an error in initialization, mustimport it one more time |
| 1027 |
before calling reload(). |
| 1028 |
Returns a string containing a printable and if possible |
| 1029 |
repr(object) evaluable representation of an object. <=> `object` |
| 1030 |
(usingbackquotes). Class redefinissable (__repr__). See |
| 1031 |
also str() |
| 1032 |
round(x, n=0) Returns the floating point value x rounded to n digitsafter |
| 1033 |
the decimal point. |
| 1034 |
setattr(object, This is the counterpart of getattr().setattr(o, 'foobar', |
| 1035 |
name, value) 3) <=> o.foobar = 3Creates attribute if it doesn't exist! |
| 1036 |
slice([start,] stop Returns a slice object representing a range, with R/ |
| 1037 |
[, step]) Oattributes: start, stop, step. |
| 1038 |
Returns a string containing a nicely |
| 1039 |
staticmethod() Convert a function to method with no self or class |
| 1040 |
argument. Useful for methods associated with a class that |
| 1041 |
do not need access to an object's internal state. |
| 1042 |
str(object) printablerepresentation of an object. Class overridable |
| 1043 |
(__str__).See also repr(). |
| 1044 |
super(type) Create an unbound super object. Used to call cooperative |
| 1045 |
superclass methods. |
| 1046 |
sum(sequence, Add the values in the sequence and return the sum. |
| 1047 |
[start]) |
| 1048 |
tuple(sequence) Creates a tuple with same elements as sequence. If already |
| 1049 |
a tuple, return itself (not a copy). |
| 1050 |
Returns a type object [see module types] representing |
| 1051 |
thetype of obj. Example: import typesif type(x) == |
| 1052 |
type(obj) types.StringType: print 'It is a string'NB: it is |
| 1053 |
recommanded to use the following form:if isinstance(x, |
| 1054 |
types.StringType): etc... |
| 1055 |
unichr(code) code. |
| 1056 |
unicode(string[, Creates a Unicode string from an 8-bit string, using |
| 1057 |
encoding[, error thegiven encoding name and error treatment ('strict', |
| 1058 |
]]]) 'ignore',or 'replace'}. |
| 1059 |
Without arguments, returns a dictionary correspondingto the |
| 1060 |
current local symbol table. With a module,class or class |
| 1061 |
vars([object]) instance object as argumentreturns a dictionary |
| 1062 |
corresponding to the object'ssymbol table. Useful with "%" |
| 1063 |
formatting operator. |
| 1064 |
xrange(start [, end Like range(), but doesn't actually store entire listall at |
| 1065 |
[, step]]) once. Good to use in "for" loops when there is abig range |
| 1066 |
and little memory. |
| 1067 |
zip(seq1[, seq2, Returns a list of tuples where each tuple contains the nth |
| 1068 |
...]) element of each of the argument sequences. |
| 1069 |
|
| 1070 |
|
| 1071 |
|
| 1072 |
|
| 1073 |
Built-In Exceptions |
| 1074 |
|
| 1075 |
Exception> |
| 1076 |
Root class for all exceptions |
| 1077 |
SystemExit |
| 1078 |
On 'sys.exit()' |
| 1079 |
StopIteration |
| 1080 |
Signal the end from iterator.next() |
| 1081 |
StandardError |
| 1082 |
Base class for all built-in exceptions; derived from Exception |
| 1083 |
root class. |
| 1084 |
ArithmeticError |
| 1085 |
Base class for OverflowError, ZeroDivisionError, |
| 1086 |
FloatingPointError |
| 1087 |
FloatingPointError |
| 1088 |
When a floating point operation fails. |
| 1089 |
OverflowError |
| 1090 |
On excessively large arithmetic operation |
| 1091 |
ZeroDivisionError |
| 1092 |
On division or modulo operation with 0 as 2nd arg |
| 1093 |
AssertionError |
| 1094 |
When an assert statement fails. |
| 1095 |
AttributeError |
| 1096 |
On attribute reference or assignment failure |
| 1097 |
EnvironmentError [new in 1.5.2] |
| 1098 |
On error outside Python; error arg tuple is (errno, errMsg...) |
| 1099 |
IOError [changed in 1.5.2] |
| 1100 |
I/O-related operation failure |
| 1101 |
OSError [new in 1.5.2] |
| 1102 |
used by the os module's os.error exception. |
| 1103 |
EOFError |
| 1104 |
Immediate end-of-file hit by input() or raw_input() |
| 1105 |
ImportError |
| 1106 |
On failure of `import' to find module or name |
| 1107 |
KeyboardInterrupt |
| 1108 |
On user entry of the interrupt key (often `Control-C') |
| 1109 |
LookupError |
| 1110 |
base class for IndexError, KeyError |
| 1111 |
IndexError |
| 1112 |
On out-of-range sequence subscript |
| 1113 |
KeyError |
| 1114 |
On reference to a non-existent mapping (dict) key |
| 1115 |
MemoryError |
| 1116 |
On recoverable memory exhaustion |
| 1117 |
NameError |
| 1118 |
On failure to find a local or global (unqualified) name |
| 1119 |
RuntimeError |
| 1120 |
Obsolete catch-all; define a suitable error instead |
| 1121 |
NotImplementedError [new in 1.5.2] |
| 1122 |
On method not implemented |
| 1123 |
SyntaxError |
| 1124 |
On parser encountering a syntax error |
| 1125 |
IndentationError |
| 1126 |
On parser encountering an indentation syntax error |
| 1127 |
TabError |
| 1128 |
On parser encountering an indentation syntax error |
| 1129 |
SystemError |
| 1130 |
On non-fatal interpreter error - bug - report it |
| 1131 |
TypeError |
| 1132 |
On passing inappropriate type to built-in op or func |
| 1133 |
ValueError |
| 1134 |
On arg error not covered by TypeError or more precise |
| 1135 |
Warning |
| 1136 |
UserWarning |
| 1137 |
DeprecationWarning |
| 1138 |
PendingDeprecationWarning |
| 1139 |
SyntaxWarning |
| 1140 |
RuntimeWarning |
| 1141 |
FutureWarning |
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
Standard methods & operators redefinition in classes |
| 1146 |
|
| 1147 |
Standard methods & operators map to special '__methods__' and thus may be |
| 1148 |
redefined (mostly in user-defined classes), e.g.: |
| 1149 |
class x: |
| 1150 |
def __init__(self, v): self.value = v |
| 1151 |
def __add__(self, r): return self.value + r |
| 1152 |
a = x(3) # sort of like calling x.__init__(a, 3) |
| 1153 |
a + 4 # is equivalent to a.__add__(4) |
| 1154 |
|
| 1155 |
Special methods for any class |
| 1156 |
|
| 1157 |
(s: self, o: other) |
| 1158 |
__init__(s, args) instance initialization (on construction) |
| 1159 |
__del__(s) called on object demise (refcount becomes 0) |
| 1160 |
__repr__(s) repr() and `...` conversions |
| 1161 |
__str__(s) str() and 'print' statement |
| 1162 |
__cmp__(s, o) Compares s to o and returns <0, 0, or >0. |
| 1163 |
Implements >, <, == etc... |
| 1164 |
__hash__(s) Compute a 32 bit hash code; hash() and dictionary ops |
| 1165 |
__nonzero__(s) Returns False or True for truth value testing |
| 1166 |
__getattr__(s, name) called when attr lookup doesn't find <name> |
| 1167 |
__setattr__(s, name, val) called when setting an attr |
| 1168 |
(inside, don't use "self.name = value" |
| 1169 |
use "self.__dict__[name] = val") |
| 1170 |
__delattr__(s, name) called to delete attr <name> |
| 1171 |
__call__(self, *args) called when an instance is called as function. |
| 1172 |
|
| 1173 |
Operators |
| 1174 |
|
| 1175 |
See list in the operator module. Operator function names are provided with |
| 1176 |
2 variants, with or without |
| 1177 |
ading & trailing '__' (eg. __add__ or add). |
| 1178 |
|
| 1179 |
Numeric operations special methods |
| 1180 |
(s: self, o: other) |
| 1181 |
|
| 1182 |
s+o = __add__(s,o) s-o = __sub__(s,o) |
| 1183 |
s*o = __mul__(s,o) s/o = __div__(s,o) |
| 1184 |
s%o = __mod__(s,o) divmod(s,o) = __divmod__(s,o) |
| 1185 |
s**o = __pow__(s,o) |
| 1186 |
s&o = __and__(s,o) |
| 1187 |
s^o = __xor__(s,o) s|o = __or__(s,o) |
| 1188 |
s<<o = __lshift__(s,o) s>>o = __rshift__(s,o) |
| 1189 |
nonzero(s) = __nonzero__(s) (used in boolean testing) |
| 1190 |
-s = __neg__(s) +s = __pos__(s) |
| 1191 |
abs(s) = __abs__(s) ~s = __invert__(s) (bitwise) |
| 1192 |
s+=o = __iadd__(s,o) s-=o = __isub__(s,o) |
| 1193 |
s*=o = __imul__(s,o) s/=o = __idiv__(s,o) |
| 1194 |
s%=o = __imod__(s,o) |
| 1195 |
s**=o = __ipow__(s,o) |
| 1196 |
s&=o = __iand__(s,o) |
| 1197 |
s^=o = __ixor__(s,o) s|=o = __ior__(s,o) |
| 1198 |
s<<=o = __ilshift__(s,o) s>>=o = __irshift__(s,o) |
| 1199 |
Conversions |
| 1200 |
int(s) = __int__(s) long(s) = __long__(s) |
| 1201 |
float(s) = __float__(s) complex(s) = __complex__(s) |
| 1202 |
oct(s) = __oct__(s) hex(s) = __hex__(s) |
| 1203 |
coerce(s,o) = __coerce__(s,o) |
| 1204 |
Right-hand-side equivalents for all binary operators exist; |
| 1205 |
are called when class instance is on r-h-s of operator: |
| 1206 |
a + 3 calls __add__(a, 3) |
| 1207 |
3 + a calls __radd__(a, 3) |
| 1208 |
|
| 1209 |
All seqs and maps, general operations plus: |
| 1210 |
(s: self, i: index or key) |
| 1211 |
|
| 1212 |
len(s) = __len__(s) length of object, >= 0. Length 0 == false |
| 1213 |
s[i] = __getitem__(s,i) Element at index/key i, origin 0 |
| 1214 |
|
| 1215 |
Sequences, general methods, plus: |
| 1216 |
s[i]=v = __setitem__(s,i,v) |
| 1217 |
del s[i] = __delitem__(s,i) |
| 1218 |
s[i:j] = __getslice__(s,i,j) |
| 1219 |
s[i:j]=seq = __setslice__(s,i,j,seq) |
| 1220 |
del s[i:j] = __delslice__(s,i,j) == s[i:j] = [] |
| 1221 |
seq * n = __repeat__(seq, n) |
| 1222 |
s1 + s2 = __concat__(s1, s2) |
| 1223 |
i in s = __contains__(s, i) |
| 1224 |
Mappings, general methods, plus |
| 1225 |
hash(s) = __hash__(s) - hash value for dictionary references |
| 1226 |
s[k]=v = __setitem__(s,k,v) |
| 1227 |
del s[k] = __delitem__(s,k) |
| 1228 |
|
| 1229 |
Special informative state attributes for some types: |
| 1230 |
|
| 1231 |
Modules: |
| 1232 |
__doc__ (string/None, R/O): doc string (<=> __dict__['__doc__']) |
| 1233 |
__name__(string, R/O): module name (also in __dict__['__name__']) |
| 1234 |
__dict__ (dict, R/O): module's name space |
| 1235 |
__file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for |
| 1236 |
modules statically linked to the interpreter) |
| 1237 |
|
| 1238 |
Classes: [in bold: writable since 1.5.2] |
| 1239 |
__doc__ (string/None, R/W): doc string (<=> __dict__['__doc__']) |
| 1240 |
__module__ is the module name in which the class was defined |
| 1241 |
__name__(string, R/W): class name (also in __dict__['__name__']) |
| 1242 |
__bases__ (tuple, R/W): parent classes |
| 1243 |
__dict__ (dict, R/W): attributes (class name space) |
| 1244 |
|
| 1245 |
Instances: |
| 1246 |
__class__ (class, R/W): instance's class |
| 1247 |
__dict__ (dict, R/W): attributes |
| 1248 |
|
| 1249 |
User-defined functions: [bold: writable since 1.5.2] |
| 1250 |
__doc__ (string/None, R/W): doc string |
| 1251 |
__name__(string, R/O): function name |
| 1252 |
func_doc (R/W): same as __doc__ |
| 1253 |
func_name (R/O): same as __name__ |
| 1254 |
func_defaults (tuple/None, R/W): default args values if any |
| 1255 |
func_code (code, R/W): code object representing the compiled function body |
| 1256 |
func_globals (dict, R/O): ref to dictionary of func global variables |
| 1257 |
func_dict (dict, R/W): same as __dict__ contains the namespace supporting |
| 1258 |
arbitrary function attributes |
| 1259 |
func_closure (R/O): None or a tuple of cells that contain bindings |
| 1260 |
for the function's free variables. |
| 1261 |
|
| 1262 |
|
| 1263 |
User-defined Methods: |
| 1264 |
__doc__ (string/None, R/O): doc string |
| 1265 |
__name__(string, R/O): method name (same as im_func.__name__) |
| 1266 |
im_class (class, R/O): class defining the method (may be a base class) |
| 1267 |
im_self (instance/None, R/O): target instance object (None if unbound) |
| 1268 |
im_func (function, R/O): function object |
| 1269 |
|
| 1270 |
Built-in Functions & methods: |
| 1271 |
__doc__ (string/None, R/O): doc string |
| 1272 |
__name__ (string, R/O): function name |
| 1273 |
__self__ : [methods only] target object |
| 1274 |
|
| 1275 |
Codes: |
| 1276 |
co_name (string, R/O): function name |
| 1277 |
co_argcount (int, R/0): number of positional args |
| 1278 |
co_nlocals (int, R/O): number of local vars (including args) |
| 1279 |
co_varnames (tuple, R/O): names of local vars (starting with args) |
| 1280 |
co_cellvars (tuple, R/O)) the names of local variables referenced by |
| 1281 |
nested functions |
| 1282 |
co_freevars (tuple, R/O)) names of free variables |
| 1283 |
co_code (string, R/O): sequence of bytecode instructions |
| 1284 |
co_consts (tuple, R/O): litterals used by the bytecode, 1st one is |
| 1285 |
fct doc (or None) |
| 1286 |
co_names (tuple, R/O): names used by the bytecode |
| 1287 |
co_filename (string, R/O): filename from which the code was compiled |
| 1288 |
co_firstlineno (int, R/O): first line number of the function |
| 1289 |
co_lnotab (string, R/O): string encoding bytecode offsets to line numbers. |
| 1290 |
co_stacksize (int, R/O): required stack size (including local vars) |
| 1291 |
co_flags (int, R/O): flags for the interpreter |
| 1292 |
bit 2 set if fct uses "*arg" syntax |
| 1293 |
bit 3 set if fct uses '**keywords' syntax |
| 1294 |
Frames: |
| 1295 |
f_back (frame/None, R/O): previous stack frame (toward the caller) |
| 1296 |
f_code (code, R/O): code object being executed in this frame |
| 1297 |
f_locals (dict, R/O): local vars |
| 1298 |
f_globals (dict, R/O): global vars |
| 1299 |
f_builtins (dict, R/O): built-in (intrinsic) names |
| 1300 |
f_restricted (int, R/O): flag indicating whether fct is executed in |
| 1301 |
restricted mode |
| 1302 |
f_lineno (int, R/O): current line number |
| 1303 |
f_lasti (int, R/O): precise instruction (index into bytecode) |
| 1304 |
f_trace (function/None, R/W): debug hook called at start of each source line |
| 1305 |
f_exc_type (Type/None, R/W): Most recent exception type |
| 1306 |
f_exc_value (any, R/W): Most recent exception value |
| 1307 |
f_exc_traceback (traceback/None, R/W): Most recent exception traceback |
| 1308 |
Tracebacks: |
| 1309 |
tb_next (frame/None, R/O): next level in stack trace (toward the frame where |
| 1310 |
the exception occurred) |
| 1311 |
tb_frame (frame, R/O): execution frame of the current level |
| 1312 |
tb_lineno (int, R/O): line number where the exception occurred |
| 1313 |
tb_lasti (int, R/O): precise instruction (index into bytecode) |
| 1314 |
|
| 1315 |
Slices: |
| 1316 |
start (any/None, R/O): lowerbound |
| 1317 |
stop (any/None, R/O): upperbound |
| 1318 |
step (any/None, R/O): step value |
| 1319 |
|
| 1320 |
Complex numbers: |
| 1321 |
real (float, R/O): real part |
| 1322 |
imag (float, R/O): imaginary part |
| 1323 |
|
| 1324 |
|
| 1325 |
Important Modules |
| 1326 |
|
| 1327 |
sys |
| 1328 |
|
| 1329 |
Some sys variables |
| 1330 |
Variable Content |
| 1331 |
argv The list of command line arguments passed to aPython |
| 1332 |
script. sys.argv[0] is the script name. |
| 1333 |
builtin_module_names A list of strings giving the names of all moduleswritten |
| 1334 |
in C that are linked into this interpreter. |
| 1335 |
check_interval How often to check for thread switches or signals(measured |
| 1336 |
in number of virtual machine instructions) |
| 1337 |
exc_type, exc_value, Deprecated since release 1.5. Use exc_info() instead. |
| 1338 |
exc_traceback |
| 1339 |
exitfunc User can set to a parameterless fcn. It will getcalled |
| 1340 |
before interpreter exits. |
| 1341 |
last_type, Set only when an exception not handled andinterpreter |
| 1342 |
last_value, prints an error. Used by debuggers. |
| 1343 |
last_traceback |
| 1344 |
maxint maximum positive value for integers |
| 1345 |
modules Dictionary of modules that have already been loaded. |
| 1346 |
path Search path for external modules. Can be modifiedby |
| 1347 |
program. sys.path[0] == dir of script executing |
| 1348 |
platform The current platform, e.g. "sunos5", "win32" |
| 1349 |
ps1, ps2 prompts to use in interactive mode. |
| 1350 |
File objects used for I/O. One can redirect byassigning a |
| 1351 |
stdin, stdout, new file object to them (or any object:.with a method |
| 1352 |
stderr write(string) for stdout/stderr,.with a method readline() |
| 1353 |
for stdin) |
| 1354 |
version string containing version info about Python interpreter. |
| 1355 |
(and also: copyright, dllhandle, exec_prefix, prefix) |
| 1356 |
version_info tuple containing Python version info - (major, minor, |
| 1357 |
micro, level, serial). |
| 1358 |
|
| 1359 |
Some sys functions |
| 1360 |
Function Result |
| 1361 |
exit(n) Exits with status n. Raises SystemExit exception.(Hence can |
| 1362 |
be caught and ignored by program) |
| 1363 |
getrefcount(object Returns the reference count of the object. Generally one |
| 1364 |
) higher than you might expect, because of object arg temp |
| 1365 |
reference. |
| 1366 |
setcheckinterval( Sets the interpreter's thread switching interval (in number |
| 1367 |
interval) of virtual code instructions, default:100). |
| 1368 |
settrace(func) Sets a trace function: called before each line ofcode is |
| 1369 |
exited. |
| 1370 |
setprofile(func) Sets a profile function for performance profiling. |
| 1371 |
Info on exception currently being handled; this is atuple |
| 1372 |
(exc_type, exc_value, exc_traceback).Warning: assigning the |
| 1373 |
exc_info() traceback return value to a local variable in a |
| 1374 |
function handling an exception will cause a circular |
| 1375 |
reference. |
| 1376 |
setdefaultencoding Change default Unicode encoding - defaults to 7-bit ASCII. |
| 1377 |
(encoding) |
| 1378 |
getrecursionlimit Retrieve maximum recursion depth. |
| 1379 |
() |
| 1380 |
setrecursionlimit Set maximum recursion depth. (Defaults to 1000.) |
| 1381 |
() |
| 1382 |
|
| 1383 |
|
| 1384 |
|
| 1385 |
os |
| 1386 |
"synonym" for whatever O/S-specific module is proper for current environment. |
| 1387 |
this module uses posix whenever possible. |
| 1388 |
(see also M.A. Lemburg's utility http://www.lemburg.com/files/python/ |
| 1389 |
platform.py) |
| 1390 |
|
| 1391 |
Some os variables |
| 1392 |
Variable Meaning |
| 1393 |
name name of O/S-specific module (e.g. "posix", "nt") |
| 1394 |
path O/S-specific module for path manipulations. |
| 1395 |
On Unix, os.path.split() <=> posixpath.split() |
| 1396 |
curdir string used to represent current directory ('.') |
| 1397 |
pardir string used to represent parent directory ('..') |
| 1398 |
sep string used to separate directories ('/' or '\'). Tip: use |
| 1399 |
os.path.join() to build portable paths. |
| 1400 |
altsep Alternate sep |
| 1401 |
if applicable (None |
| 1402 |
otherwise) |
| 1403 |
pathsep character used to separate search path components (as in |
| 1404 |
$PATH), eg. ';' for windows. |
| 1405 |
linesep line separator as used in binary files, ie '\n' on Unix, '\ |
| 1406 |
r\n' on Dos/Win, '\r' |
| 1407 |
|
| 1408 |
Some os functions |
| 1409 |
Function Result |
| 1410 |
makedirs(path[, Recursive directory creation (create required intermediary |
| 1411 |
mode=0777]) dirs); os.error if fails. |
| 1412 |
removedirs(path) Recursive directory delete (delete intermediary empty |
| 1413 |
dirs); if fails. |
| 1414 |
renames(old, new) Recursive directory or file renaming; os.error if fails. |
| 1415 |
|
| 1416 |
|
| 1417 |
|
| 1418 |
posix |
| 1419 |
don't import this module directly, import os instead ! |
| 1420 |
(see also module: shutil for file copy & remove fcts) |
| 1421 |
|
| 1422 |
posix Variables |
| 1423 |
Variable Meaning |
| 1424 |
environ dictionary of environment variables, e.g.posix.environ['HOME']. |
| 1425 |
error exception raised on POSIX-related error. |
| 1426 |
Corresponding value is tuple of errno code and perror() string. |
| 1427 |
|
| 1428 |
Some posix functions |
| 1429 |
Function Result |
| 1430 |
chdir(path) Changes current directory to path. |
| 1431 |
chmod(path, Changes the mode of path to the numeric mode |
| 1432 |
mode) |
| 1433 |
close(fd) Closes file descriptor fd opened with posix.open. |
| 1434 |
_exit(n) Immediate exit, with no cleanups, no SystemExit,etc. Should use |
| 1435 |
this to exit a child process. |
| 1436 |
execv(p, args) "Become" executable p with args args |
| 1437 |
getcwd() Returns a string representing the current working directory |
| 1438 |
getpid() Returns the current process id |
| 1439 |
fork() Like C's fork(). Returns 0 to child, child pid to parent.[Not |
| 1440 |
on Windows] |
| 1441 |
kill(pid, Like C's kill [Not on Windows] |
| 1442 |
signal) |
| 1443 |
listdir(path) Lists (base)names of entries in directory path, excluding '.' |
| 1444 |
and '..' |
| 1445 |
lseek(fd, pos, Sets current position in file fd to position pos, expressedas |
| 1446 |
how) an offset relative to beginning of file (how=0), tocurrent |
| 1447 |
position (how=1), or to end of file (how=2) |
| 1448 |
mkdir(path[, Creates a directory named path with numeric mode (default 0777) |
| 1449 |
mode]) |
| 1450 |
open(file, Like C's open(). Returns file descriptor. Use file object |
| 1451 |
flags, mode) fctsrather than this low level ones. |
| 1452 |
pipe() Creates a pipe. Returns pair of file descriptors (r, w) [Not on |
| 1453 |
Windows]. |
| 1454 |
popen(command, Opens a pipe to or from command. Result is a file object to |
| 1455 |
mode='r', read to orwrite from, as indicated by mode being 'r' or 'w'. |
| 1456 |
bufSize=0) Use it to catch acommand output ('r' mode) or to feed it ('w' |
| 1457 |
mode). |
| 1458 |
remove(path) See unlink. |
| 1459 |
rename(src, dst Renames/moves the file or directory src to dst. [error iftarget |
| 1460 |
) name already exists] |
| 1461 |
rmdir(path) Removes the empty directory path |
| 1462 |
read(fd, n) Reads n bytes from file descriptor fd and return as string. |
| 1463 |
Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid, |
| 1464 |
stat(path) st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid |
| 1465 |
are dummy on Windows] |
| 1466 |
system(command) Executes string command in a subshell. Returns exitstatus of |
| 1467 |
subshell (usually 0 means OK). |
| 1468 |
Returns accumulated CPU times in sec (user, system, children's |
| 1469 |
times() user,children's sys, elapsed real time). [3 last not on |
| 1470 |
Windows] |
| 1471 |
unlink(path) Unlinks ("deletes") the file (not dir!) path. same as: remove |
| 1472 |
utime(path, ( Sets the access & modified time of the file to the given tuple |
| 1473 |
aTime, mTime)) of values. |
| 1474 |
wait() Waits for child process completion. Returns tuple ofpid, |
| 1475 |
exit_status [Not on Windows] |
| 1476 |
waitpid(pid, Waits for process pid to complete. Returns tuple ofpid, |
| 1477 |
options) exit_status [Not on Windows] |
| 1478 |
write(fd, str) Writes str to file fd. Returns nb of bytes written. |
| 1479 |
|
| 1480 |
|
| 1481 |
|
| 1482 |
posixpath |
| 1483 |
Do not import this module directly, import os instead and refer to this module |
| 1484 |
as os.path. (e.g. os.path.exists(p)) ! |
| 1485 |
|
| 1486 |
Some posixpath functions |
| 1487 |
Function Result |
| 1488 |
abspath(p) Returns absolute path for path p, taking current working dir in |
| 1489 |
account. |
| 1490 |
dirname/ |
| 1491 |
basename(p directory and name parts of the path p. See also split. |
| 1492 |
) |
| 1493 |
exists(p) True if string p is an existing path (file or directory) |
| 1494 |
expanduser Returns string that is (a copy of) p with "~" expansion done. |
| 1495 |
(p) |
| 1496 |
expandvars Returns string that is (a copy of) p with environment vars expanded. |
| 1497 |
(p) [Windows: case significant; must use Unix: $var notation, not %var%] |
| 1498 |
getsize( return the size in bytes of filename. raise os.error. |
| 1499 |
filename) |
| 1500 |
getmtime( return last modification time of filename (integer nb of seconds |
| 1501 |
filename) since epoch). |
| 1502 |
getatime( return last access time of filename (integer nb of seconds since |
| 1503 |
filename) epoch). |
| 1504 |
isabs(p) True if string p is an absolute path. |
| 1505 |
isdir(p) True if string p is a directory. |
| 1506 |
islink(p) True if string p is a symbolic link. |
| 1507 |
ismount(p) True if string p is a mount point [true for all dirs on Windows]. |
| 1508 |
join(p[,q Joins one or more path components intelligently. |
| 1509 |
[,...]]) |
| 1510 |
Splits p into (head, tail) where tail is lastpathname component and |
| 1511 |
split(p) <head> is everything leadingup to that. <=> (dirname(p), basename |
| 1512 |
(p)) |
| 1513 |
splitdrive Splits path p in a pair ('drive:', tail) [Windows] |
| 1514 |
(p) |
| 1515 |
splitext(p Splits into (root, ext) where last comp of root contains no periods |
| 1516 |
) and ext is empty or startswith a period. |
| 1517 |
Calls the function visit with arguments(arg, dirname, names) for |
| 1518 |
each directory recursively inthe directory tree rooted at p |
| 1519 |
walk(p, (including p itself if it's a dir)The argument dirname specifies the |
| 1520 |
visit, arg visited directory, the argumentnames lists the files in the |
| 1521 |
) directory. The visit function maymodify names to influence the set |
| 1522 |
of directories visited belowdirname, e.g., to avoid visiting certain |
| 1523 |
parts of the tree. |
| 1524 |
|
| 1525 |
|
| 1526 |
|
| 1527 |
shutil |
| 1528 |
high-level file operations (copying, deleting). |
| 1529 |
|
| 1530 |
Main shutil functions |
| 1531 |
Function Result |
| 1532 |
copy(src, dst) Copies the contents of file src to file dst, retaining file |
| 1533 |
permissions. |
| 1534 |
copytree(src, dst Recursively copies an entire directory tree rooted at src |
| 1535 |
[, symlinks]) into dst (which should not already exist). If symlinks is |
| 1536 |
true, links insrc are kept as such in dst. |
| 1537 |
rmtree(path[, Deletes an entire directory tree, ignoring errors if |
| 1538 |
ignore_errors[, ignore_errors true,or calling onerror(func, path, |
| 1539 |
onerror]]) sys.exc_info()) if supplied with |
| 1540 |
|
| 1541 |
(and also: copyfile, copymode, copystat, copy2) |
| 1542 |
|
| 1543 |
time |
| 1544 |
|
| 1545 |
Variables |
| 1546 |
Variable Meaning |
| 1547 |
altzone signed offset of local DST timezone in sec west of the 0th meridian. |
| 1548 |
daylight nonzero if a DST timezone is specified |
| 1549 |
|
| 1550 |
Functions |
| 1551 |
Function Result |
| 1552 |
time() return a float representing UTC time in seconds since the epoch. |
| 1553 |
gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day |
| 1554 |
localtime( (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is |
| 1555 |
secs) monday), Julian day(1-366), daylight flag(-1,0 or 1)) |
| 1556 |
asctime( |
| 1557 |
timeTuple), |
| 1558 |
strftime( |
| 1559 |
format, return a formatted string representing time. |
| 1560 |
timeTuple) |
| 1561 |
mktime(tuple) inverse of localtime(). Return a float. |
| 1562 |
strptime( parse a formatted string representing time, return tuple as in |
| 1563 |
string[, gmtime(). |
| 1564 |
format]) |
| 1565 |
sleep(secs) Suspend execution for <secs> seconds. <secs> can be a float. |
| 1566 |
|
| 1567 |
and also: clock, ctime. |
| 1568 |
|
| 1569 |
string |
| 1570 |
|
| 1571 |
As of Python 2.0, much (though not all) of the functionality provided by the |
| 1572 |
string module have been superseded by built-in string methods - see Operations |
| 1573 |
on strings for details. |
| 1574 |
|
| 1575 |
Some string variables |
| 1576 |
Variable Meaning |
| 1577 |
digits The string '0123456789' |
| 1578 |
hexdigits, octdigits legal hexadecimal & octal digits |
| 1579 |
letters, uppercase, lowercase, Strings containing the appropriate |
| 1580 |
whitespace characters |
| 1581 |
index_error Exception raised by index() if substr not |
| 1582 |
found. |
| 1583 |
|
| 1584 |
Some string functions |
| 1585 |
Function Result |
| 1586 |
expandtabs(s, returns a copy of string <s> with tabs expanded. |
| 1587 |
tabSize) |
| 1588 |
find/rfind(s, sub Return the lowest/highest index in <s> where the substring |
| 1589 |
[, start=0[, end= <sub> is found such that <sub> is wholly contained ins |
| 1590 |
0]) [start:end]. Return -1 if <sub> not found. |
| 1591 |
ljust/rjust/center Return a copy of string <s> left/right justified/centerd in |
| 1592 |
(s, width) afield of given width, padded with spaces. <s> is |
| 1593 |
nevertruncated. |
| 1594 |
lower/upper(s) Return a string that is (a copy of) <s> in lowercase/ |
| 1595 |
uppercase |
| 1596 |
split(s[, sep= Return a list containing the words of the string <s>,using |
| 1597 |
whitespace[, the string <sep> as a separator. |
| 1598 |
maxsplit=0]]) |
| 1599 |
join(words[, sep=' Concatenate a list or tuple of words with |
| 1600 |
']) interveningseparators; inverse of split. |
| 1601 |
replace(s, old, Returns a copy of string <s> with all occurrences of |
| 1602 |
new[, maxsplit=0] substring<old> replaced by <new>. Limits to <maxsplit> |
| 1603 |
firstsubstitutions if specified. |
| 1604 |
strip(s) Return a string that is (a copy of) <s> without leadingand |
| 1605 |
trailing whitespace. see also lstrip, rstrip. |
| 1606 |
|
| 1607 |
|
| 1608 |
|
| 1609 |
re (sre) |
| 1610 |
|
| 1611 |
Handles Unicode strings. Implemented in new module sre, re now a mere front-end |
| 1612 |
for compatibility. |
| 1613 |
Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to |
| 1614 |
litteralize backslashes. |
| 1615 |
|
| 1616 |
|
| 1617 |
Regular expression syntax |
| 1618 |
Form Description |
| 1619 |
. matches any character (including newline if DOTALL flag specified) |
| 1620 |
^ matches start of the string (of every line in MULTILINE mode) |
| 1621 |
$ matches end of the string (of every line in MULTILINE mode) |
| 1622 |
* 0 or more of preceding regular expression (as many as possible) |
| 1623 |
+ 1 or more of preceding regular expression (as many as possible) |
| 1624 |
? 0 or 1 occurrence of preceding regular expression |
| 1625 |
*?, +?, ?? Same as *, + and ? but matches as few characters as possible |
| 1626 |
{m,n} matches from m to n repetitions of preceding RE |
| 1627 |
{m,n}? idem, attempting to match as few repetitions as possible |
| 1628 |
[ ] defines character set: e.g. '[a-zA-Z]' to match all letters(see also |
| 1629 |
\w \S) |
| 1630 |
[^ ] defines complemented character set: matches if char is NOT in set |
| 1631 |
escapes special chars '*?+&$|()' and introduces special sequences |
| 1632 |
\ (see below). Due to Python string rules, write as '\\' orr'\' in the |
| 1633 |
pattern string. |
| 1634 |
\\ matches a litteral '\'; due to Python string rules, write as '\\\\ |
| 1635 |
'in pattern string, or better using raw string: r'\\'. |
| 1636 |
| specifies alternative: 'foo|bar' matches 'foo' or 'bar' |
| 1637 |
(...) matches any RE inside (), and delimits a group. |
| 1638 |
(?:...) idem but doesn't delimit a group. |
| 1639 |
matches if ... matches next, but doesn't consume any of the string |
| 1640 |
(?=...) e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by |
| 1641 |
'Asimov'. |
| 1642 |
(?!...) matches if ... doesn't match next. Negative of (?=...) |
| 1643 |
(?P<name matches any RE inside (), and delimits a named group. (e.g. r'(?P |
| 1644 |
>...) <id>[a-zA-Z_]\w*)' defines a group named id) |
| 1645 |
(?P=name) matches whatever text was matched by the earlier group named name. |
| 1646 |
(?#...) A comment; ignored. |
| 1647 |
(?letter) letter is one of 'i','L', 'm', 's', 'x'. Set the corresponding flags |
| 1648 |
(re.I, re.L, re.M, re.S, re.X) for the entire RE. |
| 1649 |
|
| 1650 |
Special sequences |
| 1651 |
Sequence Description |
| 1652 |
number matches content of the group of the same number; groups are numbered |
| 1653 |
starting from 1 |
| 1654 |
\A matches only at the start of the string |
| 1655 |
\b empty str at beg or end of word: '\bis\b' matches 'is', but not 'his' |
| 1656 |
\B empty str NOT at beginning or end of word |
| 1657 |
\d any decimal digit (<=> [0-9]) |
| 1658 |
\D any non-decimal digit char (<=> [^O-9]) |
| 1659 |
\s any whitespace char (<=> [ \t\n\r\f\v]) |
| 1660 |
\S any non-whitespace char (<=> [^ \t\n\r\f\v]) |
| 1661 |
\w any alphaNumeric char (depends on LOCALE flag) |
| 1662 |
\W any non-alphaNumeric char (depends on LOCALE flag) |
| 1663 |
\Z matches only at the end of the string |
| 1664 |
|
| 1665 |
Variables |
| 1666 |
Variable Meaning |
| 1667 |
error Exception when pattern string isn't a valid regexp. |
| 1668 |
|
| 1669 |
Functions |
| 1670 |
Function Result |
| 1671 |
Compile a RE pattern string into a regular expression object. |
| 1672 |
Flags (combinable by |): |
| 1673 |
|
| 1674 |
I or IGNORECASE or (?i) |
| 1675 |
case insensitive matching |
| 1676 |
compile( L or LOCALE or (?L) |
| 1677 |
pattern[, make \w, \W, \b, \B dependent on thecurrent locale |
| 1678 |
flags=0]) M or MULTILINE or (?m) |
| 1679 |
matches every new line and not onlystart/end of the whole |
| 1680 |
string |
| 1681 |
S or DOTALL or (?s) |
| 1682 |
'.' matches ALL chars, including newline |
| 1683 |
X or VERBOSE or (?x) |
| 1684 |
Ignores whitespace outside character sets |
| 1685 |
escape(string) return (a copy of) string with all non-alphanumerics |
| 1686 |
backslashed. |
| 1687 |
match(pattern, if 0 or more chars at beginning of <string> match the RE pattern |
| 1688 |
string[, flags string,return a corresponding MatchObject instance, or None if |
| 1689 |
]) no match. |
| 1690 |
search(pattern scan thru <string> for a location matching <pattern>, return |
| 1691 |
, string[, acorresponding MatchObject instance, or None if no match. |
| 1692 |
flags]) |
| 1693 |
split(pattern, split <string> by occurrences of <pattern>. If capturing () are |
| 1694 |
string[, used inpattern, then occurrences of patterns or subpatterns are |
| 1695 |
maxsplit=0]) also returned. |
| 1696 |
findall( return a list of non-overlapping matches in <pattern>, either a |
| 1697 |
pattern, list ofgroups or a list of tuples if the pattern has more than 1 |
| 1698 |
string) group. |
| 1699 |
return string obtained by replacing the (<count> first) lefmost |
| 1700 |
sub(pattern, non-overlapping occurrences of <pattern> (a string or a RE |
| 1701 |
repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct |
| 1702 |
count=0]) called with a single MatchObj arg, which must return the |
| 1703 |
replacement string. |
| 1704 |
subn(pattern, |
| 1705 |
repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade) |
| 1706 |
count=0]) |
| 1707 |
|
| 1708 |
Regular Expression Objects |
| 1709 |
|
| 1710 |
|
| 1711 |
(RE objects are returned by the compile fct) |
| 1712 |
|
| 1713 |
re object attributes |
| 1714 |
Attribute Descrition |
| 1715 |
flags flags arg used when RE obj was compiled, or 0 if none provided |
| 1716 |
groupindex dictionary of {group name: group number} in pattern |
| 1717 |
pattern pattern string from which RE obj was compiled |
| 1718 |
|
| 1719 |
re object methods |
| 1720 |
Method Result |
| 1721 |
If zero or more characters at the beginning of string match this |
| 1722 |
regular expression, return a corresponding MatchObject instance. |
| 1723 |
Return None if the string does not match the pattern; note that |
| 1724 |
this is different from a zero-length match. |
| 1725 |
The optional second parameter pos gives an index in the string |
| 1726 |
match( where the search is to start; it defaults to 0. This is not |
| 1727 |
string[, completely equivalent to slicing the string; the '' pattern |
| 1728 |
pos][, character matches at the real beginning of the string and at |
| 1729 |
endpos]) positions just after a newline, but not necessarily at the index |
| 1730 |
where the search is to start. |
| 1731 |
The optional parameter endpos limits how far the string will be |
| 1732 |
searched; it will be as if the string is endpos characters long, so |
| 1733 |
only the characters from pos to endpos will be searched for a |
| 1734 |
match. |
| 1735 |
Scan through string looking for a location where this regular |
| 1736 |
search( expression produces a match, and return a corresponding MatchObject |
| 1737 |
string[, instance. Return None if no position in the string matches the |
| 1738 |
pos][, pattern; note that this is different from finding a zero-length |
| 1739 |
endpos]) match at some point in the string. |
| 1740 |
The optional pos and endpos parameters have the same meaning as for |
| 1741 |
the match() method. |
| 1742 |
split( |
| 1743 |
string[, Identical to the split() function, using the compiled pattern. |
| 1744 |
maxsplit= |
| 1745 |
0]) |
| 1746 |
findall( Identical to the findall() function, using the compiled pattern. |
| 1747 |
string) |
| 1748 |
sub(repl, |
| 1749 |
string[, Identical to the sub() function, using the compiled pattern. |
| 1750 |
count=0]) |
| 1751 |
subn(repl, |
| 1752 |
string[, Identical to the subn() function, using the compiled pattern. |
| 1753 |
count=0]) |
| 1754 |
|
| 1755 |
Match Objects |
| 1756 |
|
| 1757 |
|
| 1758 |
(Match objects are returned by the match & search functions) |
| 1759 |
|
| 1760 |
Match object attributes |
| 1761 |
Attribute Description |
| 1762 |
pos value of pos passed to search or match functions; index intostring at |
| 1763 |
which RE engine started search. |
| 1764 |
endpos value of endpos passed to search or match functions; index intostring |
| 1765 |
beyond which RE engine won't go. |
| 1766 |
re RE object whose match or search fct produced this MatchObj instance |
| 1767 |
string string passed to match() or search() |
| 1768 |
|
| 1769 |
Match object functions |
| 1770 |
Function Result |
| 1771 |
returns one or more groups of the match. If one arg, result is a |
| 1772 |
group([g1 string;if multiple args, result is a tuple with one item per arg. If |
| 1773 |
, g2, gi is 0,return value is entire matching string; if 1 <= gi <= 99, |
| 1774 |
...]) returnstring matching group #gi (or None if no such group); gi may |
| 1775 |
also bea group name. |
| 1776 |
returns a tuple of all groups of the match; groups not |
| 1777 |
groups() participatingto the match have a value of None. Returns a string |
| 1778 |
instead of tupleif len(tuple)=1 |
| 1779 |
start( |
| 1780 |
group), returns indices of start & end of substring matched by group (or |
| 1781 |
end(group Noneif group exists but doesn't contribute to the match) |
| 1782 |
) |
| 1783 |
span( returns the 2-tuple (start(group), end(group)); can be (None, None)if |
| 1784 |
group) group didn't contibute to the match. |
| 1785 |
|
| 1786 |
|
| 1787 |
|
| 1788 |
math |
| 1789 |
|
| 1790 |
Variables: |
| 1791 |
pi |
| 1792 |
e |
| 1793 |
Functions (see ordinary C man pages for info): |
| 1794 |
acos(x) |
| 1795 |
asin(x) |
| 1796 |
atan(x) |
| 1797 |
atan2(x, y) |
| 1798 |
ceil(x) |
| 1799 |
cos(x) |
| 1800 |
cosh(x) |
| 1801 |
degrees(x) |
| 1802 |
exp(x) |
| 1803 |
fabs(x) |
| 1804 |
floor(x) |
| 1805 |
fmod(x, y) |
| 1806 |
frexp(x) -- Unlike C: (float, int) = frexp(float) |
| 1807 |
ldexp(x, y) |
| 1808 |
log(x [,base]) |
| 1809 |
log10(x) |
| 1810 |
modf(x) -- Unlike C: (float, float) = modf(float) |
| 1811 |
pow(x, y) |
| 1812 |
radians(x) |
| 1813 |
sin(x) |
| 1814 |
sinh(x) |
| 1815 |
sqrt(x) |
| 1816 |
tan(x) |
| 1817 |
tanh(x) |
| 1818 |
|
| 1819 |
getopt |
| 1820 |
|
| 1821 |
Functions: |
| 1822 |
getopt(list, optstr) -- Similar to C. <optstr> is option |
| 1823 |
letters to look for. Put ':' after letter |
| 1824 |
if option takes arg. E.g. |
| 1825 |
# invocation was "python test.py -c hi -a arg1 arg2" |
| 1826 |
opts, args = getopt.getopt(sys.argv[1:], 'ab:c:') |
| 1827 |
# opts would be |
| 1828 |
[('-c', 'hi'), ('-a', '')] |
| 1829 |
# args would be |
| 1830 |
['arg1', 'arg2'] |
| 1831 |
|
| 1832 |
|
| 1833 |
List of modules and packages in base distribution |
| 1834 |
|
| 1835 |
(built-ins and content of python Lib directory) |
| 1836 |
(Python NT distribution, may be slightly different in other distributions) |
| 1837 |
|
| 1838 |
Standard library modules |
| 1839 |
Operation Result |
| 1840 |
aifc Stuff to parse AIFF-C and AIFF files. |
| 1841 |
anydbm Generic interface to all dbm clones. (dbhash, gdbm, |
| 1842 |
dbm,dumbdbm) |
| 1843 |
asynchat Support for 'chat' style protocols |
| 1844 |
asyncore Asynchronous File I/O (in select style) |
| 1845 |
atexit Register functions to be called at exit of Python interpreter. |
| 1846 |
audiodev Audio support for a few platforms. |
| 1847 |
base64 Conversions to/from base64 RFC-MIME transport encoding . |
| 1848 |
BaseHTTPServer Base class forhttp services. |
| 1849 |
Bastion "Bastionification" utility (control access to instance vars) |
| 1850 |
bdb A generic Python debugger base class. |
| 1851 |
binhex Macintosh binhex compression/decompression. |
| 1852 |
bisect List bisection algorithms. |
| 1853 |
bz2 Support for bz2 compression/decompression. |
| 1854 |
calendar Calendar printing functions. |
| 1855 |
cgi Wraps the WWW Forms Common Gateway Interface (CGI). |
| 1856 |
cgitb Utility for handling CGI tracebacks. |
| 1857 |
CGIHTTPServer CGI http services. |
| 1858 |
cmd A generic class to build line-oriented command interpreters. |
| 1859 |
datetime Basic date and time types. |
| 1860 |
code Utilities needed to emulate Python's interactive interpreter |
| 1861 |
codecs Lookup existing Unicode encodings and register new ones. |
| 1862 |
colorsys Conversion functions between RGB and other color systems. |
| 1863 |
commands Tools for executing UNIX commands . |
| 1864 |
compileall Force "compilation" of all .py files in a directory. |
| 1865 |
ConfigParser Configuration file parser (much like windows .ini files) |
| 1866 |
copy Generic shallow and deep copying operations. |
| 1867 |
copy_reg Helper to provide extensibility for pickle/cPickle. |
| 1868 |
csv Read and write files with comma separated values. |
| 1869 |
dbhash (g)dbm-compatible interface to bsdhash.hashopen. |
| 1870 |
dircache Sorted list of files in a dir, using a cache. |
| 1871 |
[DEL:dircmp:DEL] [DEL:Defines a class to build directory diff tools on.:DEL] |
| 1872 |
difflib Tool for creating delta between sequences. |
| 1873 |
dis Bytecode disassembler. |
| 1874 |
distutils Package installation system. |
| 1875 |
doctest Tool for running and verifying tests inside doc strings. |
| 1876 |
dospath Common operations on DOS pathnames. |
| 1877 |
dumbdbm A dumb and slow but simple dbm clone. |
| 1878 |
[DEL:dump:DEL] [DEL:Print python code that reconstructs a variable.:DEL] |
| 1879 |
email Comprehensive support for internet email. |
| 1880 |
exceptions Class based built-in exception hierarchy. |
| 1881 |
filecmp File comparison. |
| 1882 |
fileinput Helper class to quickly write a loop over all standard input |
| 1883 |
files. |
| 1884 |
[DEL:find:DEL] [DEL:Find files directory hierarchy matching a pattern.:DEL] |
| 1885 |
fnmatch Filename matching with shell patterns. |
| 1886 |
formatter A test formatter. |
| 1887 |
fpformat General floating point formatting functions. |
| 1888 |
ftplib An FTP client class. Based on RFC 959. |
| 1889 |
gc Perform garbacge collection, obtain GC debug stats, and tune |
| 1890 |
GC parameters. |
| 1891 |
getopt Standard command line processing. See also ftp:// |
| 1892 |
www.pauahtun.org/pub/getargspy.zip |
| 1893 |
getpass Utilities to get a password and/or the current user name. |
| 1894 |
glob filename globbing. |
| 1895 |
gopherlib Gopher protocol client interface. |
| 1896 |
[DEL:grep:DEL] [DEL:'grep' utilities.:DEL] |
| 1897 |
gzip Read & write gzipped files. |
| 1898 |
heapq Priority queue implemented using lists organized as heaps. |
| 1899 |
HMAC Keyed-Hashing for Message Authentication -- RFC 2104. |
| 1900 |
htmlentitydefs Proposed entity definitions for HTML. |
| 1901 |
htmllib HTML parsing utilities. |
| 1902 |
HTMLParser A parser for HTML and XHTML. |
| 1903 |
httplib HTTP client class. |
| 1904 |
ihooks Hooks into the "import" mechanism. |
| 1905 |
imaplib IMAP4 client.Based on RFC 2060. |
| 1906 |
imghdr Recognizing image files based on their first few bytes. |
| 1907 |
imputil Privides a way of writing customised import hooks. |
| 1908 |
inspect Tool for probing live Python objects. |
| 1909 |
keyword List of Python keywords. |
| 1910 |
knee A Python re-implementation of hierarchical module import. |
| 1911 |
linecache Cache lines from files. |
| 1912 |
linuxaudiodev Lunix /dev/audio support. |
| 1913 |
locale Support for number formatting using the current locale |
| 1914 |
settings. |
| 1915 |
logging Python logging facility. |
| 1916 |
macpath Pathname (or related) operations for the Macintosh. |
| 1917 |
macurl2path Mac specific module for conversion between pathnames and URLs. |
| 1918 |
mailbox A class to handle a unix-style or mmdf-style mailbox. |
| 1919 |
mailcap Mailcap file handling (RFC 1524). |
| 1920 |
mhlib MH (mailbox) interface. |
| 1921 |
mimetools Various tools used by MIME-reading or MIME-writing programs. |
| 1922 |
mimetypes Guess the MIME type of a file. |
| 1923 |
MimeWriter Generic MIME writer. |
| 1924 |
mimify Mimification and unmimification of mail messages. |
| 1925 |
mmap Interface to memory-mapped files - they behave like mutable |
| 1926 |
strings./font> |
| 1927 |
multifile Class to make multi-file messages easier to handle. |
| 1928 |
mutex Mutual exclusion -- for use with module sched. |
| 1929 |
netrc |
| 1930 |
nntplib An NNTP client class. Based on RFC 977. |
| 1931 |
ntpath Common operations on DOS pathnames. |
| 1932 |
nturl2path Mac specific module for conversion between pathnames and URLs. |
| 1933 |
optparse A comprehensive tool for processing command line options. |
| 1934 |
os Either mac, dos or posix depending system. |
| 1935 |
[DEL:packmail: [DEL:Create a self-unpacking shell archive.:DEL] |
| 1936 |
DEL] |
| 1937 |
pdb A Python debugger. |
| 1938 |
pickle Pickling (save and restore) of Python objects (a faster |
| 1939 |
Cimplementation exists in built-in module: cPickle). |
| 1940 |
pipes Conversion pipeline templates. |
| 1941 |
pkgunil Utilities for working with Python packages. |
| 1942 |
popen2 variations on pipe open. |
| 1943 |
poplib A POP3 client class. Based on the J. Myers POP3 draft. |
| 1944 |
posixfile Extended (posix) file operations. |
| 1945 |
posixpath Common operations on POSIX pathnames. |
| 1946 |
pprint Support to pretty-print lists, tuples, & dictionaries |
| 1947 |
recursively. |
| 1948 |
profile Class for profiling python code. |
| 1949 |
pstats Class for printing reports on profiled python code. |
| 1950 |
pydoc Utility for generating documentation from source files. |
| 1951 |
pty Pseudo terminal utilities. |
| 1952 |
pyexpat Interface to the Expay XML parser. |
| 1953 |
py_compile Routine to "compile" a .py file to a .pyc file. |
| 1954 |
pyclbr Parse a Python file and retrieve classes and methods. |
| 1955 |
Queue A multi-producer, multi-consumer queue. |
| 1956 |
quopri Conversions to/from quoted-printable transport encoding. |
| 1957 |
rand Don't use unless you want compatibility with C's rand(). |
| 1958 |
random Random variable generators |
| 1959 |
re Regular Expressions. |
| 1960 |
repr Redo repr() but with limits on most sizes. |
| 1961 |
rexec Restricted execution facilities ("safe" exec, eval, etc). |
| 1962 |
rfc822 RFC-822 message manipulation class. |
| 1963 |
rlcompleter Word completion for GNU readline 2.0. |
| 1964 |
robotparser Parse robots.txt files, useful for web spiders. |
| 1965 |
sched A generally useful event scheduler class. |
| 1966 |
sets Module for a set datatype. |
| 1967 |
sgmllib A parser for SGML. |
| 1968 |
shelve Manage shelves of pickled objects. |
| 1969 |
shlex Lexical analyzer class for simple shell-like syntaxes. |
| 1970 |
shutil Utility functions usable in a shell-like program. |
| 1971 |
SimpleHTTPServer Simple extension to base http class |
| 1972 |
site Append module search paths for third-party packages to |
| 1973 |
sys.path. |
| 1974 |
smtplib SMTP Client class (RFC 821) |
| 1975 |
sndhdr Several routines that help recognizing sound. |
| 1976 |
SocketServer Generic socket server classes. |
| 1977 |
stat Constants and functions for interpreting stat/lstat struct. |
| 1978 |
statcache Maintain a cache of file stats. |
| 1979 |
statvfs Constants for interpreting statvfs struct as returned by |
| 1980 |
os.statvfs()and os.fstatvfs() (if they exist). |
| 1981 |
string A collection of string operations. |
| 1982 |
StringIO File-like objects that read/write a string buffer (a fasterC |
| 1983 |
implementation exists in built-in module: cStringIO). |
| 1984 |
sunau Stuff to parse Sun and NeXT audio files. |
| 1985 |
sunaudio Interpret sun audio headers. |
| 1986 |
symbol Non-terminal symbols of Python grammar (from "graminit.h"). |
| 1987 |
tabnanny,/font> Check Python source for ambiguous indentation. |
| 1988 |
tarfile Facility for reading and writing to the *nix tarfile format. |
| 1989 |
telnetlib TELNET client class. Based on RFC 854. |
| 1990 |
tempfile Temporary file name allocation. |
| 1991 |
textwrap Object for wrapping and filling text. |
| 1992 |
threading Proposed new higher-level threading interfaces |
| 1993 |
threading_api (doc of the threading module) |
| 1994 |
toaiff Convert "arbitrary" sound files to AIFF files . |
| 1995 |
token Tokens (from "token.h"). |
| 1996 |
tokenize Compiles a regular expression that recognizes Python tokens. |
| 1997 |
traceback Format and print Python stack traces. |
| 1998 |
tty Terminal utilities. |
| 1999 |
turtle LogoMation-like turtle graphics |
| 2000 |
types Define names for all type symbols in the std interpreter. |
| 2001 |
tzparse Parse a timezone specification. |
| 2002 |
unicodedata Interface to unicode properties. |
| 2003 |
urllib Open an arbitrary URL. |
| 2004 |
urlparse Parse URLs according to latest draft of standard. |
| 2005 |
user Hook to allow user-specified customization code to run. |
| 2006 |
UserDict A wrapper to allow subclassing of built-in dict class. |
| 2007 |
UserList A wrapper to allow subclassing of built-in list class. |
| 2008 |
UserString A wrapper to allow subclassing of built-in string class. |
| 2009 |
[DEL:util:DEL] [DEL:some useful functions that don't fit elsewhere !!:DEL] |
| 2010 |
uu UUencode/UUdecode. |
| 2011 |
unittest Utilities for implementing unit testing. |
| 2012 |
wave Stuff to parse WAVE files. |
| 2013 |
weakref Tools for creating and managing weakly referenced objects. |
| 2014 |
webbrowser Platform independent URL launcher. |
| 2015 |
[DEL:whatsound: [DEL:Several routines that help recognizing sound files.:DEL] |
| 2016 |
DEL] |
| 2017 |
whichdb Guess which db package to use to open a db file. |
| 2018 |
xdrlib Implements (a subset of) Sun XDR (eXternal Data |
| 2019 |
Representation) |
| 2020 |
xmllib A parser for XML, using the derived class as static DTD. |
| 2021 |
xml.dom Classes for processing XML using the Document Object Model. |
| 2022 |
xml.sax Classes for processing XML using the SAX API. |
| 2023 |
xmlrpclib Support for remote procedure calls using XML. |
| 2024 |
zipfile Read & write PK zipped files. |
| 2025 |
[DEL:zmod:DEL] [DEL:Demonstration of abstruse mathematical concepts.:DEL] |
| 2026 |
|
| 2027 |
|
| 2028 |
|
| 2029 |
* Built-ins * |
| 2030 |
|
| 2031 |
sys Interpreter state vars and functions |
| 2032 |
__built-in__ Access to all built-in python identifiers |
| 2033 |
__main__ Scope of the interpreters main program, script or stdin |
| 2034 |
array Obj efficiently representing arrays of basic values |
| 2035 |
math Math functions of C standard |
| 2036 |
time Time-related functions (also the newer datetime module) |
| 2037 |
marshal Read and write some python values in binary format |
| 2038 |
struct Convert between python values and C structs |
| 2039 |
|
| 2040 |
* Standard * |
| 2041 |
|
| 2042 |
getopt Parse cmd line args in sys.argv. A la UNIX 'getopt'. |
| 2043 |
os A more portable interface to OS dependent functionality |
| 2044 |
re Functions useful for working with regular expressions |
| 2045 |
string Useful string and characters functions and exceptions |
| 2046 |
random Mersenne Twister pseudo-random number generator |
| 2047 |
thread Low-level primitives for working with process threads |
| 2048 |
threading idem, new recommanded interface. |
| 2049 |
|
| 2050 |
* Unix/Posix * |
| 2051 |
|
| 2052 |
dbm Interface to Unix ndbm database library |
| 2053 |
grp Interface to Unix group database |
| 2054 |
posix OS functionality standardized by C and POSIX standards |
| 2055 |
posixpath POSIX pathname functions |
| 2056 |
pwd Access to the Unix password database |
| 2057 |
select Access to Unix select multiplex file synchronization |
| 2058 |
socket Access to BSD socket interface |
| 2059 |
|
| 2060 |
* Tk User-interface Toolkit * |
| 2061 |
|
| 2062 |
tkinter Main interface to Tk |
| 2063 |
|
| 2064 |
* Multimedia * |
| 2065 |
|
| 2066 |
audioop Useful operations on sound fragments |
| 2067 |
imageop Useful operations on images |
| 2068 |
jpeg Access to jpeg image compressor and decompressor |
| 2069 |
rgbimg Access SGI imglib image files |
| 2070 |
|
| 2071 |
* Cryptographic Extensions * |
| 2072 |
|
| 2073 |
md5 Interface to RSA's MD5 message digest algorithm |
| 2074 |
sha Interface to the SHA message digest algorithm |
| 2075 |
HMAC Keyed-Hashing for Message Authentication -- RFC 2104. |
| 2076 |
|
| 2077 |
* SGI IRIX * (4 & 5) |
| 2078 |
|
| 2079 |
al SGI audio facilities |
| 2080 |
AL al constants |
| 2081 |
fl Interface to FORMS library |
| 2082 |
FL fl constants |
| 2083 |
flp Functions for form designer |
| 2084 |
fm Access to font manager library |
| 2085 |
gl Access to graphics library |
| 2086 |
GL Constants for gl |
| 2087 |
DEVICE More constants for gl |
| 2088 |
imgfile Imglib image file interface |
| 2089 |
|
| 2090 |
* Suns * |
| 2091 |
|
| 2092 |
sunaudiodev Access to sun audio interface |
| 2093 |
|
| 2094 |
|
| 2095 |
Workspace exploration and idiom hints |
| 2096 |
|
| 2097 |
dir(<module>) list functions, variables in <module> |
| 2098 |
dir() get object keys, defaults to local name space |
| 2099 |
if __name__ == '__main__': main() invoke main if running as script |
| 2100 |
map(None, lst1, lst2, ...) merge lists |
| 2101 |
b = a[:] create copy of seq structure |
| 2102 |
_ in interactive mode, is last value printed |
| 2103 |
|
| 2104 |
|
| 2105 |
|
| 2106 |
|
| 2107 |
|
| 2108 |
|
| 2109 |
|
| 2110 |
Python Mode for Emacs |
| 2111 |
|
| 2112 |
(Not revised, possibly not up to date) |
| 2113 |
Type C-c ? when in python-mode for extensive help. |
| 2114 |
INDENTATION |
| 2115 |
Primarily for entering new code: |
| 2116 |
TAB indent line appropriately |
| 2117 |
LFD insert newline, then indent |
| 2118 |
DEL reduce indentation, or delete single character |
| 2119 |
Primarily for reindenting existing code: |
| 2120 |
C-c : guess py-indent-offset from file content; change locally |
| 2121 |
C-u C-c : ditto, but change globally |
| 2122 |
C-c TAB reindent region to match its context |
| 2123 |
C-c < shift region left by py-indent-offset |
| 2124 |
C-c > shift region right by py-indent-offset |
| 2125 |
MARKING & MANIPULATING REGIONS OF CODE |
| 2126 |
C-c C-b mark block of lines |
| 2127 |
M-C-h mark smallest enclosing def |
| 2128 |
C-u M-C-h mark smallest enclosing class |
| 2129 |
C-c # comment out region of code |
| 2130 |
C-u C-c # uncomment region of code |
| 2131 |
MOVING POINT |
| 2132 |
C-c C-p move to statement preceding point |
| 2133 |
C-c C-n move to statement following point |
| 2134 |
C-c C-u move up to start of current block |
| 2135 |
M-C-a move to start of def |
| 2136 |
C-u M-C-a move to start of class |
| 2137 |
M-C-e move to end of def |
| 2138 |
C-u M-C-e move to end of class |
| 2139 |
EXECUTING PYTHON CODE |
| 2140 |
C-c C-c sends the entire buffer to the Python interpreter |
| 2141 |
C-c | sends the current region |
| 2142 |
C-c ! starts a Python interpreter window; this will be used by |
| 2143 |
subsequent C-c C-c or C-c | commands |
| 2144 |
C-c C-w runs PyChecker |
| 2145 |
|
| 2146 |
VARIABLES |
| 2147 |
py-indent-offset indentation increment |
| 2148 |
py-block-comment-prefix comment string used by py-comment-region |
| 2149 |
py-python-command shell command to invoke Python interpreter |
| 2150 |
py-scroll-process-buffer t means always scroll Python process buffer |
| 2151 |
py-temp-directory directory used for temp files (if needed) |
| 2152 |
py-beep-if-tab-change ring the bell if tab-width is changed |
| 2153 |
|
| 2154 |
|
| 2155 |
The Python Debugger |
| 2156 |
|
| 2157 |
(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) |
| 2158 |
|
| 2159 |
Accessing |
| 2160 |
|
| 2161 |
import pdb (it's a module written in Python) |
| 2162 |
-- defines functions : |
| 2163 |
run(statement[,globals[, locals]]) |
| 2164 |
-- execute statement string under debugger control, with optional |
| 2165 |
global & local environment. |
| 2166 |
runeval(expression[,globals[, locals]]) |
| 2167 |
-- same as run, but evaluate expression and return value. |
| 2168 |
runcall(function[, argument, ...]) |
| 2169 |
-- run function object with given arg(s) |
| 2170 |
pm() -- run postmortem on last exception (like debugging a core file) |
| 2171 |
post_mortem(t) |
| 2172 |
-- run postmortem on traceback object <t> |
| 2173 |
|
| 2174 |
-- defines class Pdb : |
| 2175 |
use Pdb to create reusable debugger objects. Object |
| 2176 |
preserves state (i.e. break points) between calls. |
| 2177 |
|
| 2178 |
runs until a breakpoint hit, exception, or end of program |
| 2179 |
If exception, variable '__exception__' holds (exception,value). |
| 2180 |
|
| 2181 |
Commands |
| 2182 |
|
| 2183 |
h, help |
| 2184 |
brief reminder of commands |
| 2185 |
b, break [<arg>] |
| 2186 |
if <arg> numeric, break at line <arg> in current file |
| 2187 |
if <arg> is function object, break on entry to fcn <arg> |
| 2188 |
if no arg, list breakpoints |
| 2189 |
cl, clear [<arg>] |
| 2190 |
if <arg> numeric, clear breakpoint at <arg> in current file |
| 2191 |
if no arg, clear all breakpoints after confirmation |
| 2192 |
w, where |
| 2193 |
print current call stack |
| 2194 |
u, up |
| 2195 |
move up one stack frame (to top-level caller) |
| 2196 |
d, down |
| 2197 |
move down one stack frame |
| 2198 |
s, step |
| 2199 |
advance one line in the program, stepping into calls |
| 2200 |
n, next |
| 2201 |
advance one line, stepping over calls |
| 2202 |
r, return |
| 2203 |
continue execution until current function returns |
| 2204 |
(return value is saved in variable "__return__", which |
| 2205 |
can be printed or manipulated from debugger) |
| 2206 |
c, continue |
| 2207 |
continue until next breakpoint |
| 2208 |
j, jump lineno |
| 2209 |
Set the next line that will be executed |
| 2210 |
a, args |
| 2211 |
print args to current function |
| 2212 |
rv, retval |
| 2213 |
prints return value from last function that returned |
| 2214 |
p, print <arg> |
| 2215 |
prints value of <arg> in current stack frame |
| 2216 |
l, list [<first> [, <last>]] |
| 2217 |
List source code for the current file. |
| 2218 |
Without arguments, list 11 lines around the current line |
| 2219 |
or continue the previous listing. |
| 2220 |
With one argument, list 11 lines starting at that line. |
| 2221 |
With two arguments, list the given range; |
| 2222 |
if the second argument is less than the first, it is a count. |
| 2223 |
whatis <arg> |
| 2224 |
prints type of <arg> |
| 2225 |
! |
| 2226 |
executes rest of line as a Python statement in the current stack frame |
| 2227 |
q quit |
| 2228 |
immediately stop execution and leave debugger |
| 2229 |
<return> |
| 2230 |
executes last command again |
| 2231 |
Any input debugger doesn't recognize as a command is assumed to be a |
| 2232 |
Python statement to execute in the current stack frame, the same way |
| 2233 |
the exclamation mark ("!") command does. |
| 2234 |
|
| 2235 |
Example |
| 2236 |
|
| 2237 |
(1394) python |
| 2238 |
Python 1.0.3 (Sep 26 1994) |
| 2239 |
Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam |
| 2240 |
>>> import rm |
| 2241 |
>>> rm.run() |
| 2242 |
Traceback (innermost last): |
| 2243 |
File "<stdin>", line 1 |
| 2244 |
File "./rm.py", line 7 |
| 2245 |
x = div(3) |
| 2246 |
File "./rm.py", line 2 |
| 2247 |
return a / r |
| 2248 |
ZeroDivisionError: integer division or modulo |
| 2249 |
>>> import pdb |
| 2250 |
>>> pdb.pm() |
| 2251 |
> ./rm.py(2)div: return a / r |
| 2252 |
(Pdb) list |
| 2253 |
1 def div(a): |
| 2254 |
2 -> return a / r |
| 2255 |
3 |
| 2256 |
4 def run(): |
| 2257 |
5 global r |
| 2258 |
6 r = 0 |
| 2259 |
7 x = div(3) |
| 2260 |
8 print x |
| 2261 |
[EOF] |
| 2262 |
(Pdb) print r |
| 2263 |
0 |
| 2264 |
(Pdb) q |
| 2265 |
>>> pdb.runcall(rm.run) |
| 2266 |
etc. |
| 2267 |
|
| 2268 |
Quirks |
| 2269 |
|
| 2270 |
Breakpoints are stored as filename, line number tuples. If a module is reloaded |
| 2271 |
after editing, any remembered breakpoints are likely to be wrong. |
| 2272 |
|
| 2273 |
Always single-steps through top-most stack frame. That is, "c" acts like "n". |