Вы находитесь на странице: 1из 454

. , ... , ..

Python

. , ... , .. , . , . , . , .. ,
.. , .-. , .-. , . , .. , .. ,
.. , . , . , . .
Python. / 2001 454 c.
Python , , . , ,
, . , ,
, ,
.
Python: 1.5.2 2.0.
c

c

c

c

Stichting Mathematisch Centrum, 19901995


Corporation for National Research Initiatives, 19952000
BeOpen.com, 2000
.. , 2001

3
!
Python.
.
, .
. ,
Python , .
.
Python - .

, , ;
;
- , ;
API ,
C C++;
API ;
,
, , , .
Python , , , GUI (RAD).
, , Python Internet Web (CGI), (), Web- . Python ,
, . Python ,
, IBM, Yahoo!, Google.com,
Hewlett Packard, Infoseek, NASA, Red Hat, CBS MarketWatch, Microsoft.
:
Mailman (mailing list manager), GNU;
Medusa TCP/IP
, HTTP, FTP, NNTP, XML-RPC SOAP;
Zope Web- (Web application server), .

4
Python . ; , , , GUI Web-. CGI-
Python ( www.fom.ru ), , Python ( , www.russ.ru ). Zope. : Full.RU (www.full.ru ),
(www.menatep.spb.ru ),
(www.interbit.ru ) .
Python Zope, (zope.net.ru ) Zope.
, ,
Python Zope.

. ,
Python Zope .
, , .

BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0

13

15

17

2
2.1 . . . . . . . . . . . . . . . . . . . . . . .
2.1.1 . . . . . . . . . . . . . . . . . . .
2.1.2 . . . . . . . . . . . . . . . . . .
2.2 . . . . . . . . . . . . . . . . . . . .
2.2.1 . . . . . . . . . . . . . . . . . . . .
2.2.2 . . . . . . . . . . . . . . . . . . .
2.2.3
3 Python
3.1 Python
3.1.1 . . . . . . . . . . . . . .
3.1.2 . . . . . . . . . . . . .
3.1.3 Unicode . . . . . . . .
3.1.4 . . . . . . . . . . . . .
3.2 . .

.
.
.
.
.

.
.
.
.
.
.
.


. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .

4
4.1 if . . . . . . . . . . . . . . . . . . . . . . .
4.2 for . . . . . . . . . . . . . . . . . . . . . .
4.3 range() xrange() . . . . . . . . . . . . .
4.4 break continue, else
4.5 pass . . . . . . . . . . . . . . . . . . . . .
4.6 . . . . . . . . . . . . . . . . . . .
4.7
4.7.1 . . . . . .
4.7.2 . . . . . . . .
4.7.3 . . . . . . . . . . . . .
4.7.4 . . . . . . . . . . . . . . . . . .
4.7.5 . . . . . . . . . . . . . . .
4.7.6 . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

19
19
20
20
21
21
21
21

.
.
.
.
.
.

23
23
23
26
30
32
34

.
.
.
.
.
.
.
.
.
.
.
.
.

36
36
36
37
39
39
40
42
42
43
43
45
45
46

5
47
5.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

5.2
5.3
5.4
5.5
5.6
5.7
5.8

. . .

del . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . .

6
6.1 . . . . .
6.2 . . . . . . . . . . . . . . . .
6.3 . . . . . . . . .
6.4 . . . . . . . . . . . . .
6.5 dir() . . . . . . . . . . . . . . .
6.6 . . . . . . . . . . . . . . . . . . . . .
6.6.1
6.6.2 . . .
7 /
7.1 . . . .
7.2 . . . . .
7.2.1 -
7.2.2 pickle . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

8
8.1 . . . . . . . . . . .
8.2 . . . . . . . . . . . . . . . . . .
8.3 . . . . . . . . . . .
8.4 . . . . . . . . . . .
8.5 ,
8.6 . . . . . . . . . .

. . . . .

. . . . .
. . . . .
. . . . .
. . . . .
. . . . .

. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
()
. . . . . . . . . .
.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

. .
.
. .
. .
. .
. .
. .
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.

49
51
52
53
55
56
57

.
.
.
.
.
.
.
.

58
58
61
61
62
63
64
66
67

.
.
.
.

68
68
72
73
74

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

76
76
76
77
80
80
80

9
9.1 . . . . . . . . . . .
9.2 . . . . . .
9.3 . . . . . . . . . . . . . . .
9.3.1 . . . . . . .
9.3.2 - . . . . . . . . . . . . . . . .
9.3.3 - . . . . . . . . . . . . .
9.3.4 . . . . . . . .
9.4 . . . . . . . . . . . . . . . .
9.5 . . . . . . . . . . . . . . . . . . . . . .
9.6 . . . . . . . . . . . . . . . . . . .
9.7 . . . . . . . . . . .
9.7.1
9.7.2 - . . . . . . . . . . . . . .
9.7.3 . . . . . . . . . . . . . . . . . . .
9.7.4 . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

82
82
83
84
85
85
86
87
88
90
91
92
92
94
95
98

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

II

10
10.1 . . . . . . . . . . .
10.1.1 . . . .
10.1.2 . . . . . . . . . . . . . . . . .
10.2 . . . . . . . . . . . . . . . . . . . .
10.2.1 . . . . . . . . . . . . . . . . . . .
10.2.2 . . . . . . . . .
10.2.3
10.2.4 . . . . . . . . . .
10.2.5 . . . . . . . . . . . . . . . .
10.2.6 . . . . . . . . .
10.2.7 lambda . . . . . . . . . . . .
10.2.8 . . . . . . . . . . .
10.2.9 . . . . .
10.3 . . . . . . . . . . . . . . .
10.3.1 - . . . . . . . . .
10.3.2 . . . . . . . . . . . . . .
10.3.3 del . . . . . . . . . . . . .
10.3.4 . . . . . . . . . . .
10.3.5 print . . . . . . . . . . .
10.3.6 break . . . . . . . . . . .
10.3.7 continue . . . . . . . . .
10.3.8 return . . . . . . . . . .
10.3.9 global . . . . . . . . . .
10.3.10 import . . . . . . . . . .
10.3.11 exec . . . . . . . . . . . .
10.3.12 . . . . . . .
10.3.13 . . . . . . . . .
10.4 . . . . . . . . . . . . . .
10.4.1 if . . . . . . . . . . . . .
10.4.2 while . . . . . . . . . . . . . . .
10.4.3 for . . . . . . . . . . . . . . . . .
10.4.4 try . . . . . . . . . . . . .
10.4.5 . . . . . . . . .
10.4.6 . . . . . . . . . . .
10.5 . . . . . . . . . . . . . . . .
11
11.1 . . . . . . . . . . . . . . . . . .
11.1.1 . . . . .
11.1.2 . . . . . . . . . .
11.1.3 . . . . . . . . . . .
11.1.4 . . . . . .
11.1.5
11.2 . . . . . . . . . . . . . . .
11.2.1 . . . . . . . . . . . . . . . . . .

99
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
. .
. .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

102
. 102
. 102
. 103
. 104
. 105
. 106
. 108
. 108
. 110
. 110
. 111
. 111
. 112
. 112
. 113
. 113
. 115
. 115
. 115
. 116
. 116
. 117
. 117
. 117
. 119
. 120
. 120
. 121
. 122
. 122
. 123
. 124
. 125
. 128
. 128

.
.
.
.
.
.
.
.

131
. 131
. 132
. 132
. 133
. 133
. 134
. 135
. 136

11.3
11.4

11.5
11.6

11.7
11.8

11.9

11.2.2 Unicode . . . . . . . . . . . . . . .
11.2.3 . . . . . . . . . . . . . . . . . . .
11.2.4 xrange . . . . . . . . . . . . . .
11.2.5 buffer . . . . . . . . . . . . . .
11.2.6 . . . . .
. . . . . . . . . . . . . . . . . . . . .
, . . . . . . . . .
11.4.1 , . .
11.4.2 , . .
11.4.3 . . . . . .
11.4.4 . . . . . . . . . . . . . . . . . . . .
11.4.5 . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
11.6.1 . . . . . . . . . . . . . . . . . . . .
11.6.2 . . . . . . . . . . . .
11.6.3 . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
11.8.1 . . . . . . . . . . . . . . . .
11.8.2 . . . . . . . . . . . . . . . .
11.8.3
. . . . . . . . . . . . . . . . . .
11.9.1 . . . . . . . . . . . . . . . .
11.9.2 . . . . . . . . . . . . . . . . . .
11.9.3 traceback . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. 143
. 144
. 144
. 145
. 145
. 147
. 148
. 149
. 149
. 150
. 151
. 151
. 151
. 152
. 152
. 152
. 153
. 163
. 165
. 165
. 165
. 166
. 166
. 166
. 168
. 169

12

170

13

182

III

187

14
190
14.1 site . . . . . . . . . . . . . . . . . . . . . . . . . . 190
14.2 user . . . . . . . . . . . . . . . . . . . . . . 191
15
192
15.1 sys . . . . . . . . . . . 192
15.2 gc . . . . . . . . . . . . . . . . . . . . 198
15.3 atexit . . . . 200
15.4 types . . . . . . . . . . . . . . . . . . 201
15.5 operator . . . . . . . . . . . . . . . . . . . 204
15.6 traceback traceback . . . . . . . . 208
15.7 imp , import . . . . . 211
15.8 pprint 212
15.9 repr repr() . . . . . . . . . . . . 215

16
217
16.1 string . . . . . . 217
16.2 re . . . . . . . . . . . . . . . . . 220
16.2.1 . . . . . . . . . . . . . . . . . . 220
16.2.2 . . . . . . . . . . . . . . . . 225
16.2.3 , . . . . . . . . . . . 225
16.2.4 , . . . . . . . . . 228
16.2.5 , . . . . . . . . 229
16.3 StringIO cStringIO 231
16.4 codecs . . . . . . . . . . . . . . . 232
17
17.1 locale .
17.2 gettext . . . . .
17.2.1 GNU gettext . . . . . . . . . . . . . . .
17.2.2 , . . . . . . . .
17.2.3

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

236
. 236
. 240
. 240
. 241
. 244

18
245
18.1 math . 245
18.2 cmath . 247
18.3 random . . . . 249
18.4 whrandom . . . . . . . . . . . . . . . 250
18.5 bisect 251
18.6 array . . . . . . . . . . . . . . . . . . . . . 252
19
19.1 UserString
19.2 UserList .
19.3 UserDict . . . . . .

255
. 255
. 256
. 257

20
20.1 pickle cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
20.2 shelve DBM . . . . . . .
20.3 marshal - . . . . . . .
20.4 struct C . . . . . . . .

258
. 258
. 262
. 263
. 264

21 ,
21.1 os . . . . . . . . . .
21.1.1 . . . . . . . . . . . . . . . . . . . .
21.1.2 . . . . . . . . . . . . . . .
21.1.3 . . . . . . . . . .
21.1.4 . . . . . . . . . . . . . . . . . . . . . .
21.1.5 . . . . . . . . . . . . . . . . . .
21.1.6 . . . . . . . . . . . .
21.2 os.path . . . . . . . . . . . . . . . .
21.3 stat os.stat() . . . . . . . . . . . . . . . .

266
. 267
. 267
. 269
. 270
. 273
. 276
. 279
. 280
. 283

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

10

21.4 statvfs os.statvfs() . . . . . . . . . . .


21.5 filecmp . . . . . . . . . . . .
21.6 popen2 /
21.7 time . . . . . . . . . . . .
21.8 sched . . . . . . . . . . . . . . . . . . . .
21.9 getpass .
21.10 getopt . . . . . . . . .
21.11 tempfile . . . . . . . . . . . . .
21.12 errno
21.13 glob . . . . . . . . . . . . . .
21.14 fnmatch . . . . . .
21.15 shutil . . . . . . .
21.16 signal . . . . . . . . . . .
21.17 socket . . . . . . . . . .
21.18 select / . . . . . . . . .
21.19 mmap . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

. 285
. 286
. 288
. 289
. 294
. 295
. 296
. 298
. 299
. 302
. 303
. 304
. 305
. 307
. 313
. 315

.
.
.
.
.
.
.
.

318
. 318
. 320
. 321
. 321
. 323
. 323
. 324
. 325

22
22.1 thread . .
22.2 threading
22.2.1 , . . . . . . . . . . .
22.2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . .
22.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . .
22.2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . .
22.2.5 , . . . . . . . . . . . .
22.3 Queue . . . . . . . . . . . . .

.
.
.
.
.
.
.
.

23
23.1 DBM . . . . . . . . . . . .
23.1.1 . . . . . . .
23.1.2 ,
dbhash.open() . . . . . . . . . . . . . . . . . . . . . .
23.1.3 ,
gdbm.open() . . . . . . . . . . . . . . . . . . . . . . .
23.2 whichdb . . . . .
23.3 bsddb BSD . . . . . .

327
. . . . . . . 327
. . . . . . . 328

. . . . . . . 329

. . . . . . . 329
. . . . . . . 330
. . . . . . . 330

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

24
333
24.1 zlib , gzip . . . . . . . . . . . . . . . . 333
24.2 gzip , gzip . . . . . . . . . . . 336
24.3 zipfile zip- . . . . . . . . . . . . . . . . . . . . . . . 336
25 Python
25.1 Python . . . . . . . . .
25.1.1 . . . . . .
25.1.2 . . . . . . . . . . .
25.2 . . . . . . . . . . .
25.2.1 . . . . . . . . . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

340
. 340
. 341
. 342
. 345
. 345

11

25.2.2 profile . . . . . . . . . . . . . . . . 347


25.2.3 pstats . . 348
26
350
26.1 rexec . . . . . . . 351
26.2 Bastion . . . . . . . . . . 354
27 Internet
27.1 cgi CGI . . . . . . . . . . . . . . . . .
27.1.1 . . . . . . . . . . . . . . . . . . .
27.1.2 cgi . . . . . . . .
27.1.3 . . .
27.1.4 . . . . . . . . . . . .
27.1.5 CGI- . . . . . . . . . .
27.1.6 . . . . . . . . . . . . . . . . . . . .
27.2 urllib URL
27.3 urlparse URL . . . . . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

28 , Internet
28.1 rfc822 . . . . . . . .
28.2 mimetools MIME . . . . . . .
28.3 MimeWriter MIME . . . . . . .
28.4 multifile ,
28.5 xdrlib XDR . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

355
. 355
. 355
. 356
. 359
. 361
. 361
. 362
. 363
. 367

.
.
.
.
.

369
. 369
. 373
. 374
. 376
. 378

29
29.1 sgmllib SGML- . . . . . . . . . . . . . . . . . .
29.2 htmllib HTML- . . . . . . . . . . . . . . . . . .
29.3 htmlentitydefs HTML . . . . . . . . . . .
29.4 xml.parsers.expat XML-
Expat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29.5 xml.sax SAX2 XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29.6 xml.sax.handler SAX- .
29.6.1 ContentHandler . . . . . . . . . . . . . . . .
29.6.2 DTDHandler . . . . . . . . . . . . . . . . . . .
29.6.3 ErrorHandler . . . . . . . . . . . . . . . . .
29.6.4 EntityResolver . . . . . . . . . . . . . . . .
29.7 xml.sax.saxutils , SAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29.8 xml.sax.xmlreader ,
XML- . . . . . . . . . . . . . . . . . . .
29.8.1 XMLReader . . . . . . . . . . . . . . . . . . .
29.8.2 IncrementalParser . . . . . . . . . . . . .
29.8.3 Locator . . . . . . . . . . . . . . . . . . . . .
29.8.4 InputSource . . . . . . . . . . . . . . . . .
29.8.5 AttributesImpl AttributesNSImpl

383
. 383
. 386
. 388
. 388
. 392
. 394
. 395
. 397
. 397
. 398
. 398
. 399
. 400
. 401
. 402
. 402
. 403

12

29.9 xmllib XML- . . . . . . . . . . . . . . . . . . . . 404

30
30.1 fileinput
30.2 ConfigParser . . . . .
30.3 shlex . . . . . . . . .
30.4 cmd . . . . . . . . . .
30.5 calendar . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

409
. 409
. 412
. 415
. 417
. 419

423

A
425
B

428

433

435

13

BEOPEN.COM TERMS AND


CONDITIONS FOR PYTHON 2.0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT
VERSION 1
1. This LICENSE AGREEMENT is between BeOpen.com (BeOpen), having an office
at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
(Licensee) accessing and otherwise using this software in source or binary form and
its associated documentation (the Software).
2. Subject to the terms and conditions of this BeOpen Python License Agreement,
BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to
reproduce, analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use the Software alone or in any derivative version, provided,
however, that the BeOpen Python License is retained in the Software, alone or in any
derivative version prepared by Licensee.
3. BeOpen is making the Software available to Licensee on an AS IS basis. BEOPEN
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY
OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE
SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS
OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL
DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE
POSSIBILITY THEREOF.
5. This License Agreement will automatically terminate upon a material breach of its
terms and conditions.
6. This License Agreement shall be governed by and interpreted in all respects by the
law of the State of California, excluding conflict of law provisions. Nothing in this
License Agreement shall be deemed to create any relationship of agency, partnership,
or joint venture between BeOpen and Licensee. This License Agreement does not grant
permission to use BeOpen trademarks or trade names in a trademark sense to endorse
or promote products or services of Licensee, or any third party. As an exception, the
BeOpen Python logos available at http://www.pythonlabs.com/logos.html may be
used according to the permissions granted on that web page.

14

BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0


7. By copying, installing or otherwise using the software, Licensee agrees to be bound
by the terms and conditions of this License Agreement.

CNRI OPEN SOURCE LICENSE AGREEMENT


Python 1.6 is made available subject to the terms and conditions in CNRIs License
Agreement. This Agreement together with Python 1.6 may be located on the Internet
using the following unique, persistent identifier (known as a handle): 1895.22/1012. This
Agreement may also be obtained from a proxy server on the Internet using the following
URL: http://hdl.handle.net/1895.22/1012.

CWI PERMISSIONS STATEMENT AND DISCLAIMER


c 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands.
Copyright
All rights reserved.
Permission to use, copy, modify, and distribute this software and its documentation
for any purpose and without fee is hereby granted, provided that the above copyright notice
appear in all copies and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI
not be used in advertising or publicity pertaining to distribution of the software without
specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING
MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

17


- shell-, , , :
- , , , ,
C. . . ,
C. ,
(, ), shell, C,
C.
: C,
. . ,
, ,
, .
, Python , . Python ,
,
, shell. ,
, C , , , ,
C .
, Python ,
Awk Perl, Python
.
Python , . Python ,
.
, ,
.
Python ,
, . , ,
.
.
Python . , Python, C

18

1.

C++ :

;
;
.
Python : C
, . Python , C,
.
, BBC Monty Pythons Flying Circus
.
, Python,
. ,
. , . , ,
.
, , , , ,
.

19


2.1

Python ,

python
EOF (Ctrl-D
UNIX, Ctrl-Z DOS Windows) .
, import sys; sys.exit().
UNIX shell:
;

, .
python -c
command [arg . . . ].
command, -c UNIX shell. Python ,
, , command
.
, python file python < file.
, , input() raw_input() . ,
, EOF. (
), , Python.
. , -i . (
, , , .)
A.

20

2.1.1

2.

() sys.argv, . ( ) .
sys.argv[0]. sys.argv[0] .
- ( ) -c, sys.argv[0] - -c
. , -c command Python, sys.argv
command.

2.1.2

, , . , (>>> ); ,
(... ).
, :
$ python
Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license" for more
information.
>>>

. , if:
>>> the_world_is_flat = 1
>>> # ,
... if the_world_is_flat:
...
print ", !"
...
, !

2.2.

2.2
2.2.1

21

. , . , ,
. (,
except try, .)
. ;
, ,
.
( Ctrl-C)
KeyboardInterrupt, try.

2.2.2
UNIX Python
, , ,
#!/usr/bin/env python
(, PATH
) . #! . , # Python
.

2.2.3

Python , , .
PYTHONSTARTUP , ( .profile UNIX shell).
,
,
. ,
, - .
(sys.ps1) (sys.ps2) .

22

2.


, , :
if os.path.isfile(.pythonrc.py):
execfile(.pythonrc.py)
, :
import os
filename = os.environ.get(PYTHONSTARTUP)
if filename and os.path.isfile(filename):
execfile(filename)

23

Python
(>>> ... ):
. , , . ,
,

.
, , . Python # .
, . #
#.
:
#
SPAM = 1
#
# ... , , !
STRING = "# ."

3.1

Python

Python. >>> ( .)

3.1.1

: ,
. : +, -, * / ,
(, Pascal C).
. :

24
>>>
4
>>>
...
4
>>>
4
>>>
5
>>>
...
...
2
>>>
-3

3. Python
2+2
#
2+2
2+2

# ,

(50-5*6)/4
#
# :
7/3
7/-3

, (=) . :
>>> width = 20
>>> height = 5*9
>>> width * height
900
:
>>>
>>>
0
>>>
0
>>>
0

x = y = z = 0 # x, y z 0
x
y
z

.
:
>>> 4 * 2.5 / 3.3
3.0303030303030303
>>> 7.0 / 2
3.5
. j J. (real+imagj)
complex(real, imag).

3.1. Python

25

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
. z, z.real and z.imag.
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
(int(),
long() float())
. abs(z) z.real
.
>>> a=1.5+0.5j
>>> float(a)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: cant convert complex to float; use e.g.
abs(z)
>>> a.real
1.5
>>> abs(a)
1.5811388300841898
_. Python , :
>>> tax = 17.5 / 100
>>> price = 3.50
>>> price * tax
0.61249999999999993
>>> price + _

26

3. Python

4.1124999999999998
>>> print round(_, 2)
4.11
, .

, .

3.1.2
, Python (string),
1 .
:
>>> spam eggs
spam eggs
>>> doesn\t
"doesnt"
>>> "doesnt"
"doesnt"
>>> "Yes," he said.
"Yes," he said.
>>> "\"Yes,\" he said."
"Yes," he said.
>>> "Isn\t," she said.
"Isn\t," she said.

.
(\), :
hello = " , \n\
, C.\n\
, \
\n .\n"
print hello
:
,
, C.
1

Python 7- .
,
, , .
.

3.1. Python

27

,
.
-, : """ . ,
.
print """
Usage: thingy [OPTIONS]
-h
-H hostname
"""

Display this usage message


Hostname to connect to

:
Usage: thingy [OPTIONS]
-h
-H hostname

Display this usage message


Hostname to connect to

,
: ,
,
(\). , ,
, . print, ,
.
,
r R :
,
,
.
. ,
, , .
() + *:
>>> word = Help + A
>>> word
HelpA
>>> < + word*5 + >
<HelpAHelpAHelpAHelpAHelpA>
, , . word = Help A.

28

3. Python

, .
>>> str ing
string
>>> str.strip()
string
>>> str.strip()
File "<stdin>",
str.strip()

#
+ ing

ing
#
line 1
ing
^
SyntaxError: invalid syntax
,
. C,
0. , .
Icon, ,
.
>>> word[4]
A
>>> word[0:2]
He
>>> word[2:4]
lp
Python . :
>>> word[0] = x
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: object doesnt support item assignment
>>> word[:-1] = Splat
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: object doesnt support slice assignment
:
0, ,
.
>>> word[:2]
He
>>> word[2:]
lpA

#
# ,

3.1. Python

29

: s[:i] + s[i:] s.
>>> word[:2] + word[2:]
HelpA
>>> word[:3] + word[3:]
HelpA
: , ;
, .
>>> word[1:100]
elpA
>>> word[10:]

>>> word[2:1]

, :
>>> word[-1]
A
>>> word[-2]
p
>>> word[-2:]
pA
>>> word[:-2]
Hel

#
#
#
#

-0 , 0, .
>>> word[-0]
H

# ( -0 0)

,
, (
):
>>> word[-100:]
HelpA
>>> word[-10]
#
Traceback (innermost last):
File "<stdin>", line 1
IndexError: string index out of range

30

3. Python

, , 0 .
, :

H
0
5

e
1
4

l
2
3

p
3
2

A
4
1

,
0 5, . i j
, i j, .
, , , word[1:3]
2.
len() :
>>> s = supercalifragilisticexpialidocious
>>> len(s)
34

3.1.3

Unicode

1.6, Python
Unicode. , , Unicode (.
http://www.unicode.org). Unicode ,
, , .
Unicode , .
256 ,
, (internationalization, i18n i + 18 + n) . Unicode
, .
Unicode , :
>>> uHello World !
uHello World !

3.1. Python

31

u ,
Unicode. , :
>>> uHello\u0020World !
uHello World !
\u0020 , Unicode
0x0020 ().
, 256 Unicode , Latin-1, , ,
.
, Unicode , r R . ,
Unicode,
u:
>>> urHello\u0020World !
uHello World !
>>> urHello\\u0020World !
uHello\\\\u0020World !
, Python
Unicode . unicode()
Latin-1, ASCII, UTF-8, UTF-16, ISO-88595, KOI8-R, CP1251, CP866 Mac-cyrillic, . Python
ASCII2 , , print
. ,
Unicode unicode(),
:
>>> s = unicode("", "KOI8-R")
>>> s
u\u041F\u0440\u0438\u0432\u0435\u0442
Unicode 127,
ASCII :
>>> str(s)
Traceback (most recent call last):
2

ASCII . sys.set_string_encoding(). .

32

3. Python

File "<stdin>", line 1, in ?


UnicodeError: ASCII encoding error: ordinal not in
range(128)
encode() Unicode , :
>>> s.encode("KOI8-R")
\360\322\311\327\305\324
>>> s.encode("UTF-8")
\320\237\321\200\320\270\320\262\320\265\321\202

3.1.4
Python ,
. (list),
(), ,
. , .
>>> a = [spam, eggs, 100, 1234]
>>> a
[spam, eggs, 100, 1234]
, .
, :
>>> a[0]
spam
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
[eggs, 100]
>>> a[:2] + [bacon, 2*2]
[spam, eggs, bacon, 4]
>>> 3*a[:3] + [Boe!]
[spam, eggs, 100, spam, eggs, 100, spam,
eggs, 100, Boe!]
, (immutable),
:
>>> a
[spam, eggs, 100, 1234]

3.1. Python

33

>>> a[2] = a[2] + 23


>>> a
[spam, eggs, 123, 1234]
,
:
>>> # :
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # :
... a[0:2] = []
>>> a
[123, 1234]
>>> # :
... a[1:1] = [bletch, xyzzy]
>>> a
[123, bletch, xyzzy, 1234]
>>> # :
>>> a[:0] = a
>>> a
[123, bletch, xyzzy, 1234, 123, bletch, xyzzy,
1234]
len() :
>>> len(a)
8
(, ), :
>>>
>>>
>>>
3
>>>
[2,
>>>
2
>>>
>>>
[1,
>>>
[2,

q = [2, 3]
p = [1, q, 4]
len(p)
p[1]
3]
p[1][0]
p[1].append(xtra)
p
[2, 3, xtra], 4]
q
3, xtra]

, , , append() .
, p[1] q !

34

3. Python

3.2

, Python , .
, :
>>>
...
...
...
>>>
...
...
...
1
1
2
3
5
8

# :
#
#
a, b = 0, 1
while b < 10:
print b
a, b = b, a+b

.
(multiple assignment): a b 0 1.
, , .
.
while (: b < 10) .
Python, , , .
,
. ,
. , , . , : <, >, ==,
<= ( ), >= ( ) != ( ).
: Python . ()
, .
Python ,
.
, ,
( , ). ,
.

3.2.

35

print . ( ),
print
, :
>>> i = 256*256
>>> print i , i
i 65536

:
>>> a, b = 0, 1
>>> while b < 1000:
...
print b,
...
a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
,
,
.

36


while, Python
.

4.1

if

, if:
>>>
>>>
...
...
...
...
...
...
...
...
...

x = int(raw_input(", , : "))
if x < 0:
x = 0
print ,
elif x == 0:
print
elif x == 1:
print
else:
print

elif , , ; else . elif


else if . if ...
elif ... elif ... switch case .

4.2

for

for Python ,
C Pascal. ,
( Pascal),
( ), 1
1

: Python ;

4.3. range() xrange()

37

(, ) :
>>> # :
... a = [, , ]
>>> for x in a:
...
print x, len(x)
...
3
4
9
(
, , , ).
, , ,
,
. :
>>> for x in a[:]: # ()
...
if len(x) > 4: a.insert(0, x)
...
>>> for x in a:
...
print x,
...

(. 5.2),
.

4.3

range() xrange()

,
range(). , :
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.
range(10) 10 , , 10.
(), :
( for) .

38

4.

>>> range(5, 10)


[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
, ,
range() len():
>>> a = [, , , , ]
>>> for i in range(len(a)):
...
print i, a[i]
...
0
1
2
3
4
,
, ,
:
>>> l=range(10000000)
Traceback (innermost last):
File "<stdin>", line 1, in ?
MemoryError
, , , ,
. Python
xrange():
>>> xrange(5, 10)
(5, 6, 7, 8, 9)
>>> xrange(0, 10, 3)
(0, 3, 6, 9)
>>> xrange(-10, -100, -30)
(-10, -40, -70)
>>> a = [, , , , ]
>>> for i in xrange(len(a)):
...
print i, a[i]
...
0
1

4.4. break continue, else

39

2
3
4

4.4

break continue, else

break, C, for
while. continue, C, .
else, ( for,
while), break.
:
>>>
...
...
...
...
...
...
...
2 3 4 =
5 6 =
7 8 =
9 =

for n in xrange(2, 10):


for x in xrange(2, n):
if n % x == 0:
print n, =, x, *, n/x
break
else:
print n, -

2 * 2

2 * 3

2 * 4
3 * 3

4.5 pass
pass ,
, :
>>> while 1:
...
pass #
...

40

4.

4.6

, :
>>>
...
...
...
...
...
...
...
>>>
...
1 1

def fib(n):
,
n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
#
fib(2000)
2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

def . , , . , , , .
(. 4.7.5). , , .
.
,
. , . ,
, , , . ,
( global), .
. , (
, )2 .
, .
. ,
. ,
( ):
>>> fib
<function object at 10042ed0>
2

, , :
, , (, )
, .

4.6.

41

>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
, fib , .
Python, C, ,
. , , , ,
. None ( ).
None , , :
>>> print fib(0)
None
, , , :
>>>
...
...
...
...
...
...
...
...
...
>>>
...
>>>
...
[1,

def fib2(n):
,
, n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
#
f100 = fib2(100)
#
f100
1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

, ,
Python:
return .
return (
), None.
result.append(b) - result. , , obj.methodname,
obj ( ) methodname , .
. , . (

42

4.
.) append(), ,
-. . result = result +
[b], .

4.7

Python .
, .

4.7.1


. , ,
, , :
def ask_ok(prompt, retries=4,
complaint= , !):
while 1:
ok = raw_input(prompt)
if ok in (, ): return 1
if ok in (, , ): return 0
retries = retries - 1
if retries < 0:
raise IOError(
)
print complaint
: ask_ok( ?), : ask_ok( ?, 2).

,
i = 5
def f(arg = i): print arg
i = 6
f()
5.
: .
, ,

4.7.

43

, . ,
( l )3 :
def f(a, l = []):
l.append(a)
return l
print f(1)
print f(2)
print f(3)
:
[1]
[1, 2]
[1, 2, 3]
,
, :
def f(a, l = None):
if l is None:
l = []
l.append(a)
return l

4.7.2

, ,
. 4 .
:
def fprintf(file, format, *args):
file.write(format % args)

4.7.3

(keyword
arguments) keyword = value. , ask_ok() ( 4.7.1)
:
3

, , ,
. .
4
, .

44

4.

ask_ok( ?)
ask_ok(retries = 2, prompt = ?)
ask_ok(?, complaint =
, -!)
ask_ok( ?, 100,
- ?)
:
#
ask_ok()
#
ask_ok(prompt = ?, 2)
#
ask_ok(?, prompt = /)
#
ask_ok(actor = )
, . ,
. :
>>> def function(a):
...
pass
...
>>> function(0, a=0)
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: keyword parameter redefined
**name,
, ,
.
*name, (tuple), , . ( **name *name.) , :
def example(formal, *arguments, **keywords):
print " :", formal
print -*40
for arg in arguments: print arg
print -*40
for kw in keywords.keys():
print kw, :, keywords[kw]

4.7.

45

:
example(1000000,
,
,
language = Python,
author = Guido van Rossum)
:
: 1000000
---------------------------------------

---------------------------------------language: Python
author: Guido van Rossum

4.7.4

Python , . lambda
. , , , lambda a, b: a+b.
, -. . ,
, ,
. ,
:
>>>
...
...
>>>
>>>
42
>>>
43

4.7.5

def make_incrementor(n):
return lambda x, incr=n: x+incr
f = make_incrementor(42)
f(0)
f(1)

( ) ,

46

4.

. (, IDLE) . , ,
. :
>>> print map.__doc__
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function
to the items of the argument sequence(s). If more than
one sequence is given, the function is called with an
argument list consisting of the corresponding item of
each sequence, substituting None for missing values
when not all sequences have the same length. If the
function is None, return a list of the items of the
sequence (or a list of tuples if more than one
sequence).
Python . , , . (
).
.

4.7.6

(func(arg . . . )), Python . 1.6,


, :
args = ( ,
)
kwds = {language: Python,
author: Guido van Rossum)
example(1000000, *args, **kwds)
apply():
apply(example, (1000000,)+args, kwds)

(. 5.2).

47


, .

5.1

, append()
:
>>> a = [66.6, 333, 333, 1, 1234.5]
>>> a.append(333)
>>> a
[66.6, 333, 333, 1, 1234.5, 333]
.
insert ,
:
>>> a.insert(2, -1)
[66.6, 333, -1, 333, 1, 1234.5, 333]
, , : , () ( index), ( count):
>>> a.index(333)
1
>>> print a.count(333), a.count(66.6), a.count(x)
3 1 0
remove() () ,
:
>>> a.remove(333)
>>> a
[66.6, -1, 333, 1, 1234.5, 333]

48

5.

( sort()) ( reverse()):
>>> a.sort() #
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
>>> a.reverse()
>>> a
[1234.5, 333, 333, 66.6, 1, -1]
11.2.6.
, .

5.1.1

, , ,
(LIFO, last-in, first-out).
, append(),
pop() :
>>>
>>>
>>>
>>>
[3,
>>>
7
>>>
[3,
>>>
6
>>>
5
>>>
[3,

5.1.2

stack = [3, 4, 5]
stack.append(6)
stack.append(7)
stack
4, 5, 6, 7]
stack.pop()
stack
4, 5, 6]
stack.pop()
stack.pop()
stack
4]

, ,
(FIFO, first-in, first-out). ,
append(), pop()
0:

5.2.

49

>>> queue = ["Eric", "John", "Michael"]


>>> queue.append("Terry")
# Terry
>>> queue.append("Graham") # Graham
>>> queue.pop(0)
Eric
>>> queue.pop(0)
John
>>> queue
[Michael, Terry, Graham]

5.2

, : filter(), map(), zip() reduce().


filter(function, sequence) ( , sequence),
sequence, function(item) . , :
>>> def f(x):
...
for y in xrange(2, x):
...
if x%y==0: return 0
...
return 1
...
>>> filter(f, xrange(2, 40))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
map(function, sequence [. . . ]) ,
function . , :
>>> def cube(x): return x*x*x
...
>>> map(cube, xrange(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
function , .
None, - . function None, ,
.
, , map(None, list1, list2)
:

50

5.

>>> seq = xrange(8)


>>> def square(x): return x*x
...
>>> map(None, seq, map(square, seq))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25),
(6, 36), (7, 49)]
:
>>> seq1 = [cat, mouse, bird]
>>> seq2 = [, , ]
>>> for x, y in map(None, seq1, seq2):
...
print x, y
...
cat
mouse
bird
, - , map() , None. . 2.0 zip(). zip(sequence
[. . . ]) , -. .
:
>>> a = (1, 2, 3, 4)
>>> b = (5, 6, 7, 8)
>>> c = (9, 10, 11)
>>> d = (12, 13)
>>> zip(a, b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> zip(a, d)
[(1, 12), (2, 13)]
>>> zip(a, b, c, d)
[(1, 5, 9, 12), (2, 6, 10, 13)]
, zip()
map() None .
, zip() map() :
>>>
>>>
>>>
>>>

a
b
x
y

=
=
=
=

(1, 2, 3)
(4, 5, 6)
zip(a, b)
zip(*x) # apply(zip, x)

5.3.

51

>>> z = zip(*y) # apply(zip, y)


>>> x
[(1, 4), (2, 5), (3, 6)]
>>> y
[(1, 2, 3), (4, 5, 6)]
>>> z
[(1, 4), (2, 5), (3, 6)]
>>> x == z
1
reduce(function, sequence [, initial]) ,
function
sequence, . . , :
>>> def add(x, y): return x+y
...
>>> reduce(add, xrange(1, 11))
55
, , , TypeError.
.
,
,
. .:
>>> def sum(seq):
...
def add(x,y): return x+y
...
return reduce(add, seq, 0)
...
>>> sum(xrange(1, 11))
55
>>> sum([])
0

5.3

2.0, Python, , .

for:

52

5.

>>> freshfruit = [ banana,


...
loganberry ,
...
passion fruit ]
>>> [weapon.strip() for weapon in freshfruit]
[banana, loganberry, passion fruit]
>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [{x: x**2} for x in vec]
[{2: 4}, {4: 16}, {6: 36}]
>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
, ,
if:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
, , :
>>> [x, x**2 for x in vec]
File "<stdin>", line 1
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
>>> [(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
for, . .,
:
>>>
>>>
>>>
[8,
>>>
[6,

5.4

vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
6, -18, 16, 12, -36, 24, 18, -54]
[x+y for x in vec1 for y in vec2]
5, -7, 8, 7, -5, 10, 9, -3]

del

, , ( -

5.5.

53

): del:
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.6, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.6, 1234.5]
del :
>>> del a
a NameError,
.
del.

5.5

, ,
. .
(tuple).
, , :
>>> t = 12345, 54321, hello!
>>> t[0]
12345
>>> t
(12345, 54321, hello!)
>>> # :
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, hello!), (1, 2, 3, 4, 5))
, ,
, .
, , (
).
: (x, y), . . , , :

54

5.

( ,
).
, ,
.
,
( ). ,
. :
>>> empty = ()
>>> #
... singleton = hello,
>>> len(empty)
0
>>> empty
()
>>> len(singleton)
1
>>> singleton
(hello,)
t = 12345, 54321, hello! :
12345, 54321 hello! .
:
>>> x, y, z = t
, , . ,
.
:
>>> a = [spam, eggs, 100, 1234]
>>> a1, a2, a3, a4 = a
, , , . ,
, ,
:
>>> t = 1, [foo, bar]
>>> t
(1, [foo, bar])
>>> t[1] = []
#
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: object doesnt support item assignment

5.6.

55

>>> t[1].append(baz)
#
>>> t
(1, [foo, bar, baz])

5.6

Python (dictionary)
. , , ,
, 1 . , ,
, . ,
( -) , ,
append().
: , .
{} . key: value, , , .
.

. key: value del.
, ,
. ,
KeyError.
keys() ( , ,
sort()). , has_key().
:
>>> tel = {jack: 4098, sape: 4139}
>>> tel[guido] = 4127
>>> tel
{sape: 4139, guido: 4127, jack: 4098}
>>> tel[jack]
4098
>>> del tel[sape]
>>> tel[irv] = 4127
1

, ( ),
hash(). , ,
.

56

5.

>>> tel
{guido: 4127, irv: 4127, jack: 4098}
>>> tel.keys()
[guido, irv, jack]
>>> tel.has_key(guido)
1

5.7

,
.
in not in , . is is not ,
. ,
, .
: , a < b == c ,
a b b c.

and or, not.
, . , not or . , A or
not B and C A or ((not B) or C). , .
and or
, . , A C ,
B , A and B and C C . ,
and or ,
.
:
>>> string1, string2, string3 = \
...
, Trondheim, Hammer Dance
>>> non_null = string1 or string2 or string3
>>> non_null
Trondheim
, , C, . ,
C: = ==.

5.8.

5.8

57

- .
:
, , ,
; , . ., .
, .
, . ,
.
ASCII . :
(1, 2, 3)
<
[1, 2, 3]
<
ABC < C < Pascal <
(1, 2, 3, 4)
<
(1, 2)
<
(1, 2, 3)
==
(1, 2, (aa, ab))
<

(1, 2, 4)
[1, 2, 4]
Python
(1, 2, 4)
(1, 2, -1)
(1.0, 2.0, 3.0)
(1, 2, (abc, a), 4)

, .
, . , 0 0.0, . .

58

, (, ) . ,
- ,
. , , , , .
,
.
Python
. .
( ,
).

6.1

, Python.
() .py.
, __name__. , ,
fibo.py :
\

def fib(n):
,
n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n):
,
, n

6.1.

59

result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
:
>>> import fibo
, fibo , fibo. ,
:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
fibo
,
:
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
, , . ,
.
, . ,
,
. , , ,
,
( , ), modname.itemname.
. import .
.
import :

60

6.

>>> from fibo import fib, fib2


>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
(
, fibo ).
import , , , (_):
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
, , . , string _string (
from my_module import *) :
import string
_string = string
del string
, ,
, :
import anydbm
dbopen = anydbm.open
2.0, ( ) import:
import string as _string
from anydbm import open as dbopen
, as , .
, , , exec
(exec import + module_name) __import__() (.
12).

6.2.

6.2

61

, spam,
spam.py , ,
PYTHONPATH, .
, , sys.path.
, Python
.

6.3

, ,
spam.pyc , spam.py, ,
- spam. ,
, spam.py spam.pyc
( , .pyc- , .py-
).
spam.pyc. spam.py
,
spam.pyc. - (,
), . , .
- - ( ),
.
:
-O
PYTHONOPTIMIZE , - .pyo-. : assert, if __debug__: . . . ,
.py-. , .pyc- .
-OO , ,
() , .
, , -O,
, .pyo-.
,
.
, , - .pyc- .pyo-. , , -

62

6.
, ,
, .
( ) .pyc-
( .pyo-, -O -OO), .py-. , , .
compileall .pyc- ( .pyo-) . ,
, . ,
.pyc-, , .pyo-, ( .py-,
).

6.4

Python , . , , , , ,
, .
, , , amoeba , Amoeba. : sys, . sys.ps1
sys.ps2 ,
:
>>> import sys
>>> sys.ps1
>>>
>>> sys.ps2
...
>>> sys.ps1 = C>
C> print !
!
C>
sys.path ,
.
PYTHONPATH . ,
:
>>> import sys
>>> sys.path.append(/ufs/guido/lib/python)

6.5. dir()

63

6.5 dir()
, ,
dir(). :
>>> import fibo, sys
>>> dir(fibo)
[__name__, fib, fib2]
>>> dir(sys)
[__name__, argv, builtin_module_names,
copyright, exit, maxint, modules, path,
ps1, ps2, setprofile, settrace, stderr,
stdin, stdout, version]
, dir() , :
>>> a = [1, 2, 3, 4, 5]
>>> import fibo, sys
>>> fib = fibo.fib
>>> dir()
[__name__, a, fib, fibo, sys]
, : , , . .
, dir()
__builtin__:
>>> import __builtin__
>>> dir(__builtin__)
[AccessError, AttributeError, ConflictError,
EOFError, IOError, ImportError, IndexError,
KeyError, KeyboardInterrupt, MemoryError,
NameError, None, OverflowError, RuntimeError,
SyntaxError, SystemError, SystemExit,
TypeError, ValueError, ZeroDivisionError,
__name__, abs, apply, chr, cmp, coerce,
compile, dir, divmod, eval, execfile,
filter, float, getattr, hasattr, hash, hex,
id, input, int, len, long, map, max,
min, oct, open, ord, pow, range,
raw_input, reduce, reload, repr, round,
setattr, str, type, xrange]

64

6.6

6.

,
. , A.B A B.
, ,
.
, () .
( , .wav, .aiff,
.au), .
(, , , ), ,
, . (
):
Sound/
__init__.py
Formats/
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
Effects/
__init__.py
echo.py
surround.py
reverse.py
...
Filters/
__init__.py
equalizer.py
vocoder.py
karaoke.py
...

__init__.py , Python , ,
, ( string). , __init__.py , -

6.6.

65

/ __all__,
.
, :
import Sound.Effects.echo
Sound.Effects.echo. :
Sound.Effects.echo.echofilter(input, output,
delay=0.7, atten=4)
:
from Sound.Effects import echo
Sound.Effects.echo, :
echo.echofilter(input, output, delay=0.7, atten=4)
:
from Sound.Effects.echo import echofilter
Sound.Effects.echo, ,
echofilter() :
echofilter(input, output, delay=0.7, atten=4)
, from package import item, item
, , package,
, . import ,
item , , .
, ImportError.

import
item.subitem.subsubitem, , ,
. ,
, , .

66

6.6.1

6.

()

, from Sound.Effects
import *? , - , , . ,
, Macintosh Windows,
.
,
ECHO.PY: echo, Echo ECHO.
. import : __init__.py __all__, , from package import *.
. __all__, *. ,
Sounds/Effects/__init__.py :
__all__ = ["echo", "surround", "reverse"]
, from Sound.Effects import * Sound.
__all__ , from Sound.Effects import *
Sound.Effects, ,
__init__.py (
). , ,
import, :
import Sound.Effects.echo
import Sound.Effects.surround
from Sound.Effects import *
, echo surround , Sound.Effects
from ... import.
, , , , , .
( ,
, .) ,
()
. ,
, .

6.6.

67

from package import


specific_module, ,
.

6.6.2

. ,
surround echo. ,
, import
, ,
. , surround import
echo from echo import echofilter.
( Sound ), . , Sound.Filters.vocoder echo
Sound.Effects, from Sound.Effects import echo.

68

/
:
, ,
. .

7.1

: print ( write()).
,
, . , : , . ,
1 . % . %
sprintf() C,
, .
, :
? , Python : str().
repr() (
: expr)
str(). , ,
,
print. str() , , repr() .
:
>>> x = 10 * 3.14
1

1.6 Python.
, string.

7.1.

69

31.4 , :
>>> x
31.399999999999999
str() :
>>> y = 200*200
>>> s = x + str(x) + \
...
, y + str(y) + ...
>>> print s
x 31.4, y 40000...
Python L.
1.6, str() :
>>> repr(1000L)
1000L
>>> str(1000L)
1000
:
>>> p = [x, y]
>>> ps = repr(p)
>>> ps
[31.399999999999999, 40000]
>>> x, y, (spam, eggs)
"(31.399999999999999, 40000, (spam, eggs))"
repr() ( ) :
>>> hello = hello, world\n
>>> print hello
hello, world
>>> hellos = hello
>>> print hellos
hello, world\012
:

70

7. /

>>> for x in range(1, 11):


...
print str(x).rjust(2), str(x*x).rjust(3),
...
#
...
print str(x*x*x).rjust(4)
...
1
1
1
2
4
8
3
9
27
4 16
64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> for x in range(1,11):
...
print %2d %3d %4d % (x, x*x, x*x*x)
...
1
1
1
2
4
8
3
9
27
4 16
64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
( ,
print.)
rjust(), , . ljust() center().
. , ,
:
, . ( ,
: s.ljust(n)[0:n].)
zfill(), string,
,
:
>>> import string
>>> string.zfill(12, 5)
00012

7.1.

71

>>> string.zfill(-3.14, 7)
-003.14
>>> string.zfill(3.14159265359, 5)
3.14159265359
% :
>>> import math
>>> print PI %5.3f. % \
...
math.pi
PI 3.142.
, :
>>> table = {Sjoerd: 4127,
...
Jack : 4098,
...
Dcab : 7678}
>>> for name, phone in table.items():
...
print %-10s ==> %10d % (name, phone)
...
Sjoerd
==>
4127
Dcab
==>
7678
Jack
==>
4098
, C. ,
,
(,
str()) , , 2 .
* ,
.
, , :
>>> def f(x):
...
print "%s" % x
...
>>> f(1)
"1"
>>> f([1, 2])
"[1, 2]"
>>> # ,
... f((1,))
"1"
2

: .

72

7. /

>>> #
... f((1, 2))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in f
TypeError: not all arguments converted
,
:
>>> def f(x):
...
print "%s" % (x,)
...
>>> #
... f((1,))
"(1,)"
>>> f((1, 2))
"(1, 2)"
,
. ,
%(name)format, :
>>> table = {Sjoerd: 4127, Jack: 4098,
...
Dcab: 8637678}
>>> print Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; \
... Dcab: %(Dcab)d % table
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
vars(),
.
11.2.1.

7.2

open() - (file)
: open(filename, mode).
>>> f=open(/tmp/workfile, wb)
>>> print f
<open file /tmp/workfile, mode wb at 80a0960>

7.2.

73

, , , , .
r, , w ( ), a .
r+ . mode
: , r.
Windows ( Macintosh) , ,
b. , , JPEG UNICODE,
, , !
, , ( -
).

7.2.1

, - f .
f.read(size) .
size . ,
, , size
. , ().
>>> f.read() #
This is the entire file.\012
>>> f.read()

f.readline() .
(\n), ,
.
: readline() ,
, \n.
>>> f.readline() #
This is the first line of the file.\012
>>> f.readline() #
Second line of the file\012
>>> f.readline() #

f.readlines() , .

74

7. /

>>> f.readlines()
[This is the first line of the file.\012,
Second line of the file\012]
f.write(s) s .
>>> f.write(This is a test\n)
f.tell() ,
. , f.seek(offset,
from_what). offset . from_what:
0 ( ,
), 1 2 .
>>>
>>>
>>>
>>>
5
>>>
>>>
d

f=open(/tmp/workfile, rb+)
f.write(0123456789abcdef)
f.seek(5)
# Go to the 5th byte in the file
f.read(1)
f.seek(-3, 2) # Go to the 3rd byte before the end
f.read(1)

, ,
f.close(). /
ValueError:
>>> f.close()
>>> f.read()
Traceback (innermost last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
- ,
(isatty(), truncate()).
11.7.

7.2.2

pickle

.
, read() ,
, , int(). ,

7.2.

75

, ,
.
, Python
pickle.
( ) (), . (pickling).
( ) .
(unpickling).
x f, ,
:
pickle.dump(x, f)
(f , ):
x = pickle.load(f)
pickle,
.
pickle Python (persistent) . , , (, )
.

76


, , . ( )
: 1 .

8.1

, , :
>>> while 1 print Hello world
File "<stdin>", line 1
while 1 print Hello world
^
SyntaxError: invalid syntax
, , ,
. ,
: , print,
(:).
, , ,
.

8.2

,
. , ,
, ,
Python. , ,
:
>>> 10 * (1/0)
Traceback (innermost last):
1

, , ,
.

8.3.

77

File "<stdin>", line 1


ZeroDivisionError: integer division or modulo
>>> 4 + spam*3
Traceback (innermost last):
File "<stdin>", line 1
NameError: spam
>>> 2 + 2
Traceback (innermost last):
File "<stdin>", line 1
TypeError: illegal argument type for built-in operation
, . . :
ZeroDivisionError, NameError TypeError. , .
.
. ,
, .
13 .

8.3

, .
, ,
( Ctrl-C). KeyboardInterrupt.
>>> while 1:
...
try:
...
x = int(raw_input(
...
", , : "))
...
break
...
except ValueError:
...
print " . ..."
...
try .
try (,
try except).

78

8.
, except try .
try ,
. , () except, except
try .
except,
try , ,
,
.

try except,
. ( ) . , try,
try. except
:
... except (RuntimeError, TypeError, NameError):
...
pass
except . !
,
( ):
import sys
try:
f = open(myfile.txt)
s = f.readline()
i = int(s.strip())
except IOError, exc:
print " /", exc
except ValueError:
print " ."
except:
print " :", sys.exc_info()[0]
raise #
#
except, try else, , try
. :

8.3.

79

for arg in sys.argv[1:]:


try:
f = open(arg, r)
except IOError:
print , arg
else:
print arg, , len(f.readlines()), \

f.close()
else, try, , , .
, .
. . , except
( ) :
>>> try:
...
spam()
... except NameError, x:
...
print , x,
...
spam
,
.
, try, . :
>>> def this_fails():
...
x = 1/0
...
>>> try:
...
this_fails()
... except ZeroDivisionError, exc:
...
print :, exc
...
: integer division or modulo

80

8.4

8.

raise .
:
>>> raise NameError(HiThere)
Traceback (innermost last):
File "<stdin>", line 1
NameError: HiThere
raise .
; , , .

8.5

, ( ) . :
>>> class MyError(Exception): pass
...
>>> try:
...
raise MyError(2*2)
... except MyError, e:
...
print MyError, value , e
...
MyError, value 4
>>> raise MyError(1)
Traceback (innermost last):
File "<stdin>", line 1
__main__.MyError: 1
9.

8.6

try
finally, . :
>>> try:
...
raise KeyboardInterrupt()

8.6.

81

... finally:
...
print !
...
!
Traceback (innermost last):
File "<stdin>", line 2
KeyboardInterrupt
finally ,
try ,
break return.
try except,
finally, .

82

Python .
C++ Modula-3. , ,
,
.
:
,
,
. .
C++, ( )
(public), (virtual). Modula-3, , : -
, , . Smalltalk, ,
: Python .
, ( C++ Modula-3)
. , C++, Modula-3,
.

9.1

, Smalltalk C++. , , - : Python . , , ,


, , . Python ,
.
,
( , aliasing).
,
, (,
, ). (!)
, (, , .

9.2.

83

.). ,
. ,
, .
, ,
,
, Pascal.

9.2

, , , .
,
, .
.
. Python , , , ( )
. :
(, ), ,
.
. , .
, maximize

.
, : , z.real, real z. ,
: modname.funcname,
modname - funcname . , : 1 !
, . modname.attribute = 42
, del: del modname.attribute.
. , , . , , , ,
. , ,
. . - ,
__main__, . ( ,
1

. - __dict__, ,
. __dict__ ,
. __dict__ - ,
.

84

9.

__builtin__.)
( ,
). ,
.
, ,
, .
, . ( ).
,
. , . , , , .

(, ). (, ), , :
.
, : , ,
, .
, , .
,
, ! (, .)
Python :
, (
global), .
.
: del x x ,
. , , ,
. ,
.

9.3

,
.

9.3.

85

9.3.1
:
class _:
1
.
.
.
N
, ( class, def),
, . (, if
.)
, , , .
, . .
,
. , . ,
.
, -. , .
- .
( ) , - (
_) , .

9.3.2 -
- : .
- ,
Python: obj.attrname. , -.
:
class MyClass:

86

9.
i = 12345
def f(x):
return

i f ,
- . , ,
MyClass.i. __doc__
, : .
.
- , .
,
x = MyClass()
x.
.

__init__(), :
class MyClass:
def __init__(self):
self.data = []
__init__(),
.
__init__(), , .
, , ,
__init__(). :
>>> class Complex:
...
def __init__(self, realpart, imagpart):
...
self.r = realpart
...
self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

9.3.3

-? , - .

9.3.

87

.
.
Smalltalk C++. :
, . , x
MyClass, ,
16:
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
. , . Python
. , -
append(), insert(), remove(), sort() . . ,
, (instance
method).
- : , -
2 . , x.f
, x. x.f ,
MyClass.f. , ,
- .

9.3.4
:
x.f()
. . x.f -,
:
xf = x.f
while 1:
print xf()
2

lambda-, , (
, __call__) .

88

9.

, .
? , x.f()
, , .
? , Python , , , .
: , ,
, .
x.f() MyClass.f(x). , , , n ( ) ,
.
, , , . ,
, , . ,
, . , , , , ,
, ( ).
, , , , - ( )
-. ,
, - , -.

9.4

( ) ( ) . ,
, , . :
, ,
( ) .
,
,
.
, , . : ,
,
. ( ,
, , .
9.6.) , , C,

9.4.

89

.
self.
: self . ,
, .
( , , ,
.)
-, , . ,
: -
. :
#
def f1(self, x, y):
return min(x, x+y)
class C:
f = f1
def g(self):
return
h = g
f, g h C ,
, C. , lambda. ,
.
, self, :
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
,
. ,
, ( , , ).
, :
, .

90

9.

(
).
, ,
(
).

9.5

, . _
:
class _(_):
1
.
.
.
N
(_) , (_).
, , :
class _(._):
, . -
: , . , ,
, . : _()
.
. , , , ,
, (
C++, Python ).
,
. : _.(self, _), _
, .
Python . :

9.6.

91

class _(_1,
_2,
_3):
1
.
.
.
N
, , . , .
, _,
_1, () _1
_2 . . ( _1, _2, _3
_1.
. ,
.)

9.6
Python . __ (
) ___,
. ,
,
. (
, 255 .) ,
, ,
.

, , ,
, . ,
,
. , , , .
exec, execfile, eval()
evalfile(), : global - . getattr(),
setattr() delattr(), __dict__.

92

9.

9.7

(record Pascal struct C),


.
:
class Employee:
pass
#
john = Employee()
#
john.name =
john.dept =
john.salary

:
John Doe
computer lab
= 1000

.
()
, . , ,
, read()
readline(), ,
. (. 11.6.3), , ,
.
, , , , . , UserString, UserList UserDict, StringIO.
, , , , , ,
.

9.7.1

Python ( ; )
.
.
raise :
raise _

9.7.

93

except ,
. ,
, (
except ,
, ). (
) B, C, D:
class B:
pass
class C(B):
pass
class D(C):
pass
for c in [B, C, D]:
try:
raise c()
except D:
print "D"
except C:
print "C"
except B:
print "B"
, except ,
B, B, B except, .
- , :
, , ,
str() -.
>>> class MyError:
...
def __init__(self, value):
...
self.value = value
...
def __str__(self):
...
return self.value
...
>>> raise MyError(1)
Traceback (innermost last):
File "<stdin>", line 1
__main__.MyError: 1
, 13. Exception
,
( __init__()) (
__str__().
:

94

9.

>>> class MyError(Exception): pass


...
>>> raise MyError(Oops!)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: Oops!

9.7.2

, -
. , , map() (. 5.2)
(, . .). ,
:
class parallel:
def __init__(self, *args):
self.__args = args
def __getitem__(self, item):
return map(lambda s, i=item: s[i], self.__args)
-
:
>>> seq1 = xrange(10)
>>> seq2 = [1, 2, 3, 5, 7]
>>> for x, y in parallel(seq1, seq2):
...
print x, y
...
0 1
1 2
2 3
3 5
4 7
,
? , for
Python IndexError.
, (
seq1 seq2). for
, .

9.7.

95

2.0 zip(),
.
parallel,
zip() , .

9.7.3

, , .
, , . ,
, . , dictionary .
, .

class set:
def __init__(self, seq = ()):
# _data ,
# .
# (__data) ,
#
# set .
if isinstance(seq, set):
# seq set
# ,
# ""
self._data = seq._data.copy()
else:
# seq
#
self._data = {}
for item in seq:
self._data[item] = None
def items(self):
#
# :
# for item in myset.items():
#
...
return self._data.keys()
def tuple_key(self):
#
#
# .
# .

96

9.
items = self._data.keys()
# , ,
#
# .
items.sort()
return tuple(items)
def add(self, item):
#
#
# .
self._data[item] = None
def remove(self, item):
if self._data.has_key(item):
del self._data[item]
else:
#
raise ValueError("item doesnt exist")
def copy(self):
return set(self)
def __repr__(self):
return set(+self.items()+)
def __len__(self):
# ,
# len().
# .
return len(self._data)
def __contains__(self, item):
# in not in.
return self._data.has_key(item)
def __cmp__(self, other):
# .
return cmp(self._data, other._data)
def __or__(self, other):
# | ().
res = set(self)
res._data.update(other._data)
return res
def __ior__(self, other):
# |=.

9.7.
self._data.update(other._data)
return self
def __and__(self, other):
# & ().
# ,
# .
if len(other._data) < len(self._data):
self, other = other, self
res = set()
for item in self._data.keys():
if other._data.has_key(item):
res._data[item] = None
return res
def __iand__(self, other):
# &=.
for item in self._data.keys():
if not other._data.has_key(item):
del self._data[item]
return self
def __sub__(self, other):
# - (,
# ).
res = set()
for item in self._data.keys():
if not other._data.has_key(item):
res._data[item] = None
return res
def __isub__(self, other):
# -=.
for item in other._data.keys():
if self._data.has_key(item):
del self._data[item]
return self
# ,
#
# ().
__add__ = __or__
__iadd__ = __ior__
def __xor__(self, other):
# ^ (,
# ).

97

98

9.
if len(other._data) < len(self._data):
self, other = other, self
res = set(other)
for item in self._data.keys():
if res._data.has_key(item):
del res._data[item]
else:
res._data[item] = None
return res
def __ixor__(self, other):
# ^=
for item in other._data.keys():
if self._data.has_key(item):
del self._data[item]
else:
self._data[item] = None
return self

9.7.4

__getattr__(),
__setattr__()

__delattr__() . , __getattr__()
__setattr__() :
class VirtualAttributes:
__vdict = None
#
# __vdict:
__vdict_name = locals().keys()[0]

def __init__(self):
# self.__vdict = {},
# ..
# __setattr__
self.__dict__[self.__vdict_name] = {}
def __getattr__(self, name):
return self.__vdict[name]
def __setattr__(self, name, value):
self.__vdict[name] = value

II

101
,
Python. (, ), , .
, .
, .
, .

102

10



Python. B.

10.1
10.1.1

Python .
, . , . ,
, .
,
: ASCII LF UNIX, CR LF DOS Windows,
CR Macintosh.
#, , . .

(\): ,
, ,
. :
if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60:
#
return 1
, ,
. ,

10.1.

103

.
, , , .
(, , )

, :
month_names = [,
,
,
,
,
,

,
,
,
,
,
]

#
#
# -

, , . , ,
, , , .
, (whitespace) , , , . (
) .

10.1.2
.
.
( )
, ,
, .
.
: .
, ( ) ,
.
, , :
def perm(l):
# l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):

104

10.
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r

:
# :
def perm(l):
# :
for i in range(len(l)):
s = l[:i] + l[i+1:]
# :
p = perm(l[:i] + l[i+1:])
for x in p:
r.append(l[i:i+1] + x)
# :
#
return r
.
,
. . vim,
autocmd FileType python set softtabstop=4
shiftwidth=4 expandtab autoindent .vimrc
(_vimrc Windows).
(FF) .
(, ).
, ,
.

10.2

( ), . ,
( ).
, 11.6.3.
11.

10.2.

10.2.1

105

, .

global, , .
, (
) .
global , .
,
. ,
, NameError.
()
, . Python : , , spam Spam .
.
( ) :
and
assert
break
class
continue
def

del
elif
else
except
exec
finally

for
from
global
if
import
in

is
lambda
not
or
pass
print

raise
return
try
while

,
( * ; , ):
__*__
( , ).
__* ( )
, .
, __spam, Ham,
_Ham_spam. , .
, .

106

10.

_*
, from module
import *. _
-, . _
( ).


: (. 11.1), ( 11.2.1) Unicode
( 11.2.2).


,
.

. , (. 11.2.3) , .
, ,
(
).
(. 11.2.6 11.3).
, .
, repr(). repr() ( 12) __repr__() (
11.6.3).

10.2.2

, (primary) ,
:
primary.attr
. primary -

10.2.

107

, . attr
primary , AttributeError.
primary[key]
/, (. 11.2 11.3).
primary[slice_list]
. (slice_list)
[start]:[stop] ( start stop ). (, , Numerical Python)
[start]:[stop][:[step]]
(step ) (...). : x[1:10:2],
x[:10, ...], x[5:, ::2]. slice ellipsis, 11.8.3.
primary(arg_list)
. , , 11.4. arg_list ( ) ,
( , ,
(exprN ):
expr1 [, ...]
.
/ , (
) :
>>> def print_vector(s, (x, y, z)):
>>>
print s+:
>>>
print x =, x
>>>
print y =, y
>>>
print z =, z
...
>>> velocity = 0.0, 1.0, 1.0
>>> print_vector( , velocity)
:
x = 0.0
y = 1.0
z = 1.0
name1 = expr1 [, ...]
. nameN () , exprN .
.
*seq
(seq) . ,
,
( ) seq. ,
1.6.

108

10.
**dict
(dict) . , , dict.
,
1.6.
( None),
(, ).

10.2.3


. .
x ** y
, , ,
( not ). , , -x ** -y ,
-(x ** (-y)).
+x, -x, ~x
x * y, x / y, x%y
x + y, x - y
x << y, x >> y
x & y
x ^ y
x | y

10.2.4

( , ) (, ). , , ,
x < y <= z , , x < y and y <= z, , y
( z , x < y ).
, a < b > c ,
( a c ). != <>
, .

10.2.

109

x < y
1, x y, 0.
x <= y
1, x y, 0.
x > y
1, x y, 0.
x >= y
1, x y, 0.
x == y
1, x y, 0.
x <> y
x != y
0, x y, 1. <> !=
, .
.
. , .
Unicode,
unicode() (, ASCII, 127,
UnicodeError). __cmp__() ( __rcmp__(), .
11.6.3), <, <=, >, >=, ==, !=
(<>), , ( ,
).
: ,
. , ,
1 .

is is not :
( ; .
id() 12).
x is y
1, x y , 0.
1

, obj1 < obj2 obj2 < obj3, obj1 > obj3, ,


, __cmp__().

110

10.

x is not y
0, x y , 1.

in not in ,
( )
11.2.

x in y
1, y , ( ==)
x, 0.
x not in y
1, y x, 0.

10.2.5

if while , .
:
None;
, , 0, 0L, 0.0, 0j;
, , , (), [];
() {};
, __nonzero__()
__len__(), . 11.6.3.
.

10.2.6

. ,
not , .
not a == b not (a == b), a == not b
.

10.2.

111

or and .
or and ,
.
not x
x , 1, 0.
x and y
x , x, y.
x or y
x , y, x.

10.2.7

lambda

lambda param_list: expression


() , expression. ,
def name(param_list): return expression. 10.4.5.
, , lambda,
. , lambda- ( , def)
, . ,
, , :
def make_incrementor(increment):
return lambda x, n=increment: x+n
lambda ,
, . , ,
lambda: 1, 2 (lambda: 1), 2
: , 1, 2.

10.2.8

() () . , ,
, , : ,
(. 11.2.3).
, print, . print ,
(. 10.3.5).

112

10.2.9

10.

,
, . ,
, .
1. : , ((expression . . . ),
[expression . . . ], {key: value . . . }, expression) .
2. : x.attribute, x[key], x[slice_list], x(arg_list).
3. ** (. 10.2.3).
4. +, - ~.
5. *, /, %.
6. + -.
7. <<, >>.
8. &.
9. ^.
10. |.
11. : <, <=, >, >=, ==, !=, <>, is [not], [not] in.
12. not.
13. and.
14. or.
15. lambda.
16. expr1, ... ( ).

10.3
.
.

10.3.

10.3.1

113

- ( ) , (None) (
).
, None, , repr() . None
.

10.3.2

(lvalue = expression) , ( ) ,
, , . (,
, lvalue):
name = expression
.
x.attribute = expression
. attribute x
, expression.
,
__setattr__().
x[key] = expression
. __setitem__().
x[slice_list] = expression
( slice_list 10.2.2). expression .
__setslice__() ( ) __setitem__()
( ).
lvalue, . . . = expression
(lvalue, . . . ) = expression
[lvalue, . . . ] = expression
, ( , ) . . expression ,

114

10.
, . .
ValueError. :
>>>
>>>
>>>
[0]
>>>
...
...
...
...
...
>>>
>>>
>>>
>>>
2 3

x = range(1)
y, = range(1)
print x, y
0
class c:
def __init__(self, val):
self.val = val
def __repr__(self):
return c(+self.val+)
o = c(1)
l = range(3)
l[1], [(x, y), o.val] = [10, (xrange(2, 4), 5)]
print x, y, l, o
[0, 10, 2] c(5)

= ( ) ,
. , a, b = b, a a b. [0, 2]:
x = [0, 1]
i = 0
i, x[i] = 1, 2
print x
2.0,
:
lvalue
lvalue
lvalue
lvalue
lvalue
lvalue
lvalue
lvalue
lvalue
lvalue
lvalue

+= expression
-= expression
*= expression
/= expression
%= expression
**= expression
&= expression
|= expression
^= expression
>>= expression
<<= expression

lvalue , lvalue op=


expression -

10.3.

115

( ) lvalue (lvalue = lvalue op expression).


, , lvalue .
, Python ,
, . ,
, = == if.

10.3.3

del

del lvalue
( lvalue 10.3.2). ( ) (. 10.5) . . ,
__delattr__(). () -
(-) __delitem__(), __delslice__() (
) __delitem__() (
).

10.3.4

pass ,
, , :
# ,
def do_nothing(arg): pass
#
class record: pass

10.3.5 print
print [expr_list]
expr_list , (
softspace ). , str() (.
12).
, . , , -

116

10.

print.
,
stdout sys. sys.stdout ,
RuntimeError.
2.0, print
. print >>
expr_list None (
sys.stdout). :
print >> sys.stderr, !
print ,
: write()
softspace ( , __getattr__() __setattr__()).

10.3.6

break

break ()
for while, , . ( else ,
). for ( ),
, .
try
finally, finally.

10.3.7 continue
continue ()
for while, , . continue try ( )
except else2 .
.
2

, , .

10.3.

10.3.8

117

return

return [expression] ( ) ( )
expression (None, ) .
try
finally, finally.

10.3.9

global

global identifier_list ,
identifier_list ( )
.
, ( ) ,
global .
- global, .
for,
, import. for, class def , import
, .
global
. , global, exec
, exec. , global
, exec,
exec. eval(), execfile()
compile().

10.3.10

import

import:
import module_list
. module_list
( ,
, ..) ,
- (. ).

118

10.

from module import obj_list


module. obj_list
( , ,
-, , ,
) ,
(. ).
from module import *
module, ,
.
import :
1. ( ) , , .
2. -
( ) , .
2.0, , , object
as local_name (module_list) (obj_list). , , import operator -
operator, import operator as op - op.
,
: import xml.sax as s
from xml import sax as s.
, Python, -, sys.modules
module.py ( __init__.py
module, ). , -
module.pyc module.pyo , . -
.py-, (
, SyntaxError sys.modules ), - ( - ). .
sys.modules. initmodule.
, ( ) sys.modules. ,
sys.modules, .

10.3.

119

(, ),
reload().
,
, sys.path. sys.path , PYTHONPATH
.
, ImportError.
global
. , .
from ... import *
.
import,
__import__(). ,
imp.

10.3.11

exec

exec expression [in globals, [locals]] . expression


code, string file ( ). expression
, exec . Python, (
).
globals locals , . ,
. globals,
. ( )
__builtins__, ( ,
__builtin__).

eval(). globals()
locals(), , .
. , exec for i in (1,2):\n\tprint i\n
, exec for i
in (1,2):\n\tprint i SyntaxError.

120

10.3.12

10.

assert expression [, exc_arg]. expression , AssertionError.


exc_arg, , . assert .
assert expression (, __debug__ AssertionError
; __debug__ 1 )
if __debug__:
if not expression: raise AssertionError()
assert expression, exc_arg
if __debug__:
if not expression: raise AssertionError(exc_arg)
exc_arg , , , . ,
expression, ( ) .

10.3.13

raise [expr1 [, expr2 [, expr3]]]


.
raise ,
.
expr1, ,
. ( expr2), , None.
- , expr2 .
, expr1 : expr2 ,
; expr2 None, ; expr2
.

10.4.

121

raise , (
None ).

. , ,
, .
( None)
.
, None, traceback
(. 11.9.3). ,
, .

10.4

-
.
, ,
, ,
.
if, while for . try .
.
.
.
.
. ,
.
, ( ),
, .
. ,
, , if
else:
if test1: if test2: print x
,
. print
if:
if x < y < z: print x; print y; print z

122

10.

, . , ,
, . , C,
else Python
.

10.4.1

if

if
:
if expr1: suite1
[elif expr2: suite2...]
[else: suite0]
if exprN
elif , ,
( if ).
, suite0
else.

10.4.2

while

while ,
:
while expr: suite1
[else: suite2]
while :
1. expr , , 3.
2. suite1. break
( 3 ),
continue ,
1. suite1, 1.
3. suite2 ( else). break continue
.

10.4.

10.4.3

123

for

for :
for lvalue in sequence: suite1
[else: suite2]
sequence
(, ; , IndexError).
sequence ,
0, lvalue ( item
lvalue ,
lvalue = item; . 10.3.2) suite1.
( IndexError), else, suite2.
break suite1 ( else ). continue
suite1 lvalue sequence
else, .
, lvalue,
, lvalue. , lvalue
. , sequence , lvalue ( , , NameError).
. range() xrange() 12.
, , . . IndexError
. , suite1 ,
. ,
, . , ,
, :
for x in a[:]:
if x < 0: a.remove(x)

124

10.

10.4.4

try

try. ( ,
try except finally),
.
:
try: suite1
except [exc_class1 [, lvalue1]]: suite2
[...]
[else: suite0]
suite1, , suite0 ( else).
suite1 , (
) except , except, . except , , except (
SyntaxError) . exc_classN, ,
. exc_classN , exc_classN
exc_classN.
exc_classN , ,
, (
).
except ,
try ( ) . . exc_classN,

( try ).
except, , (
) (
) lvalueN ( , . 10.3.2), ,
(suiteN)
try ( ). , try try
, .
except
sys.exc_info()
, ( ), (

10.4.

125

) (
) traceback (. 11.9.3). sys.exc_type, sys.exc_value sys.exc_traceback .
,
.
else ,
. except else
, try (
), .
:
try: suite1
finally: suite2
try ( suite1). , finally ( suite2).
suite1 , , finally (
try, ).
suite2 return, break continue
, ( ).
finally , suite1 return break.
continue try (,
, ).

10.4.5
def - (function, .
11.4.1):
def func_name(param_list): suite
param_list ( ; , ,
) ( ,

, ):
param1 [, param2 ...]
.

126

10.
(subparam1 [,
subparam2 ...]) (
).

param1 = expr1 [, param2 = expr2...]


paramN, , exprN. ,
. exprN
, , .
*indentifier
.
indentifier ,
, .
**indentifier
.
indentifier ,
, .
( def)
- func_name ()
( func_name , global . 10.3.9). - ,

.
(suite)
. ,
, . .
10.2.2. , :
. ,
*identifier **identifier, , .

lambda (. 10.2.7).
( , lambda) , .
, :
# , ,
# n
def make_incrementer(n):

10.4.

127

def increment(x, n=n):


return x+n
return increment
add1 = make_incrementer(1)
print add1(3) # 4
, .
, (, ): (,
), . , .
None :
def add_ostrich_notice(notices=None):
if notices is None:
notices = []
notices.append(
" - ")
return notices


__call__(), :
#
# ,
# from ... import *
_MAX_KICKS_ALLOWED = 10 #
class _dog_kicker:
def __init__(self):
#
# "" kick_a_dog()
self.num_of_kicks = 0
def __call__(self, num=1):
if self.num_of_kicks >= _MAX_KICKS_ALLOWED:
print " ?"
return
num = min(_MAX_KICKS_ALLOWED-self.num_of_kicks,
num)
self.num_of_kicks = self.num_of_kicks+num
print " ", num, "()"
#
kick_a_dog = _dog_kicker()

128

10.4.6

10.

- (class, . 11.6.1):
class class_name[(base_classes)]: suite
base_classes (. 10.2.8),
-. ,
( ,
) suite (
). suite ( )
( , base_classes) - - class_name
.
,
. , ( ),
(,
__init__()). , (instance.name)
. ,
,
.

10.5
() . .
Python : , .
, , 3 .
:
global, , - ,
; .
global .
3

exec from ... import *,


: ,
.

10.5.

129

( )
:
,
import,
(
),
,
for ( ),
except.
, , , , __builtin__. ( )
__builtins__. , NameError.
. ,
.


( ),

( - ,
, - , -
exec, , )


( ),

,

input()

(
__main__)

130

10.


, , - exec, ,

eval() execfile() (-

,
,
)

globals() locals() , (. 12).

131

11


,
: , , . Python
.
; , , (. 10.2.4 10.2.5)
repr() ( : expression) str().
:
__methods__
. ,
.
__members__
. ,
.
__methods__ __members__
.

11.1

Python : (int), (long int),


(; float) (complex).

. ( ) .
Python : ,
(int < long int < float < complex).
1 .
1

, , [1, 2] [1.0, 2.0] .

132

11.

int(), long(), float() complex().


( ) ,
(. floor() ceil()
math).

11.1.1

long C,
2 147 483 647 2 147 483 647. .
, . (0
9), .
(07).
0x 0X (09, az,
AZ). - + , , . ,
, OverflowError.
L l (
L, - l ).
:
7
3L

2147483647
79228162514264337593543950336L

11.1.2

0177
0377L

0x80000000
0x100000000L

( )
double C ( 10 ,
1037 ).
(
) / .
e E,
(+ -) .
:
3.14

10.

.001

1e100

3.14e-10

, float, C. , ( )

11.1.

133

.

C, , 1. -1. c #INF,
#IND #QNAN.

11.1.3

, double C.
j J . :
3.14j

10.j

10j

.001j

1e100j

3.14e-10j

complex() (.
12).
:
real
.
imag
.
conjugate()
, .
:
real,
abs().

11.1.4

, :
x + y
x y.
x - y
x y.
x * y
x y.

134

11.

x / y
x y. ( ),
. : 1/2 -1/-2
0, -1/2 1/-2 -1.
x % y
x y.
-x
x .
+x
x ( ).
x ** y
x y.
, Python
abs(), divmod() pow() (. 12), , math.

11.1.5

Python .
, , ,
. ~ ,
(+ -).
:
x | y
x y.
x ^ y
x y.
x & y
x y.
x << n
x, n , 2**n
. (
ValueError).
x >> n
x, n , () 2**n
.
( ValueError).
~x
x .

11.2.

11.2

135

Python : string, unicode,


tuple, xrange, buffer list.
, . in not in , ,
+ () and * , 2 .
s t 3 , n, i j .
len(s)
s.
x in s
1, x s, 0.
x not in s
0, x s, 1
s + t
s t.
s * n
n * s
n s . n
0 ( ,
s).
s += t
s *= t
s = s + t s = s * n , , s
,
, s
.
s[i]
i- s, 0. i , , len(s) + i.
-0 0. i ,
IndexError.
s[[i]:[j]]
s i j , s k, i <= k < j. i j ,
, len(s) + i len(s) + j. i j : i 0, j sys.maxint. (
) ,
.
2
3

, .
, , .

136

11.

min() max() (. 12).

11.2.1
.
Unicode.


() (") ( )
. , (
). , (\),
, .
,
, .
:

\newline


(newline ).

\\

(\).

().

\"

(").

\a

(BEL).

\b

(backspace, BS).

\f

(formfeed, FF).

\n

(linefeed, LF).

\r

(CR).

\t

(TAB).

\v

(VT).

\ooo
\xhh...

ASCII , ooo.
ASCII , hh....

C, -

11.2.

137

( 8- char
8 ). C,
( ).
.
( ) r R. ,
:
,
( ). , r"\n" ,
n, r"\"" ,
. , :
. , r"\"
.
,
(whitespace), ( ; ), .
, "" . ,
, Unicode (a ub == uab).

:
re.compile("[A-Za-z_]"

#
#
"[A-Za-z0-9_]*" #
#

)
, , + .


% - (string unicode)
. ,
( sprintf() ),
.
,
, .
, % -

138

11.

, 4 .
( %),
, .
: %[. . . ][][.]_5 .
% :

. o,
x X 0, 0x 0X .
f, g G
, .
, g G
. .

. s-
%- .

(
).

(+ -) .

. , ,
().
d, i, o, u, x X ( 1),
e, E f ( 6),
g G ( 6; 0
1), s .
, / , *.
:
>>> import math
>>> R = 1
>>> print " %*.*f" % (
...
5,
#
...
2,
#
...
2*math.pi*R) #
6.28
4

.
(h, l L),
.
5

11.2.

139

- . . ,
.
Python :

d, i

()

.
(abcdef).

.
(ABCDEF).

.
e.

.
E.

. 0,
. , 50.

4
, e-, f. .

4
, E-, f. .

,
repr(). , 1.6.

, str().

%.

int ( *), TypeError. ,


, .
, TypeError ( )
AttributeError ( instance).
% (
). %

140

11.

,
. :
>>> count = 2
>>> language = Python
>>> print %(language)s %(count)03d \
. % vars()
Python 002 .

( , * ).


1.6, ( Unicode)
. ,
string. s , .

center(width)
width, ( ).
. width ,
.
ljust(width)
, ( ). width
, .
rjust(width)
, (
). width
, .

count(sub [, start [, end]])


sub s[start:end]. start end ,
( 11.2).

11.2.

141

endswith(suffix [, start [, end]])


1, s[start:end] suffix, 0.
find(sub [, start [, end]])
s
sub s[start:end]. start end , ( 11.2). ,
-1.
index(sub [, start [, end]])
find(), , .
rfind(sub [, start [, end]])
s
sub s[start:end]. start end , ( 11.2). ,
-1.
rindex(sub [, start [, end]])
rfind(), , .
startswith(prefix [, start [, end]])
1, s[start:end] prefix, 0.

expandtabs([tabsize])
,

. tabsize 8 .
lstrip()
,
(. isspace()).
replace(old, new [, maxcount])
, old
new. maxcount,
maxcount .
rstrip()
, (. isspace()).
strip()
, (. isspace()).

142

11.

translate(table [, delchars])
, , delchars
, c table[ord(c)].
table 256 . :
unicode (. 11.2.2).
encode([encoding [, errors]])
encoding ( ASCII).
errors () .
strict , UnicodeError (,
ValueError). ignore ( ) replace (
, ?). ( encode() 1.6
Unicode.)

join(seq)
- seq,
s . ,
, ValueError.
split([sep [, maxcount]])
, . sep, None, . maxcount
maxcount >= 0, maxcount (
maxcount-1 ).
splitlines([keepends])
split(),
. ,
keepends.

,
.
locale.setlocale() (. locale). Unicode Unicode,
.
capitalize()
, .

11.2.

143

isdigit()
1, , 0.
islower()
1, ,
,
(), 0.
isspace()
1, (whitespace)
, , . ., 0.
istitle()
1, ( ,
, ,
, ), 06 .
isupper()
1, ,
,
(), 0.
lower()
, .
swapcase()
,
.
title()
, ( ,
, ,
, )6 .
upper()
, .

11.2.2

Unicode

Unicode ( )
u U: uabc, ur"""abc""" ( ruabc).
, Unicode
\uhhhh, , \xhh..., , .
6


. ,
.

144

11.

, \xhh... \uhhhh
Unicode, \ooo 256.
translate unicode
string:

translate(table)
, c,
table ord(c),
unichr(table[ord(c)]) , table[ord(c)] == None. table
.
, Unicode
:
isdecimal()
1, , , 0. ASCII
, ,
( isdigit
Unicode , , . .).
isnumeric()
1, , -, 0. ,
, . .

11.2.3

, . ( ) , . :
a, b, c, (), (d,).
tuple() (. 12). ,
.

11.2.4

xrange

xrange xrange() (. 12)


, (
, ).

11.2.

145

xrange , , . xrange
.
, , xrange
:
tolist()
, , -
.

11.2.5

buffer

buffer buffer() (. 12)


, :
string, unicode, buffer, , (, array array). buffer
.
( ) buffer.
str() buffer .

11.2.6

. - (list)
, 7 . :
[a, b, c]. 2.0, [expression iter_list], iter_list ( ) for lvalue
in expression , , if test.
lvalue (. 10.3.2), test .
, ,
(x , s t
3 ):
s[i] = x
, i x.
del s[i]
, i.
7

, , .
, .

146

11.

s[[i]:[j]] = t
i j t (
t).
del s[[i]:[j]]
, (
s[i:j] = []).
,
(x , s , , t 3 ).
, . , ( )
.
append(x)
(
s[len(s):len(s)] = [x]).
extend(t)
t ( s[len(s):len(s)] = x).
count(x)
x (
s, x).
index(x)
i, s[i] == x.
ValueError, , x.
insert(i, x)
x i- (
s[i:i] = [x], i >= 0, ). , , .
pop([i])
i- , .
, .
, . , IndexError.
remove(x)
x (
del s[s.index(x)]). , ValueError.
reverse()
.

11.3.

147

sort([cmpfunc])
.
, ( , cmp()). . , ,
sort() reverse() ,
lambda x, y: cmp(y, x).

11.3

() .
.
(dictionary). , (. 10.2.4), .
( , ), 1 1.0,

.
key: value, , {jack: 4098, sjoerd: 4127}
{4098: jack, 4127: sjoerd}. , ,
, .
(m , k ,
v ):
len(m)
m.
m[k]
, k m.
k, KeyError.
m[k] = v
, k v.
del m[k]
m , k.
k, KeyError.
, (m ,
, n 8 , k , v
):
8

, , .

148

11.

clear()
.
copy()
(. .
, , )
.
has_key(k)
1, k,
0.
items()
(key, value)
keys()
.
update(m)
for k in b.keys(): m[k] = b[k].
values()
, .
get(k [, v])
m[k], k, v (
None).
setdefault(k [, v])
k, m[k],
v, k. v , None.
get(), ,
, ,
.
. , keys() values(), ,
. (value, key), map():
pairs = map(None, m.values(), m.keys()).

11.4

,
(obj(arglist)). , , callable().

11.4. ,

11.4.1

149

- (function) def lambda. ,


: func(arglist).
- :

func_doc
__doc__
None, .
func_name
__name__
.
func_defaults
None,
.
func_code
(code), - .
func_globals
, ,
(, ).
func_doc ( __doc__), func_defaults func_code , 9 .

11.4.2

- (instance method)
, - .
__dict__, .
( )
( ). , - - ,
. ,
.
9

func_globals , , , . ,
, ,
, .

150

11.
- :

im_func
-, . .
im_self
, (None, ).
.
im_class
, . .
__name__
( , im_func.__name__).
__doc__
( , im_func.__doc__).
, ,
(im_func) : im_class ,
TypeError. ,
im_func , im_self. , C f x
C, x.f(1) C.f(x, 1).
, - ( )
. ,
.

11.4.3

Python
builtin_function_or_method.
. , ,
.
builtin_function_or_method :
__doc__
(None, ).
__name__
/.

11.5.

151

__self__
, None .

11.4.4

-, . __init__ (
) , -. __init__
, - . 11.6.1.

11.4.5

__call__() (. 11.6.3), : (x(arglist))


__call__() (x.__call__(arglist)). 11.6.2.

11.5
, - : m.name, m name ,
m ( , ). import (. 10.3.10).
:
__dict__
, . ,
, __dict__ (
m.__dict__[a] = 1, m.a
1, m.__dict__ = {}).
__name__
.
__doc__
.
__file__
, ( ,
, __file__ ).

152

11.

11.6

11.6.1

- (. 10.4.6). ,
__dict__.
, , C.x C.__dict__[x]. ,
. ,
, . function,
- (. 11.4.2). im_class -
, - (
).
, .
- , (.
11.4.4).
- :
__name__
.
__module__
, .
__dict__
. , . __dict__ ,
.
__bases__
.
,
.
__doc__
None, .

11.6.2
- - (. 11.4.4).
- ,

11.6.

153

. ,
(. 11.6.1). , , (. 11.4.2).
, __getattr__().
__getattr__() , AttributeError.

, .
__setattr__() __delattr__(), ,
.
- :
__dict__
. ,
.
__dict__ ,
( Python
, __dict__
).
__class__
-, . ,
.

11.6.3

,
,
.


__init__(self [, args...])
(). args... , -.
__init__(), __init__() ,
, .
__del__(self)
().
__del__(), __del__() , , . ,
( ) ,
. __del__()

154

11.
. , .
:
del x x.__del__(),
x , . ,
__del__(). ,

. , ,
. . , traceback,
sys.exc_info() (. sys). traceback, ,
sys.last_traceback. , , , ,
. None
sys.last_traceback.
, , __del__(), , ,
, sys.stderr . ,
-, (,
), . __del__()
. , , -,
, .
(. gc)
, .
, __del__()
, .


__cmp__(self, other)
( ) , , __cmp__(). : , self < other, ,
self == other, , self > other (.
cmp() 12). __cmp__() ( __rcmp__())
, .
__rcmp__(self, other)
,

11.6.

155

__cmp__(). : , self > other, ,


self == other, , self < other. cmp(y, x) -cmp(x, y), __rcmp__()
:
def __rcmp__(self, other):
return -cmp(self, other)
__hash__(self)
- . , ,
hash(). 32- . , ,
-. (,
, ) - ,
. __cmp__(),
- , __hash__() . __cmp__(), __hash__(),
. -
, __hash__().
__nonzero__(self)
, 0 1.
, __len__() (. 11.6.3);
,
.


, : , . - .
.

__getattr__(self, name)
, ( ,
, , name). ()
AttributeError.
, __setattr__() __delattr__(),
__getattr__() , .
.

156

11.

__setattr__(self, name, value)


, __dict__ . name ,
value .
, (, setattr(self, name, value)) __setattr__() .
: self.__dict__[name] = value.
__delattr__(self, name)
.
, del self.name.


__call__(self [, args...])
, x(arg1, arg2, ...) x.__call__(arg1, arg2, ...).


, ,
string, tuple, list dictionary, , . , ()
k, 0 <= k < N, N . 10 . ,
, , ( slice ellipsis) (
slice ellipsis) (. 11.8.3).
,
keys(), values(), items(), has_key(), get(), clear(), copy(),
update(), , dictionary (.
11.3); ,
list: append(), count(), index(), insert(), pop(), remove(),
reverse() sort() (. 11.2.6). , , __add__(),
__radd__(), __iadd__(), __mul__(), __rmul__() __imul__(),
( ) ( ), 11.6.3.
, 10

dictionary :
- (. hash() 12).

11.6.

157

__getslice__(), __setslice__() __delslice__() (. ),


( ) .

__len__(self)
len().
, . ,
__nonzero__(),
, __len__().
__getitem__(self, key)

(self[key]). ( ) __getitem__().
key , TypeError.
, ,
( ),
IndexError ( ). key, KeyError.
__setitem__(self, key, value)
(self[key] = value). ,
, ,
, , . , ,
( ), IndexError.
__delitem__(self, key)

(del self[key]).
, .
, __getitem__.
2.0, , , ( __getslice__()).
i j sys.maxint . , . __len__() , AttributeError. , ,
. , , . ,
.

158

11.

__getslice__(self, i, j)
(self[i:j]).
__setslice__(self, i, j, sequence)
, (self[i:j] = sequence).
__delslice__(self, i, j)
(del self[i:j]).
, , __getitem__(), __setitem__() __delitem__().
slice, Ellipsis
(. 11.8.3). , ,
2.0, __getslice__(),
__setslice__() __delslice__():
method__getitem__(), __setitem__() __delitem__().
, () (, method__getitem__(), __setitem__() __delitem__() , , ):
class MyClass:
...
def __getitem__(self, item):
...
def __setitem__(self, item, value):
...
def __delitem__(self, item):
...
if sys.hexversion<0x020000F0:
# ,
# 2.0 ()
def __getslice__(self, i, j):
return self[max(0, i):max(0, j):]
def __setslice__(self, i, j, seq):
self[max(0, i):max(0, j):] = seq
def __delslice__(self, i, j):
del self[max(0, i):max(0, j):]
...
max().
__*item__() ,
__*slice__() . __*item__(). max(0, i) , .

11.6.

159

in .
. 1.6 :
__contains__(self, item)
in not in (item in self,
item not in self). 1.6, __contains__
, . in not in 0 1, __contains__ (. 10.2.5).


, . ,
, __len__()
__getattr__() (. 11.6.3).

__repr__(self)
repr() (expr) ( str() print,
__str__() )
.
Python, . ,
,
, < > ( ,
__repr__()).
__str__(self)
str(), print s ,
.
__oct__(self)
__hex__(self)
oct() hex() .
.

160

11.

__complex__(self)
__int__(self)
__long__(self)
__float__(self)
complex(), int(), long(),
float(), ,
s. .



, ,
.

__neg__(self)
__pos__(self)
__invert__(self)
__abs__(self)
-, +, ~
abs().


, x op y,
(__op__() __rop__() , op, , __add__()
__radd__() +):
1. x op (%), .
2. x :
(a) x __coerce__(), x y , x.__coerce__(y);
__coerce__() None, 3.
(b) x, y ,
4.
(c) x __op__, x.__op__(y),
x y,
2a.

11.6.

161

3. y :
(a) y __coerce__(), x y , x.__coerce__(y);
__coerce__() None, 4.
(b) x, y ,
4.
(c) y __rop__, y.__rop__(x),
x y,
3a.
4. (a) x op + *, .
(b) .
,
.

__coerce__(self, other)
11 . , self other, , None,
. ,
(other), None, __coerce__ (,
, ,
).
__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__div__(self, other)
__mod__(self, other)
__divmod__(self, other)
__pow__(self, other [, modulo])
__lshift__(self, other)
__rshift__(self, other)
__and__(self, other)
__xor__(self, other)
__or__(self, other)
( ) +, -, *,
/, %, divmod(), ** pow(),
<<, >>, &, ^ | . ,
x+y, x , __add__,
11

, .

162

11.
x.__add__(y). , , pow() , __pow__()
.

__radd__(self, other)
__rsub__(self, other)
__rmul__(self, other)
__rdiv__(self, other)
__rmod__(self, other)
__rdivmod__(self, other)
__rpow__(self, other)
__rlshift__(self, other)
__rrshift__(self, other)
__rand__(self, other)
__rxor__(self, other)
__ror__(self, other)
( ) ,
( r). ,
x-y, y ,
__rsub__, y.__rsub__(x). ,
pow(), ,
__rpow__() ( ).
__iadd__(self, other)
__isub__(self, other)
__imul__(self, other)
__idiv__(self, other)
__imod__(self, other)
__ipow__(self, other)
__ilshift__(self, other)
__irshift__(self, other)
__iand__(self, other)
__ixor__(self, other)
__ior__(self, other)
(
) +=, -=, *=, /=, %=, **= <<=, >>=, &=, ^= |= . , , . , x op= y
x = x op y.

11.7.

11.7

163

file open() (. 12),


os.popen() os.fdopen() (. os).
, (, makefile() , ).
sys.stdin, sys.stdout sys.stderr (. sys) , ,
.
- , , - (, seek() , tty,
, ), IOError.
file :

close()
. - ValueError. close()
.
flush()
.
isatty()
, tty,
0 (). , ,
, .
fileno()
( ), /.
, (,
os fcntl). ,
, ,
.
read([size])
size (,
, size ). size , . . (, tty)
.
readline([size])
,

164

11.
12 ( ). size, size (
). .

readlines([sizehint])
. sizehint, ( )
sizehint (sizehint ,
). ,
, sizehint.
seek(offset [, whence])
. whence : 0 ( ) , 1
2 .
tell()
.
truncate([size])
(size) .
. .
write(s)
s . , -
,
flush() close().
writelines(slist)
slist . writelines()
. 1.6, slist
, list.
:

closed
: , , .
,
close(). , .
mode
/.
open(), mode.
. , .
12

, ,
.

11.8.

165

name
open(),
. , , , <>.
.
softspace
,
print () ().

softspace, . ,
Python, .

11.8

11.8.1

None ,
, None. None
(,
). None .

11.8.2

(type) .
( )
type(). types
.
, :

__doc__
, , None.
__name__
. :
, .
(,
print)
<type >.

166

11.

11.8.3

ellipsis ,
, Ellipsis. Ellipsis (...)
. Ellipsis .

slice , , (obj[i:j:s]),
(obj[i:j, k:l], obj[..., i:j]). , slice,
slice().
, (
None,
start:stop:step ):

start
.
stop
.
step
.
range(start,
stop, step).

11.9
11.9.1

(code) - , . - , - , , ,
- , . ,

11.9.

167

-, . -, -,
( ) .
- compile(), - func_code. -
exec eval().
, :

co_name
( ?, -
compile()).
co_argcount
( ,
).
co_nlocals
( ).
co_varnames
, .
co_code
, - .
co_consts
, .
co_names
- .
co_filename
, - .
co_firstlineno
.
co_lnotab
, - ( , ).
co_stacksize
( ).
co_flags
, . co_flags ( ): 0x04 ,

168

11.
*args ( ); 0x08 , **kwds ( ).

, co_consts
( None, ).

11.9.2
frame , , . tb_frame
traceback (. 11.9.3). frame
( f_trace, f_exc_type, f_exc_value f_exc_traceback , ):

f_back
( ,
func, ,
func) None,
( , ,
).
f_code
(. 11.9.1),
.
f_locals
, .
f_globals
, .
f_builtins
, .
f_restricted
, , .
f_lineno
.
f_lasti
( -
code).

11.9.

169

f_trace
, ,
None ( ).
f_exc_type
f_exc_value
f_exc_traceback

.

11.9.3

traceback

traceback ,
. , . traceback , sys.exc_info() (. sys).
, ,
traceback, .
traceback
sys.last_traceback.
traceback , :

tb_next
traceback,
, , None,
.
tb_frame
, .
tb_lineno
( ), .
tb_lasti
( ) -, (
- code).
tb_lineno tb_lasti traceback f_lineno f_lasti frame,
try except
finally.

170

12


, , ,
. .
__import__(name [, globals [, locals [fromlist]]])
import.
, __import__() ,
import. , ihooks rexec.
imp, , __import__.
,

import
spam

__import__(spam, globals(), locals(), []), from


spam.ham import eggs __import__(spam.ham,
globals(), locals(), [eggs]). , locals()
[eggs] , __import__()
eggs. ,
__import__() locals, globals
import.
name . fromlist , __import__() -, ( name ), -
name. , fromlist, __import__()
-, name. -, import:
import spam.ham.eggs, spam
, ,
import, from
spam.ham import eggs, - spam.ham
eggs.
getattr(), :
import string
def my_import(name):

171
mod = __import__(name)
components = string.split(name, .)
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
abs(x)
. x*x.conjugate(). abs()
__abs__() (. 11.6.3).
apply(object, args [, keywords])
object , (.
11.4) args ( args
, ).
keywords , .
object args
keywords. 1.6,
, : object(*args,
**keywords).
buffer(object [, offset[, size]])
buffer, object (.
11.2.5). object , (string, unicode, array, buffer). buffer
offset ( , offset ) size (
object, size ).
callable(object)
, object ,
(. 11.4).
chr(i)
, , i. , chr(97) a. i
0 255 , i , ValueError.
ord(). . unichr().
cmp(x, y)
x y : , x < y,
, x == y, , x > y.
coerce(x, y)
x y ,
,
. ,
__coerce__() .

172

12.

compile(string, filename, kind)


string (. 11.9.1). filename , . <>,
(, <string>). kind : exec, string , eval, string ,
single, string
( -
None ).
complex(real [, imag])
real ,
imag*j ( imag ,
) real ( imag
) .
delattr(object, name)
name () object, . , delattr(x, foobar)
del x.foobar.
dir([object])
, , ( , locals().keys()).
, object.
__dict__, __methods__
__members__, . , dir()
, object.
, , , ,
, ,
. .
divmod(a, b)
1 : a b.
,
. (int
long int), (a / b, a % b).
(q, a % b), q ( float)
math.floor(a / b), . ,
q * b + a % b a, a % b (
) , b. ,
0 <= abs(a % b) < abs(b).
eval(expression [, globals [, locals]])
expression
1

, a b __divmod__
__rdivmod__ .

173
Python, globals locals . locals,
globals. ,
, eval().
. :
>>> x = 1
>>> eval(x+1)
2
-
compile() ( kind eval)
. expression .
. exec ( 10.3) execfile(),
globals() locals().
execfile(file [, globals [, locals]])
exec,
. import ,
- , (
) - -.
file , Python ( ),
globals locals . locals, globals.
, ,
execfile().
filter(function, list)
list, function ( , ,
None) . list (string) ,
. list. function None,
list, .
float(x)
( ) . , , , ,
(whitespace). , ,
-, C.
,
__float__.
getattr(object, name [, default])
name object. object

174

12.
name (), default ( )
AttributeError.

globals()
, ( ,
, , ).
hasattr(object, name)
1, object name (),
0. :
, ()
, , .
hash(object)
- object. -, TypeError. - . (
, , 1 1.0) -.
hex(x)
(int
long int) .
Python ( L). ,
, , 32- hex(1) 0xffffffff.
, -1.
OverflowError.
id(object)
object ( int
long int).
. , , . .
input([prompt])
eval(raw_input(prompt)) ( ,
).
int(x [, radix])
( , ) x
(int). x ,
, , ,
(whitespace). , 1.6, radix ( , string.atoi) 2 36 2 0.
2

10 26 .

175
radix , (8, 10 16) ,
. radix, x , TypeError.
C.
3 .
intern(string)
string (
) -
, .
, ( ).
, Python, , , .
, , .
isinstance(object, class)
1, object ( ) class class, 0. ,
issubclass(object.__class__, class), , type(object) is class. class -
-, TypeError.
issubclass(class1, class2)
1, class1 ( )
class2. , . - -,
TypeError.
len(object)
( ) . , ,
__len__().
list(sequence)
, sequence.
. sequence
, ( sequence[:]). , list(abc) [a, b, c], list((1, 2, 3))
[1, 2, 3].
locals()
, .
,
, .
3

176

12.

long(x [, radix])
( , ) x (long int). x ,
( l L), , , (whitespace).
, 1.6,
radix ( , string.atol) 2 36 0. radix
, (8, 10 16)
, . radix, x ,
TypeError. C. . .
int().
map(function, seq ...)
function ( , ,
None) seq
. map() . function
.
, None. function None, , ( )
( ). ,
list.
max(seq)
max(v1, v2 ...)
seq, . , ValueError.
, .
min(seq)
min(v1, v2 ...)
seq, . , ValueError.
, .
oct()
(int long int) . Python (
L). , , , 32- oct(-1)
037777777777. . hex().
open(filename [, mode [, bufsize]])
(.

177
11.7). filename , mode , ,
. : r ( ), w ( , ,
), a (
, ;
; seek() ), r+, w+ a+ ( r+
, w+
). b ,
. ,
. ( ,

). , IOError.
mode , r.
bufsize : 0
, 1 , () . bufsize
, 4 : tty
.
ord(c)
. c (string
unicode), . , ord(a) 97,
ord(u\u2020) 8224. chr() unichr()
Unicode.
pow(x, y [, z])
x y ( x ** y).
, ,
pow(x, y) % z, . ,
. .
, . , pow(2, -1)
ValueError, pow(2, 35000) OverflowError.
range([start,] stop [, step])
start
(; 0) stop ( stop) step ( 1; , start ). (int),
4

, C setvbuf(), ,
bufsize, .

178

12.
step , ValueError. step ,
start + i * step, , stop (i
). step ,
start + i * step, stop.
:
>>>
[0,
>>>
[1,
>>>
[0,
>>>
[0,
>>>
[0,
>>>
[]
>>>
[]

range(10)
1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1, 11)
2, 3, 4, 5, 6, 7, 8, 9, 10]
range(0, 30, 5)
5, 10, 15, 20, 25]
range(0, 10, 3)
3, 6, 9]
range(0, -10, -1)
-1, -2, -3, -4, -5, -6, -7, -8, -9]
range(0)
range(1, 0)

raw_input([prompt])
prompt, ( , , str() print)
( print,
).
(
). ,
EOFError. :
>>> s = raw_input(--> )
--> Monty Pythons Flying Circus
>>> s
"Monty Pythons Flying Circus"
readline, raw_input() ,
( , Windows NT, ).
reduce(function, sequence [, initializer])
function (,
) sequence, . . , reduce(operator.__add__, [1, 2, 3, 4, 5])
((((1+2)+3)+4)+5). initializer,
.
(initializer, ,

179
sequence) 1, ( ) ,
0 ( initializer
), TypeError.
reload(module)
.
module -, . - ( , module).

( ) .
,
, import , (
) - sys.modules. , ,
import ( , -) reload().
, . ,
. -
, . , :
try , ,
.
( sys, __main__ __builtin__), . , ,
, .
, from ...
import ..., from ...
import ....
, ,
,
. .
repr(object)
, object. , object
(object). repr() ,
eval(). .
str().
round(x [, n])
, x n . n .

180

12.
x , 10n . , ( round(0.5) 1.0
round(-0.5) -1.0).

setattr(object, name, value)


name () object
value. name .
, setattr(x, foobar, 123)
x.foobar = 123.
slice([start,] stop [, step])
(. 11.8.3). -
, None .
str(object)
, .
repr(), str() , Python.
print.
tuple(sequence)
, sequence.
. sequence
, (
, ) . ,
tuple(abc) (a, b, c), tuple([1, 2, 3]) (1, 2, 3).
type(object)
object. (. 11.8.2). types
. :
>>> import types
>>> if type(x) == types.StringType:
...
print " x "
unichr(i)
Unicode, , i.
, unichr(97) ua. i
0 65535 , i , ValueError.
ord(). . chr().
unicode(string [, encoding [, errors]])
string encoding ( utf-8)
Unicode .
errors: strict ( ) ,

181
UnicodeError, ignore (),
replace (REPLACEMENT CHARACTER, u\uFFFD).
vars([object])
,
. , ,
( , __dict__),
, . : 5 .
xrange([start,] stop [, step])
range(),
xrange (. 11.2.4) .
, (
range() ), .
xrange() range()
.
zip(seq1 ...)
, i- , i- seq1, ..., seqN . ,
, TypeError.
seq1, ..., seqN. , zip
map None . ,
2.0.

, . .

182

13


Python .
. exceptions.

( ).
except try - C, , C . ,
except ValueError: UnicodeError1 , except
UnicodeError: ValueError. , ( ) ,
, (
, __name__ ).
, .
( ,
), . Exception,
, , args.

, ,
( ), .
.

Exception
. . args
1

SomeError SomeError , SomeError,


, , SomeError ,
.

183
, . str(),
Exception, (
), ( ) ( ). , ( )
, (exc[i]).
StandardError
, ( ,
).
ArithmeticError
, .
FloatingPointError
,
(
Python --with-fpectl
config.h WANT_SIGFPE_HANDLER).
OverflowError
,
, . ,
(long int) MemoryError. - , C ,
. (int),
, , ,
,
.
ZeroDivisionError
,
.
AssertionError
, ,
assert.
AttributeError
, , . ( ,
), TypeError.
EOFError
(input(), raw_input()), ,
, . ,

184

13.
read() readline()
.
EnvironmentError
, ,
Python.
2 3 ,
, , , () , . ( args) errno, strerror
filename ( str()) [Errno errno] strerror [Errno errno]
strerror: filename.
IOError
/, ,
.
OSError
( os.error) os.
WindowsError
, Windows errno.
errno strerror , Windows API GetLastError()
FormatMessage() . 1.6.
ImportError
, import
, from ... import ....
KeyboardInterrupt
, SIGINT, ,
( Ctrl-C), KeyboardInterrupt.
SIGINT, signal.signal(). , input()
raw_input(), read(), readline() readlines()
, tty,
KeyboardInterrupt2 .
LookupError
, , .
sys.setdefaultencoding().

, . , Windows NT input() raw_input()


EOFError.

185
IndexError
, ,
, . ,
, .
,
TypeError.
KeyError
, . .
MemoryError
, ,
, . ,
() , .
,
( malloc() C)
. MemoryError (
)
.
NameError
,
. .
UnboundLocalError
,
( global),
. 1.6.
RuntimeError
,
. .
.
NotImplementedError
- ,
,
.
SyntaxError
.
import exec, eval() input(),
(

186

13.
).
: filename
lineno ,
text , , offset ,
, msg
. SyntaxError(msg, (filename, lineno, offset, text)).
str(), , ( msg).
SystemError

. ,
( ). .
TypeError
, - . , .
ValueError
, - , , (, IndexError).
UnicodeError
Unicode . 1.6.
SystemExit
sys.exit(). , . ,
exit() C. ,
None, 0. ,
. ,
code. SystemExit Exception, StandardError,
SystemExit .
sys.exit() , ( finally try)
. (, os.fork() ),
os._exit().

III

189
Python
. C , Python .
, Python (,
) (,
), , (, WWW).
, , . , .

190

14


14.1

site

( , -S)
, , ,
. sys.prefix + /lib/site-packages sys.prefix + /site-python
(UNIX) sys.prefix ( ). , package.pth . (
), sys.path. ,
#, .
,

/usr/lib/python1.5, site-packages. /usr/lib/python1.5/site-packages


foo, bar spam foo.pth bar.pth. ,
foo.pth :
# foo package configuration
foo
bar
bletch
bar.pth :
# bar package configuration
bar
sys.path /usr/lib/python1.5/site-packages/bar
/usr/lib/python1.5/site-packages/foo.
, bletch spam , bletch spam
.

14.2. user

191

,
sitecustomize,
. ImportError, .

14.2

user


. ,
PYTHONSTARTUP.
. , , import
user.
user .pythonrc.py
execfile()
( user) . ,
.pythonrc.py user .
, .pythonrc.py .
, .pythonrc.py.
, ,
.
, :
.pythonrc.py. , spam , , :
import user
try:
# ,
verbose = user.spam_verbose
except AttributeError:
#
verbose = 0
, ,
. ,
, ,
user.

192

15


, ,
Python .
sys

atexit

types

operator

Python .

traceback

traceback.

imp

, import.

pprint

repr

repr() .

15.1

sys

,
, , . sys .

argv
, Python.
argv[0] ( ,
). , argv[0] -c.
( ) argv[0] -
, - .
byteorder
, :
big (big-endian) little (little-endian). ,
2.0.

15.1. sys

193

builtin_module_names
, .
(modules.keys()
).
copyright
, Python.
dllhandle (Windows)
, DLL Python.
exc_info()
, , ( ).
except ( ) try (. 10.4.4).
,
None. , (type,
value, traceback), type ( ), value
( ) ()
traceback traceback (. 11.9.3), .
: traceback , ,
. , , (. gc).
traceback ,
type, value = sys.exc_info()[:2]
. traceback, , ( finally try)
exc_info() , except.
exc_type
exc_value
exc_traceback

exc_info(). , , .
, . , exc_type None
exc_value exc_traceback .
exec_prefix
, Python ( / ). , UNIX
sys.exec_prefix + /lib/python + sys.version[:3] + /config.

194

15.

executable
() Python,
.
exit([exit_code])
.
SystemExit, ( finally try)
. ( 0, ;
, 0 127), , .
None 0,
( ,
str()) 1.
sys.exit( ) .
exitfunc
, -, ( ) . exitfunc() ,
,
os._exit(). exitfunc (
) atexit, .
getdefaultencoding()
,
Unicode . ,
2.0.
getrefcount(object)
object. ,
, , ,
getrefcount().
getrecursionlimit()
Python. .
setrecursionlimit(). , 2.0.
hexversion
. ,
, . ,
, , , 1.5.2 (
), :

15.1. sys

195

if sys.hexversion >= 0x010502F0:


# .
...
else:
#
# .
...
hexversion , ,
(, hex()).

version_info.
last_type
last_value
last_traceback
. ,
.
,
,
. import pdb; pdb.pm() (.
25.1).
,
exc_info() ( , ).
maxint
, int.
, 231 1. int
-maxint-1.
modules
, -.
, ,
, (. new). ,
modules ,
reload().
path
. , (
, ;
), , PYTHONPATH .
, , ,
(path[0]).

196

15.

platform
, , , sunos5, linux1
win32. , ,
path.
prefix
, Python ( / ). ,
UNIX
sys.prefix + /lib/python + sys.version[:3], (, config.h)
sys.prefix + /include/python + sys.version[:3].
ps1
ps2
, , , . ,
. >>> ... .
, , str().

.
setcheckinterval(interval)
, () , ,
. interval ( 10), - . ,
, . ,
-, .
setdefaultencoding(encoding)
, Unicode . encoding
, LookupError.
site ( sitecustomize),
sys. , 2.0.
setprofile(profilefunc)
, (profiling) (. 25.2).
profilefunc (. settrace()), ,
.

15.1. sys

197

setrecursionlimit(limit)
Python. . .
, . ,
. , 2.0.
settrace(tracefunc)
,
. Python (. 25.1).
stdin
stdout
stderr
, , . stdin ,
input() raw_input(). stdout
print, - input() raw_input().

( ) stderr.
Python stdout stderr
( ), write(). input() raw_input() , stderr
readline(). ,
/ (,
os.popen() os.system()) .
__stdin__
__stdout__
__stderr__
stdin, stderr stdout
.
tracebacklimit
,
, traceback,
() .
1000 .

.
version
, , Python , , version
(#build_number, build_date, build_time) [compiler].

198

15.
,
. version
: Python +sys.version+
on +platform.

version_info
, : (major, minor,
micro, releaselevel, serial). , releaselevel . releaselevel :
alpha, beta, candidate final. version_info, Python 2.0, (2, 0, 0, final, 0).
, 1.6.
winver (Windows)
, Windows ( version).
,
.

15.2

gc

(garbage
collector, GC): , , , 1 ,
, , , . , Python,
, , . gc.disable().
, gc.set_debug(gc.DEBUG_LEAK).
gc :
enable()
.
disable()
.
isenabled()
1, , 0.
1
( ) ,
.
.

15.2. gc

199

collect()
. ,
, garbage.
set_debug(flags)
.
. (. ) .
set_debug(0).
get_debug()
, .
set_threshold(threshold0 [, threshold1 [, threshold2]])
() . threshold0 .
,
. , 0. ,
1, 2. 2 ,
. , ,
, .
threshold0, .
. 0 threshold1
1, 1.
threshold2 1, 2.
get_threshold()

(threshold0, threshold1, threshold2).
:
garbage
, ,
. , __del__()
, . DEBUG_SAVEALL,
(
).
:

200

15.

DEBUG_STATS
. .
DEBUG_COLLECTABLE
, .
DEBUG_UNCOLLECTABLE
,
. garbage.
DEBUG_INSTANCES
DEBUG_COLLECTABLE DEBUG_UNCOLLECTABLE, .
DEBUG_OBJECTS
DEBUG_COLLECTABLE DEBUG_UNCOLLECTABLE, , .
DEBUG_SAVEALL
garbage, , .
DEBUG_LEAK
, , (DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_INSTANCES |
DEBUG_OBJECTS | DEBUG_SAVEALL).

15.3

atexit

, 2.0.
atexit , .
. , , , os._exit().
, sys.exitfunc. , , sys.exitfunc . , Python atexit
. , , sys.exitfunc
.

15.4. types

201

register(func ...)
func ,
. ( )
func.
(
, sys.exit() ), ,
. , , ,
.
,
.

try:
_count = int(open("/tmp/counter").read())
except IOError:
_count = 0
def incrcounter(n):
global _count
_count = _count + n
def savecounter():
open("/tmp/counter", "w").write("%d" % _count)
import atexit
atexit.register(savecounter)
. readline, atexit .

15.4

types

, ( 11). from types import * , ,


. ,
, Type.
- , ,
, . :

202

15.

from types import *


def delete(list, item):
if type(item) is IntType:
del list[item]
else:
list.remove(item)
:
NoneType
, None. None
( ).
TypeType
, type () ,
type(). , ,
.
IntType
, int ( , , 1).
LongType
, long int ( , , 1L).
FloatType
, float ( , , 1.0).
ComplexType
, complex ( , , 1.0j).
StringType
, string (, , Python).
UnicodeType
, unicode ( Unicode, , uPython).
TupleType
, tuple (, , (1, 2, 3)).
XRangeType
, xrange.
xrange().
BufferType
, buffer (, buffer).
ListType
, list (, , [1, 2, 3]).

15.4. types

203

DictType
DictionaryType
, dictionary (, , {: Python, : 2.0}).
FunctionType
LambdaType
, function (, ). , def lambda.
CodeType
, code ( , ,
compile()).
ClassType
, class (). - class.
InstanceType
, instance ( ).
-.
MethodType
UnboundMethodType
, method (,
).
BuiltinFunctionType
BuiltinMethodType

builtin_function_or_method ( , ,
abs()).
ModuleType
, module ().
FileType
, file ( , ,
open()).
SliceType
, slice (). slice().
EllipsisType
, ellipsis.
Ellipsis (),
.

204

15.

TracebackType
, traceback.
.
FrameType
, frame ( ). , .

15.5

operator

operator , C, Python. , , .
, operator.add(x, y) x + y .
__ .
:
add(x, y)
__add__(x, y)
x + y.
sub(x, y)
__sub__(x, y)
x - y.
mul(x, y)
__mul__(x, y)
x * y.
div(x, y)
__div__(x, y)
x / y.
mod(x, y)
__mod__(x, y)
x % y.
neg(x)
__neg__(x)
-x.
pos(x, y)
__pos__(x, y)
+x.

15.5. operator

205

abs(x)
__abs__(x)
x (. abs()).
inv(x)
__inv__(x)
invert(x)
__invert__(x)
~x. invert() __invert__() 2.0.
lshift(x, y)
__lshift__(x, y)
x << y.
and_(x, y)
__and__(x, y)
x & y.
or_(x, y)
__or__(x, y)
x | y.
xor(x, y)
__xor__(x, y)
x ^ y.
not_(x)
__not__(x)
not x.
truth(x)
1, x , 0.
concat(seq1, seq2)
__concat__(seq1, seq2)
seq1 + seq2, seq1 seq2
.
repeat(seq, n)
__repeat__(seq, n)
seq * n, seq
, n .
contains(x, y)
__contains__(x, y)
sequenceIncludes(x, y)
y in x. . __contains__() ,

206

15.
2.0, sequenceIncludes() .

countOf(x, y)
y x.
count() -,
y x.
indexOf(x, y)
x, y. index() -,
y x. x
y, ValueError.
getitem(x, y)
__getitem__(x, y)
x[y].
setitem(x, y, z)
__setitem__(x, y, z)
x[y] = z.
delitem(x, y)
__delitem__(x, y)
del x[y].
getslice(x, y, z)
__getslice__(x, y, z)
x[y:z].
setslice(x, y, z, v)
__setslice__(x, y, z, v)
x[y:z] = v.
delslice(x, y, z)
__delslice__(x, y, z)
del x[y:z].
isCallable(obj)
1, obj , 0.

callable().
isMappingType(obj)
1, obj , () , 0.
, ,
.

15.5. operator

207

isNumberType(obj)
1, obj ,
() ,
0. ,
, .
isSequenceType(obj)
1, obj ,
() , 0. ,
, .
map() reduce(). , seq
reduce(operator.add, seq).
, operator.

a ( not not a)
not a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a ^ b
a | b
a << b
a >> b
seq1 + seq2
seq * i
o in seq
o[k]
o[k] = v
del o[k]
seq[i:j]
seq[i:j] = values
del seq[i:j]

truth(a)
not_(a)
neg(a)
add(a, b)
sub(a, b)
mul(a, b)
div(a, b)
mod(a, b)
invert(a)
and_(a, b)
xor(a, b)
or_(a, b)
lshift(a, b)
rshift(a, b)
concat(seq1, seq2)
repeat(seq, i)
contains(seq, o)
getitem(o, k)
setitem(o, k, v)
delitem(o, k)
getslice(seq, i, j)
setslice(seq, i, j, values)
delslice(seq, i, j)

208

15.

15.6

traceback
traceback

, , traceback (. 11.9.3).

.
traceback :
print_tb(traceback [, limit [, file]])
limit traceback,
, ,
( traceback).
limit None,
sys.tracebacklimit (10000, sys.tracebacklimit ) traceback. file ( write()) ,
file .
print_exception(type, value, traceback [, limit [, file]])
print_tb(),
traceback :
traceback None, Traceback
(most recent call last):.
(type value;
, ).
type is SyntaxError value , , ^,
.
.
print_exc([limit [, file]])
print_exception(*(sys.exc_info()
+ (limit, file))).
print_last([limit [, file]])
print_exception(sys.last_type,
sys.last_value, sys.last_traceback, limit, file).

15.6. traceback traceback

209

print_stack([frame [, limit [, file]]])


frame
( __main__). frame None,
, print_stack() .
limit file ,
print_exception().
extract_tb(traceback [, limit])
, traceback,
( , traceback) (filename, line_number,
function_name, text), filename , line_number , function_name text (whitespace)
None. limit ,
print_exception().
extract_stack([frame [, limit]])
,
. ,
, extract_tb().
frame limit , print_stack().
format_list(list)
(, writelines
) , list extract_tb() extract_stack(). .

,
( ) None.
format_exception_only(type, value)
, (,
writelines ) .
. type
value , . .
SyntaxError , ,
,
. , ,
.
format_exception(type, value, traceback [, limit])
, (,
writelines ) , traceback. , print_exception(). -

210

15.

. (, writelines ) , print_exception().

format_tb(traceback [, limit])
format_list(extract_tb(traceback,
limit)).
format_stack(frame [, limit])
format_list(extract_stack(frame,
limit)).
tb_lineno(traceback)
, traceback.
traceback.tb_lineno.
tb_lineno , tb_lineno() .
, :
import sys, traceback
def run_user_code(envdir):
source = raw_input(">>> ")
try:
exec source in envdir
except:
print " :"
print -*60
traceback.print_exc(file=sys.stdout)
print -*60
envdir = {}
while 1:
run_user_code(envdir)
, code.
: traceback
linecache, ,
- . , - (, )
, . ,
linecache.clearcache().

15.7. imp , . . .

15.7

211

imp , import

, import. :
get_magic()
, , .
.
get_suffixes()
, (suffix, mode,
type) : suffix ,
; mode ,
open() ,
(r rb ); type ,
PY_SOURCE, PY_COMPILED C_EXTENSION (. ).
find_module(name [, path])
name path.
, get_suffixes(),
path. , . path
None, (C_BUILTIN)
(PY_FROZEN) , (PY_RESOURCE) Macintosh , Windows,
, sys.path.
(file, pathname,
description), file , , , , pathname description
get_suffixes(), .
, file None, pathname ,
description ( ). , ImportError.
.
. , P.M , M P, P, find_module() path, P.__path__.
load_module(name, file, filename, description)
. ,
load_module() reload().
name ( ).

212

15.
file filename , , (None , ).
description , . , , find_module().
, -.
( ImportError). , file ( None) ,
. finally
try.

new_module(name)
- name. sys.modules.
, :
PY_SOURCE
Python.
PY_COMPILED
- .
C_EXTENSION
.
PY_RESOURCE
Macintosh.
PKG_DIRECTORY
.
C_BUILTIN
.
PY_FROZEN
( Python, ).

.
knee (
)
rexec.

15.8

pprint

15.8. pprint . . .

213

Python. repr(),
eval(). , .
:
PrettyPrinter([keyword_list])

(keyword_list). stream ( write()).


, sys.stdout. indent,
depth width . indent
( ) ,
1. depth
,
....
, .
width (
80 ).
>>>
>>>
>>>
>>>
>>>
[

import pprint, sys


stuff = sys.path[:]
stuff.insert(0, stuff[:])
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(stuff)
[
,
/usr/local/lib/python1.5,
/usr/local/lib/python1.5/test,
/usr/local/lib/python1.5/sunos5,
/usr/local/lib/python1.5/sharedmodules,
/usr/local/lib/python1.5/tkinter],
,
/usr/local/lib/python1.5,
/usr/local/lib/python1.5/test,
/usr/local/lib/python1.5/sunos5,
/usr/local/lib/python1.5/sharedmodules,
/usr/local/lib/python1.5/tkinter]

>>>
>>> import parser
>>> suite = parser.suite(open(pprint.py).read())
>>> tup = parser.ast2tuple(suite)[1][1][1]
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
(266, (267, (307, (287, (288, (...))))))
, :

214

15.

pformat(object)
.
pprint(object [, stream])
object ( ) stream. stream ,
sys.stdout.
.
>>> stuff = sys.path[:]
>>> stuff.insert(0, stuff)
>>> pprint.pprint(stuff)
[<Recursion on list with id=869440>,
,
/usr/local/lib/python1.5,
/usr/local/lib/python1.5/test,
/usr/local/lib/python1.5/sunos5,
/usr/local/lib/python1.5/sharedmodules,
/usr/local/lib/python1.5/tkinter]
isreadable(object)
1, object
eval(), 0. 0 .
>>> pprint.isreadable(stuff)
0
isrecursive(object)
1, , 0.
saferepr(object)
object
, <Recursion on type with id=id>,
type id .
PrettyPrinter ,
, :
pformat(object)
object.
pprint(object)
object ( ) , .
isreadable(object)
1, object

15.9. repr repr()

215

eval(), 0. 0
, .
isrecursive(object)
1, , 0.

15.9

repr repr()

repr(), . , , Python.
:
Repr()
, , , repr().
.
aRepr
Repr. repr(), . , repr() , , .
repr(object)
repr() aRepr. , repr(), .
Repr ,

, , :
maxlevel
, .
6.
maxdict
maxlist
maxtuple
, , .
.

216

15.

maxlong
.
. 40.
maxstring
. ,
. ,
. 30.
maxother
,
20.
repr(object)
,
repr(), .
repr1(object, level)
repr().
object , , .
repr_typename(object, level)
, . , , repr_. ,
, repr1() repr1()
level, .
, Repr,
. ,
:
import repr
import sys
class MyRepr(repr.Repr):
def repr_file(self, obj, level):
if obj.name in [<stdin>,
<stdout>,
<stderr>]:
return obj.name
else:
return obj
aRepr = MyRepr()
print aRepr.repr(sys.stdin)

# <stdin>

217

16


, , .
string

re

StringIO

cStringIO

StringIO.

codecs

16.1

string

string , , .
(. locale).
digits
(0123456789).
hexdigits
,
(0123456789abcdefABCDEF).

letters
lowercase uppercase, .
lowercase
, ( ).
octdigits
, (01234567).
punctuation
, .

218

16.

printable
, .
digits, letters, punctuation whitespace.
uppercase
, ( ).
whitespace
,
\t\n\v\f\r

(whitespace).

:
maketrans(from, to)
, translate()
, from ,
to. from to
. ,
lowercase uppercase .
zfill(s, width)
s, , ,
width. , ,
.
, ,
. 1.6, ,
,
Unicode .
atof(s)
float(s).
atoi(s [, base])
int(s, base).
atol(s [, base])
long(s, base).
capitalize(word)
word.capitalize().
capwords(s [, sep])
, sep,
(
sep) . ,
,

16.1. string

219

. title() ,
.
expandtabs(s [, tabsize])
s.expandtabs(tabsize).
find(s, sub [, start [, end]])
s.find(sub, start, end).
rfind(s, sub [, start [, end]])
s.rfind(sub, start, end).
index(s, sub [, start [, end]])
s.index(sub, start, end).
rindex(s, sub [, start [, end]])
s.rindex(sub, start, end).
count(s, sub [, start [, end]])
s.count(sub, start, end).
lower(s)
s.lower().
split(s [, sep [, maxsplit]])
splitfields(s [, sep [, maxsplit]])
s.split(sep, maxsplit).
join(words [, sep])
joinfields(words [, sep])
sep.join(words).
lstrip(s)
s.lstrip().
rstrip(s)
s.rstrip().
strip(s)
s.strip().
swapcase(s)
s.swapcase().
translate(s, table [, deletechars])
s.translate(table, deletechars), .
upper(s)
s.upper().

220

16.

ljust(s, width)
s.ljust(width).
rjust(s, width)
s.rjust(width).
center(s, width)
s.center(width).
replace(s, old, new [, maxsplit])
s.replace(old, new, maxsplit).

16.2

re

, ,
Perl. ( Unicode)
, NUL.
(\) ,
Python. , ,
, \\\\,
\\
\\. (.
11.2.1).

16.2.1

(regular expression) , , . , re
,
(, , ).
. a A b B, a + b A + B. , ,
.
,
. , A, a
0, ,
. , list
list.

16.2. re

221

, (atom , , ; expr ):

. ()

,
(\n).
DOTALL, ,
.

^ ( )

.
MULTILINE,
.

.
MULTILINE,
.

atom*

(0
) ,
atom. , ab*
a, ab, abb . .

atom+

(1
) ,
atom. , ab+
ab, abb . ., a.

atom?

(0
1) , atom.
, ab? a
ab.

{m,[n]}

(
m n) , atom. , a{3,5}
aaa, aaaa aaaaa. n ,
.

atom*?

(0
) ,
atom. , <.*> <H1>title</H1>,
<.*?> <H1>.

atom+?

(1
) ,
atom.

atom??

(0
1) , atom.

222

16.

{m,[n]}?

(
m n) ,
atom.

[chars]

. chars ,
( ). ( ,
) . , [ab?] a, b ?, [a-z]
, [azA-Z0-9] .
] ,
: []], r[]\-]. ^ , ,

.

[^chars]

,
[chars].

expr1|expr2

,
expr1 expr2, expr1 expr2
. . , .

(expr)

expr .
, , ,
r\number, .

(?options)


, . options
i, L, m, s, u, t x, IGNORECASE, LOCALE, MULTILINE, DOTALL, UNICODE,
TEMPLATE VERBOSE. , ,
compile().

(?:expr)

(expr) expr , .

16.2. re

223

(?P<name>expr)

(expr) , ,
,
expr, name, .
Python. , , r\number.

(?P=name)

, , name.

(?#comment)

, .

(?=expr)

,
, expr. , (?=) .

(?!expr)

,
, expr. , (?!) , .

(?<=expr)

, , expr. , (?<=abc)def
def abcdef. expr
. ,
abc a|b, a*.
,
2.0.

(?<!expr)

,
, expr.
expr . , abc
a|b, a*. , 2.0.

\number

number.
1. , r(.+) \1
the the 55 55, the end. 99. number 0, number

([chars]),

number.

224

16.

\A

\b

1 . ,
.
([chars]) r\b
Python
(BS).

\B

\d

, [0-9]. LOCALE
UNICODE ,
Unicode .

\D

, ; [^0-9]. LOCALE UNICODE


, Unicode
.

\s

(whitespace), r[\t\n\v\f\r ]. LOCALE UNICODE ,


Unicode .

\S

, (whitespace),
r[^\t\n\v\f\r ]. LOCALE
UNICODE ,
Unicode
.

\w

, , .
LOCALE, [a-zA-Z0-9_].
LOCALE UNICODE ,
Unicode
.

\W

,
r\w, r^\w.

\Z

( LOCALE), C.

16.2. re

\char

16.2.2

225

char, char , , , -
.

re : (match) (search).
Perl, , (.
search() , ).
,
:
>>>
>>>
>>>
0
>>>
1

import re
from operator import truth
truth(re.match(a, ba))
truth(re.search(a, ba))

^ ( MULTILINE)
(\n), ^
:
>>>
>>>
>>>
>>>
0
>>>
1

import re
from operator import truth
re_obj = re.compile(.*^a, re.M)
truth(re_obj.match(\na))
truth(re_obj.search(\na))

16.2.3

compile(pattern [, flags])
pattern .
flags. flags |.

226

16.

prog = re.compile(pat)
result = prog.match(str)

result = re.match(pat, str)
compile() ,
.

IGNORECASE
I
,
. LOCALE
1.5.2 , (
ASCII) .
LOCALE
L
r\w, r\W, r\b r\B (
, ).
MULTILINE
M
, ^ ( ) $ ( ,
) ,
\n .
DOTALL
S
. .
. , \n.
VERBOSE
X
:
(whitespace) - ,
.
#, , #

(r\#), .
TEMPLATE
T
:
. (
); , 1.6.

16.2. re

227

UNICODE
U
r\w, r\W, r\b r\B ( Unicode). , 1.6.
pattern
, , .
,
(?flags) .
search(pattern, string [, flags])
string , pattern , .
, None.
match(pattern, string [, flags])
0 string
pattern, , , None.
split(pattern, string [, maxsplit])
string ,
pattern . pattern , .
0 maxsplit, maxsplit . :
>>> re.split(\W+, Words, words, words.)
[Words, words, words, ]
>>> re.split((\W+), Words, words, words.)
[Words, , , words, , , words, ., ]
>>> re.split(\W+, Words, words, words., 1)
[Words, words, words.]
findall(pattern, string)
string, pattern. pattern , , , ,
.
.
sub(pattern, repl, string [, count])
,
string, pattern, repl.
, . repl .
, , . :

228

16.
>>> def dashrepl(matchobj):
....
if matchobj.group(0) == -: return
....
else: return -
>>> re.sub(-{1,2}, dashrepl, pro----gram-files)
pro--gram files
0 count,
. .
,
. , sub(x*, -, abc) -a-b-c-.
repl ,
, . ,
r\n , r\6 ( r\g<6>) ,
, r\g<id> ,
id.

subn(pattern, repl, string [, count])


, sub(), ,
.
escape(string)
,
string,
, .
error
, , (, ),
. .

16.2.4

:
search(string [, pos [, endpos]])
string , , .
, None. pos
endpos , match(), .
match(string [, pos [, endpos]])
0 string , , ,
None.

16.2. re

229

pos ( 0) , .
string[pos:], ^ r\A
. endpos ,
.
split(string [, maxsplit])
split() , , .
findall(string)
findall() , , .
sub(repl, string [, count])
sub() , , .
subn(repl, string [, count])
subn() , , .
flags
flags, compile()
. ,
.
groupindex
, (, ).
pattern
, , .

16.2.5

, search() match()
, ,
:
group([group1 [, group2 ...]])
, .
groupN 1 99 , ( 0). groupN

230

16.
, ?P<name>expr.
(), IndexError.
group() , ( ), ,
( , 0).
- , None .
, .
.
m = re.match(r"(?P<int>\d+)\.(\d*)", 3.14)
m.group(1) m.group(int) 3, m.group(2)
14.

groups([default])
, , . default ,
. default ,
None.
groupdict([default])
, , . default
, . default
, None.
start([group])
end([group])
,
( ) group ( 0, ). , -1. , g, m.group(g),
m.string[m.start(g):m.end(g)].
span([group])
(m.start(group), m.end(group)), m ,
. , , , (-1, -1).
expand(template)
template ,
(, \n) (\1, \g<1>,

16.3. StringIO cStringIO . . .

231

\g<name>) sub() . , 2.0.


pos
pos, () search() match().
endpos
endpos, () search()
match().
lastgroup
( ) None,
. :
>>> import re
>>> re.match((?P<g1>a)(?P<g2>b(?P<g3>c)),
...
abc).lastgroup
g2
lastindex
( ) None,
. :
>>> import re
>>> re.match((?P<g1>a)(?P<g2>b(?P<g3>c)),
...
abc).lastindex
2
re
, .
string
string, () search()
match().

16.3

StringIO cStringIO

StringIO StringIO, , , . cStringIO, C ( ), , ,


- StringIO(). , , StringIO.

232

16.

StringIO , Unicode.
,
write() close() UnicodeError. , cStringIO.StringIO()
: Unicode, write(),
, , UnicodeError.

StringIO([string])
, . string, ,
. .
StringIO(), cStringIO . ,
( ,
ValueError),
.
, .
InputType ( cStringIO)
, cStringIO.StringIO()
.
OutputType ( cStringIO)
, cStringIO.StringIO() .
, StringIO() , , :

getvalue()
.
, close().

16.4

codecs

, 1.6.

.

16.4. codecs

233

register(search_function)
search_function .
search_function , , , , (encoder, decoder, stream_reader, stream_writer).
encoder decoder , encode()
decode() Codec, . stream_reader
stream_writer , StreamReader StreamWriter .
search_function ,
None.
lookup(encoding)
encoding
(encoder, decoder, stream_reader, stream_writer),
. ,
LookupError.
,
, :
open(filename [, mode [, encoding [, errors
[, buffering]]]])
filename encoding ( StreamReaderWriter, ), / /.
mode , (
rb). . errors
strict ( ValueError ; ), ignore ( ) replace ( , \uFFFD). buffering
, open().
EncodedFile(file, input [, output, [errors]])
( StreamRecoder, ), file
( ). output,
write() writelines() read(), readline() readlines() input.
Unicode.
output , input. errors
, open().

234

16.

, :
Codec()
/. :
encode(input [, errors])
, input,
.
decode(input [, errors])
,
input, .
StreamWriter(stream [, errors])
,
stream. Codec encode(),
.
StreamReader(stream [, errors])
, stream.
Codec decode(),
.
encode() decode() ,
Codec, :
charmap_encode(input, errors, encoding_map)
input, encoding_map.
, encode().
charmap_decode(input, errors, encoding_map)
input,
encoding_map. ,
decode().
encodings.
open()
EncodedFile():
StreamReaderWriter(stream, Reader, Writer [, errors])
, ( Reader(stream, errors)) (
Writer(stream, errors)) stream.

16.4. codecs

235

StreamRecoder(stream, encode, decode, Reader, Writer


[, errors])

file ( ). output,
write() writelines() read(), readline() readlines()
input.
,
:
BOM
BOM_BE
BOM_LE
BOM32_BE
BOM32_LE
BOM64_BE
BOM64_LE
, (byte order mark, BOM). BOM BOM_BE
BOM_LE . _BE _LE big-endian little-endian.

236

17


, , , .
locale

gettext

17.1

locale

locale ,
.
( C).

Error
setlocale(),
.
setlocale(category [, locale])
locale, category. locale , (locale). locale ,
. 2.0,
locale :
. , ,
Error.
locale None,
category.
setlocale()
. :
import locale
locale.setlocale(locale.LC_ALL,)

17.1. locale

237

1 . , .
localeconv()
, .
:
decimal_point
( LC_NUMERIC)
, .
grouping
( LC_NUMERIC)

,
,

localeconv()[thousands_sep]. CHAR_MAX, .
,
.
thousands_sep
( LC_NUMERIC)
, .
int_curr_symbol
( LC_MONETARY)
( ISO 4217).
currency_symbol
.

( LC_MONETARY)

mon_decimal_point
( LC_MONETARY)
, .
mon_grouping
( LC_MONETARY)
, localeconv()[grouping].
.
mon_thousands_sep
( LC_MONETARY)
,
.
positive_sign
( LC_MONETARY)
negative_sign
( LC_MONETARY)
,
.
int_frac_digits
( LC_MONETARY)
rac_digits
( LC_MONETARY)
.
p_cs_precedes
( LC_MONETARY)
n_cs_precedes
( LC_MONETARY)
0, , 1,
1

Windows ,
cp866 Unicode. ,
Windows cp1251.
Windows, , .

238

17.
,
.
p_sep_by_space
( LC_MONETARY)
n_sep_by_space
( LC_MONETARY)
1, , 0,
.
p_sign_posn
( LC_MONETARY)
n_sign_posn
( LC_MONETARY)
,
( ): 0 , 1
, 2 , 3 , 4 CHAR_MAX
.

CHAR_MAX
, , localeconv(), .
getdefaultlocale([envvars])

( None, )2 .
, , envvars ( [LANGUAGE, LC_ALL,
codeLC_CTYPE, LANG]). , 2.0.
getlocale([category])
category
( None,
). category
LC_*, LC_ALL; LC_CTYPE. ,
2.0.
normalize(locale)
. locale
, .
,
(ISO8859-5 ). , 2.0.
resetlocale([category])
category ( LC_ALL) 3 . ,
2

Windows NT getdefaultlocale() , , ,
setlocale(),
( ) . .
3
Windows NT - getdefaultlocale() setlocale()
(. 2).

17.1. locale

239

2.0.
strcoll(string1, string2)
( LC_COLLATE)
string1 string2 .
, 0 , string1 string2 .
\000.
strxfrm(string)
( LC_COLLATE)
,
cmp() ( )
, strcoll().
\000.
format(format, val [, grouping])
( LC_NUMERIC)
. , %.
,
grouping, .
str(float)
( LC_NUMERIC)

str(), .
atof(string)
( LC_NUMERIC)
, , .
atoi(string)
( LC_NUMERIC)
,
, .
,
setlocale() ( ):
LC_CTYPE

string, .
LC_COLLATE
strcoll()
strxfrm().
LC_TIME
time.strftime().

240

17.

LC_MONETARY
(. localeconv()
).
LC_MESSAGES
(UNIX)
. (.
gettext).
LC_NUMERIC
, . format(),
atoi(), atof() str(), .
LC_ALL
.
setlocale()
. ,
. LC_ALL , ,
. .

17.2

gettext

gettext .
GNU gettext, , Python.

.
: , , ,
locale.setlocale(), LANGUAGE, LC_ALL, LC_MESSAGES LANG ( ,
) .
language.

17.2.1

GNU gettext

GNU gettext, . ,
.
,
.

17.2. gettext

241

bindtextdomain(domain [, localedir])
domain localedir. gettext os.path.join(localedir, language, LC_MESSAGES,
domain +.mo). localedir None, , domain (
os.path.join(sys.prefix, share, locale)).
textdomain([domain])
None domain, , ( ) domain
.
gettext(message)
message , .
. _() (. ).
dgettext(domain, message)
gettext(),
domain.
GNU gettext dcgettext(), .
:
import gettext
gettext.textdomain(myapplication)
_ = gettext.gettext
...
# , :
print _(This is a translatable string.)
...

17.2.2

, GNU
gettext. , Python. gettext -,
.mo- ,
Unicode .
_() .

242

17.

find(domain [, localedir [, languages]])


.mo- domain localedir ,
languages ( : LANGUAGE, LC_ALL, LC_MESSAGES LANG). languages (
)
. find() .mo-, .
, None.
translation(domain [, localedir [, languages [, class_]]])
Catalog(domain [, localedir [, languages [, class_]]])
, . domain,
localedir languages find() .mo. class_ ( GNUTranslations).
, .mo-. .mo , IOError. translation()

.mo-.
Catalog() gettext, GNOME.
install(domain [, localedir [, unicode]])
translation(domain, localedir).install(unicode).
_(), . _()
, , ,
.
, .
NullTranslations([fp])
, -. _info _charset
None , None fp, _parse(fp),
.
NullTranslations :
_parse(fp)
.
, fp, .

17.2. gettext

243

gettext(message)
message .
.
ugettext(message)
message Unicode. Unicode.
info()
_info (
).
charset()
_charset ( ).
install([unicode])
unicode ,
gettext() _(),
ugettext().
,
. . , _()
, :
def gettext(message): return message
import __builtin__
if hasattr(__builtin__, ps1):
#
_ = gettext
elif not hasattr(__builtin__, _):
__builtin__._ = gettext
( )
.
gettext GNUTranslations,
NullTranslations. _parse(),
.mo- GNU gettext ( big-endian, little-endian).
_info. Content-Type,
_charset.
.mo ,
GNUTranslations IOError.

244

17.

GNUTranslations gettext()
ugettext(). _charset unicode()
Unicode.
Solaris .mo-,
.

17.2.3

, Python ,
. , ,
_(). :
filename = mylog.txt
message = _(writing a log message)
fp = open(filename, w)
fp.write(message)
fp.close()
writing a log message ,
mylog.txt w .
Python pygettext,
, , .pot-4 .
, .
GNU gettext .mo-,
GNUTranslations.

xpot, po-utils

http://www.iro.umontreal.ca/contrib/po-utils/HTML.

245

18


, ,
. , Numerical Python (NumPy),
http://numpy.sourceforge.net/.
math

cmath

random

whrandom

bisect

. .

array

18.1

math

math
.
cmath.

acos(x)
x.
asin(x)
x.
atan(x)
x.
atan2(x, y)
atan(x/y). y 0
pi/2.

246

18.

ceil(x)
,
x.
cos(x)
x.
cosh(x)
x.
exp(x)
e**x.
fabs(x)
x.
floor(x)
,
x.
fmod(x, y)

C. , x % y.
frexp(x)
(m, e), m ( ) e ( ). m e
x == m * 2**e. x , (0.0, 0). 0.5 <= abs(m) < 1.
hypot(x, y)
, sqrt(x*x + y*y).
ldexp(m, e)
, frexp(). m * (2**e).
log(x)
x.
log10(x)
x.
modf(x)
x.
, x.
pow(x, y)
x**y.
sin(x)
x.

18.2. cmath . . .

247

sinh(x)
x.
sqrt(x)
x.
tan(x)
x.
tanh(x)
x.
, frexp() modf() ,
C: ,
.
:
pi
.
e
e.

18.2

cmath

cmath ,
.

acos(x)
x.
acosh(x)
x.
asin(x)
x.
asinh(x)
x.
atan(x)
x.

248

18.

atanh(x)
x.
cos(x)
x.
cosh(x)
x.
exp(x)
e**x.
log(x)
x.
log10(x)
x.
sin(x)
x.
sinh(x)
x.
sqrt(x)
x.
tan(x)
x.
tanh(x)
x.
, frexp() modf() ,
C: ,
.
:
pi
().
e
e ().
, , math. .
, math.sqrt(-1) , cmath.sqrt(-1)
1j. , cmath
, (
).

18.3. random . . .

18.3

249

random

,
.
, whrandom.

.
betavariate(alpha, beta)
-. 1,
0 1.
cunifvariate(mean, arc)
. mean , arc
. 0 .
mean - arc/2 mean + arc/2 (
0 ).
expovariate(lambda)
. lambda ,
. 0
+.
gamma(alpha, beta)
-. alpha > -1
beta > 0.
gauss(mu, sigma)
normalvariate(mu, sigma)
(). mu sigma
. gauss() .
lognormvariate(mu, sigma)
. ,
,
mu sigma. mu ,
sigma .
vonmisesvariate(mu, kappa)
. mu , 0 2, kappa ,
. kappa ,
0 2.
paretovariate(alpha)
. alpha .

250

18.

weibullvariate(alpha, beta)
. alpha , beta
.
random random(), uniform(),
randrange(), randint() choice() whrandom
seed():
seed([obj])
- obj.
obj None,
( whrandom.seed()).

18.4

whrandom

whrandom, -1 :
whrandom([x, y, z])
, , seed(), -.
whrandom :
seed([x, y, z])
x, y z. 0 255 (). ,
, .
, .
random()
r , 0.0 <= r < 1.0.
uniform(a, b)
r , a <= r < b.
randrange([start,] stop [, step])
range(start, stop, step).
randint(a, b)
range(a, b +1).
randrange().
1

Wichmann, B. A. and Hill, I. D., Algorithm AS 183: An efficient and portable pseudo-random number
generator, URL 31 (1982) 188190.

18.5. bisect . . .

251

choice(seq)
seq
.
whrandom whrandom
seed(), random(), uniform(), randrange(), randint()
choice() . , whrandom
.
whrandom . ,
, random.

18.5

bisect

,
, .
.
bisect :
bisect(list, item [, lo [, hi]])
(), item, ,
. lo hi
,
.
list.insert().
insort(list, item [, lo [, hi]])
item list, . list.insert(bisect.bisect(list, item, lo, hi), item).
bisect() .
(
, )
. 85 A, 7584 B
. .:
>>> grades = "FEDCBA"
>>> breakpoints = [30, 44, 66, 75, 85]

252

18.

>>> from bisect import bisect


>>> def grade(total):
...
return grades[bisect(breakpoints, total)]
...
>>> grade(66)
C
>>> map(grade, [33, 99, 77, 44, 12, 88])
[E, A, B, D, F, A]

18.6

array

array,
: , .
:
.
, :

c
b
B
h
H
i
I
l
L
f
d

char ()
signed char ( )
unsigned char ( )
signed short ( )
unsigned short ( )
signed int ( )
unsigned int ( )
signed long ( )
unsigned long ( )
float ( )
double ( )

1
1
1
2
2
2
2
4
4
4
8

. itemsize .
, L I,
long int Python, int
unsigned int unsigned long.
array(typecode [, initializer])
-,
typecode, initializer ( ; initializer
fromlist() fromstring()) .

18.6. array

253

ArrayType
, , array().
:
typecode
, .
itemsize
.
append(x)
x .
buffer_info()
, . ,
, .
byteswap()
.
,
1, 2, 4 8 .
, .
count(x)
x.
extend(a)
a .
fromfile(f, n)
read(f, n)
n ( )
, ( file) f.
, n, EOFError,
.
read() .
fromlist(list)
list. for x in list: a.append(x) : , .
fromstring(s)
s, ( ,
fromfile()).
.

254

18.

index(x)
x.
, ValueError.
insert(i, x)
x i.
pop([i])
i . . i
-1, .
remove(x)
x.
reverse()
.
tofile(f)
write()
( ) , f. write()
.
tolist()
.
tostring()
(
, tofile()).

255

19

, , ,
.
UserString

UserList

UserDict

19.1

UserString

,
, .
,
.
UserString([initialdata])
, string ( ) unicode ( Unicode). initialdata ( ).
initialdata (string unicode), (str(initialdata)). initialdata , .
initialdata data .
, (. 11.2.1),
UserString :
data
(string unicode), .

256

19.

, UserString
:
MutableString([initialdata])
, .
:
- , , ,
, . MutableString
, ,
__hash__().
UserString, MutableString
, :
( ) ( ) , (. 11.2.6).

19.2

UserList

,
. ,
.
UserList:
UserList([initialdata])
, list (). , initialdata ( ).
initialdata , .
initialdata data .
, (. 11.2.6), UserList
:
data
, .

19.3. UserDict

19.3

257

UserDict

,
. ,
.
UserDict:
UserDict([initialdata])
, dictionary (). ,
initialdata ( ).
initialdata , .
initialdata data .
, (.
11.3), UserDict :
data
, .

258

20


, ,
Python.
pickle

Python .

cPickle

pickle.

shelve

DBM.

marshal

- ( ) .

struct

C.

20.1

pickle cPickle

pickle , (pickling,
)
Python (unpickling).
.
,
. shelve
DBM.
Python pickle , C cPickle 1000
. cPickle , , Pickler Unpickler
, .
pickle cPickle
marshal, :

20.1. pickle cPickle . . .

259

pickle cPickle , , .
(, ),
marshal. ( ):
, .
marshal , pickle cPickle .
, .
Python , , , XDR (External Data
Representation), . ,
.
ASCII ,
. ,
, . , bin Pickler dump()
dumps().
pickle cPickle .
,
marshal. ,
.
, . , -
persistent_id().
ASCII . - persistent_load().
. ,
. -, ( __dict__)
__getstate__() , , .
__init__() . , , __getinitargs__()
. (. ??)
__getstate__() __setstate__() .

260

20.

, -
, , , .
, , , .

, .
, ,
,
__setstate__().
pickle cPickle :
Pickler(file [, bin])
( pickle) ( cPickle), ,
. file , write(). bin (
), .
Unpickler(file)
( pickle) ( cPickle), ,
. file , read() readline().
, Pickler(), ()
:
dump(object)
object.
persistent_id(object)
( , ) . -
None, .
persistent_id() (cPickle) None
(pickle).
, Unpickler(), , :
load()
.
noload() ( cPickle)
, .
persistent_load

20.1. pickle cPickle . . .

261

persistent_load(id_string)
( , )
id_string, persistent_id(). persistent_load() .
dump() Pickler.
load() Unpickler().
dump()
Pickler, load() . ,

load(). Pickler,
.
Pickler() Unpickler(),
:
dump(object, file [, bin])
object
Pickler(file, bin).dump(object).

file.

load(file)
file .
dumps(object [, bin])

, .
loads(string)
string
.
format_version
- , .
compatible_formats
() , ,
(format_version), .
, pickle
cPickle ( 2.0
, ):
PickleError
,
Exception.

262

20.
PicklingError
,
, .
UnpicklingError
, ,
(. copy_reg).
, :

None;
, .
Unicode.
, , , .
, (
).
, __dict__ .
,
(. ??).
, copy_reg.
.

20.2

shelve
DBM

(shelf)
, DBM . cPickle pickle,
.
open(filename [, flag])
filename DBM
-. flag
anydbm.open() (. anydbm).
- , (. 11.3): , ,

20.3. marshal -

263

has_key(), keys(), get().


. sync() close() , .
shelve , . .

20.3

marshal -

-
(code), : None; ,
( ); , , , . - ( ) . - Python,
. marshal . pickle, cPickle shelve.
:
dump(object, file)
- object . file file,
(wb w+b). object - , ValueError,
,
load().
load(file)
- , . , EOFError,
ValueError TypeError. file file,
(rb r+b).
dumps(object)
- object.
loads(string)
- string. .

264

20.

20.4

struct C

C .
.
, .

error
, .
, .
pack(format, value1 ...)
, value1 ..., . , format.
unpack(format, string)
string format . , ,
calcsize(format).
calcsize(format)
( ),
format.
:

x
c
b
B
h
H
i
I

C
( )
char
signed char
unsigned char
short
unsigned short
int
unsigned int

l
L
f
d
s
p
P

long
unsigned long
float
double
char[]
char[]
void *

Python
( )
( 1)
int
int
int
int
int
long int (int, C int ,
long)
int
long int
float
float
string
string
int

20.4. struct C

265

, .
, 4h hhhh.
,
.
s ,
. 10s 10 , 10c
10 .
0.
.
p
Pascal. , . p ,
.

. , ,
.

@
=
<
>
!

little-endian
big-endian
(= big-endian)

P .
, ,
, 0. , llh0l
(, long ).
.
struct ( Intel,
little-endian):
>>> from struct import *
>>> pack(hhl, 1, 2, 3)
\001\000\002\000\003\000\000\000
>>> unpack(hhl, \001\000\002\000\003\000\000\000)
(1, 2, 3)
>>> calcsize(hhl)
8

266

21

, , , ( ) .
os

os.path

stat

,
os.stat(), os.lstat() os.fstat().

statvfs

, , os.statvfs().

filecmp

popen2

/ .

time

sched

getpass

getopt

tempfile

errno

glob

UNIX shell.

fnmatch

UNIX shell.

shutil

signal

socket

select

/
.

mmap

21.1. os

21.1

267

os

os (). ,
(posix, nt, mac .)
. , , . ,
os,
.

error
OSError (. 13).
name
. : posix, nt, dos, mac, os2, ce, java.
path

, , posixpath macpath.
os.path.
strerror(code)
(UNIX, Windows)
,
code.

21.1.1

, ,
.

environ
. ,
environ[HOME] HOME. putenv(), environ
. putenv() environ.
putenv() , , .
chdir(path)
getcwd()
21.1.4.

268

21. , . . .

ctermid()
(UNIX)
,
.
getegid()
(UNIX)
.
geteuid()
(UNIX)
.
getgid()
.

(UNIX)

getgroups()
(UNIX)
,
.
getlogin()
(UNIX)
,

.
getpgrp()
.
getpid()
.

(UNIX)

(UNIX, Windows)

getppid()
.

(UNIX)

getuid()
.

(UNIX)

putenv(varname, value)
( UNIX, Windows)
varname
value. .
setegid(egid)
(UNIX)
egid.
seteuid(euid)
(UNIX)
euid.
setgid(gid)
(UNIX)

egid.

21.1. os

269

setpgrp()
(UNIX)
( setpgid(0, 0)).
setpgid(pid, pgrp)
(UNIX)
pid
pgrp. pid 0 .
pgrp 0,
.
setreuid(ruid, euid)
(UNIX)

ruid euid .
setregid(rgid, egid)
(UNIX)
rgid egid .
setsid()
(UNIX)
, .
setuid(uid)
(UNIX)
uid.
umask(mask)
(UNIX, Windows)
,
.
uname()
( UNIX)
: , , ,
, . , socket.gethostname()
socket.gethostbyaddr(socket.gethostname()) (.
socket).

21.1.2

.
fdopen(fd [, mode [, bufsize]])
(UNIX, Windows, Macintosh)
, fd.
mode bufsize ,
open().

270

21. , . . .

popen(command [, mode [, bufsize]])


(UNIX, Windows)
(pipe) command . mode: r (,
) w (). bufsize
, open().
( ,
wait()) close() . ,
( 0),
close() None.
Windows - _popen() Windows. 2.0,
.
tmpfile()
(UNIX)
,
(w+).
.
popen*() bufsize
mode , (t , , b ).
popen2, .
popen2(cmd [, bufsize [, mode]])
(UNIX, Windows)
cmd
, .
, 2.0.
popen3(cmd [, bufsize [, mode]])
(UNIX, Windows)
cmd
, ,
. , 2.0.
popen4(cmd [, bufsize [, mode]])
(UNIX, Windows)
cmd
: . , 2.0.

21.1.3

.
close(fd)
fd.

(UNIX, Windows, Macintosh)

21.1. os
dup(fd)
fd.

271
(UNIX, Windows, Macintosh)

dup2(fd1, fd2)
(UNIX, Windows)
fd1 fd2, ,
.
fpathconf(fd, name)
(UNIX)
, . name
. pathconf_names. name ,
ValueError. (
pathconf_names), OSError errno.EINVAL .
fstat(fd)
(UNIX, Windows)
fd , ,
stat().
fstatvfs(fd)
(UNIX)
, , fd, , ,
statvfs().
ftruncate(fd, length)
(UNIX)
, fd, ,
length .
isatty(fd)
(UNIX)
1, fd tty- , 0.
lseek(fd, offset, whence)
(UNIX, Windows, Macintosh)
, fd. whence : 0 , 1
2 .
open(filename, flags [, mode])
(UNIX, Windows, Macintosh)
filename,
flags
mode ( 0777) (umask). . ,
, |.
openpty()
( UNIX)

(master, slave) pty tty .

272

21. , . . .

pipe()
(UNIX, Windows)
(r, w), .
read(fd, n)
(UNIX, Windows, Macintosh)
n , fd. .
tcgetpgrp(fd)
(UNIX)
, , fd.
tcsetpgrp(fd, pg)
(UNIX)
, ,
fd, pg.
ttyname(fd)
(UNIX)
, fd. fd
tty, .
write(fd, str)
(UNIX, Windows, Macintosh)
str , fd.
.
flags open()
, |:
O_RDONLY
(UNIX, Windows,
O_WRONLY
(UNIX, Windows,
O_RDWR
(UNIX, Windows,
: ,
.

Macintosh)
Macintosh)
Macintosh)

O_APPEND
.

(UNIX, Windows, Macintosh)

O_CREAT
, .

(UNIX, Windows, Macintosh)

O_EXCL
, .

(UNIX, Windows, Macintosh)

O_TRUNC
(UNIX, Windows, Macintosh)
, .
O_NDELAY
O_NONBLOCK
.

(UNIX)
(UNIX)

O_DSYNC
O_RSYNC
O_SYNC
/.

(UNIX)
(UNIX)
(UNIX)

21.1. os

273

O_NOCTTY
(UNIX)
tty, ,
.
O_BINARY
O_TEXT
.

21.1.4

(Windows, Macintosh)
(Windows, Macintosh)

access(path, mode)
(UNIX, Windows)
() path ,
/ . mode F_OK ( |)
R_OK, W_OK X_OK . 1, ,
0.
F_OK
mode access() .
R_OK
mode access() .
W_OK
mode access() .
X_OK
mode access() .
chdir(path)
path.

(UNIX, Windows, Macintosh)

getcwd()
(UNIX, Windows, Macintosh)
, .
chmod(path, mode)
(UNIX, Windows)
() mode ( ).
chown(path, uid, gid)
(UNIX)
()
path uid gid .
link(src, dst)
dst, src.

(UNIX)

274

21. , . . .

listdir(path)
(UNIX, Windows, Macintosh)
path (
path). (curdir
pardir), .
lstat(path)
(UNIX)
stat(), .
mkfifo(path [, mode])
(UNIX)
(FIFO) path mode ( ,
0666) (umask).
.
, , ,
unlink().
.
mkdir(path [, mode])
(UNIX, Windows, Macintosh)
path mode ( , 0777) (umask).
makedirs(path [, mode])
.
mkdir(), .
IOError, path
.
pathconf(path, name)
(UNIX)
, path.
name . pathconf_names. name ,
ValueError. (
pathconf_names), OSError errno.EINVAL .
pathconf_names
(UNIX)
, , pathconf()
fpathconf(), .
readlink(path)
(UNIX)
(), path.
remove(path)
(UNIX, Windows, Macintosh)
unlink(path)
(UNIX, Windows, Macintosh)
path.
rmdir().
removedirs(path)
.

21.1. os

275

rmdir(), (
). IOError, path
.
rename(src, dst)
() src dst.

(UNIX, Windows, Macintosh)

renames(old, new)
.
rename(), ,
new. old new old
removedirs().
rmdir(path)
path.

(UNIX, Windows, Macintosh)

stat(path)
(UNIX, Windows, Macintosh)
() path ,
10 ( )
: st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid,
st_size, st_atime, st_mtime, st_ctime. stat , .
Windows .
statvfs(path)
(UNIX)
, path,
10 : f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree,
f_favail, f_flag, f_namemax. statvfs
, .
symlink(src, dst)
dst, src.

(UNIX)

tempnam([dir [, prefix]])
(UNIX)
, dir. dir None,
. None prefix (), .
, 1.6.
tmpnam()
(UNIX)
, . . ,
1.6.
TMP_MAX
, tmpnam() , . ,
1.6.

276

21. , . . .

utime(path, times)
(UNIX, Windows, Macintosh)

path. 2.0, times
None , . times (atime, mtime), atime mtime
.

21.1.5

, , .
exec*()
. ,
, sys.argv[0], Python. , os.execv(/bin/echo, [foo, bar])
bar , foo
.
abort()
(UNIX, Windows)
SIGABRT . UNIX SIGABRT
(core), Windows , 3.
signal.signal().
execl(path [, arg1 ...])
execv(path, (arg1, ...)).

(UNIX, Windows)

execle(path [, arg1 ...], env)


(UNIX, Windows)
execve(path, (arg1, ...), env).
execlp(path [, arg1 ...])
execvp(path, (arg1, ...)).

(UNIX, Windows)

execv(path, args)
(UNIX, Windows)
path args ( ),
( ).
execve(path, args, env)
(UNIX, Windows)
path args ( ) env (, ),
( ).
execvp(path, args)
(UNIX, Windows)
(environ[PATH]) path execv().

21.1. os

277

execvpe(path, args, env)


(UNIX, Windows)
(env[PATH]) path
execve().
_exit(code)
(UNIX, Windows)
code
- . sys.exit(n). _exit() fork().
fork()
(UNIX)
. 0
.
forkpty()
( UNIX)
, , . (pid,
fd), pid 0 fd .
pty.
kill(pid, sig)
(UNIX)
sig pid.
signal.
nice(increment)
(UNIX)
increment , .
plock(op)
(UNIX)
. ,
2.0.
spawnv(mode, path, args)
(UNIX, Windows)
path args (
). mode , .
UNIX , 1.6.
spawnve(mode, path, args, env)
(UNIX, Windows)
path args (
) env . mode
, . UNIX ,
1.6.
P_WAIT
(UNIX, Windows)
P_NOWAIT
(UNIX, Windows)
P_NOWAITO
(UNIX, Windows)
P_OVERLAY
(Windows)
P_DETACH
(Windows)
mode spawnv() spawnve().

278

21. , . . .

startfile(path)
(Windows)
, ( ) path
, start
Windows ( Explorer). .
. os.path.normpath() .
startfile() , 2.0.
system(command)
(UNIX, Windows)
command (). ,
wait(), Windows 95 98
0.
times()
(UNIX, Windows)
,
, , ,
.
wait()
(UNIX)
(pid, code),
pid code , , (
, ),
( 0).
waitpid(pid, options)
(UNIX)
, pid,
(pid, code) (. wait()).
options, 0
.
pid 0, waitpid()
pid. pid 0,
, . pid -1, .
pid -1,
-pid ( pid).
WNOHANG
(UNIX)
waitpid() , , .
, system(), wait() waitpid():
WIFSTOPPED(code)
, .

(UNIX)

21.1. os
WIFSIGNALED(code)
, .

279
(UNIX)

WIFEXITED(code)
(UNIX)
,
exit().
WEXITSTATUS(code)
(UNIX)
WIFEXITED(code) , ,
exit(), - .
WSTOPSIG(code)
, .

(UNIX)

WTERMSIG(code)
, .

(UNIX)

21.1.6

confstr(name)
(UNIX)
, . name
.
confstr_names. name ,
. name , ValueError.
( confstr_names), OSError errno.EINVAL .
confstr_names
(UNIX)
, , confstr(),
.
sysconf(name)
(UNIX)
. name
.
sysconf_names.
name , -1. name , ValueError. ( sysconf_names), OSError
errno.EINVAL .
sysconf_names
(UNIX)
, , sysconf(),
.
. os.path.

280

21. , . . .

curdir
, , . :.
pardir
, , ..
::.
sep
, , , /,
\ :.
altsep
, ,
None, . DOS Windows
/.
pathsep
,
( PATH), , : ;.
defpath
,
PATH.
linesep
, , , \n, \r \r\n.

21.2

os.path

.
abspath(path)

path.

normpath(join(os.getcwd(), path)).
basename(path)
(basename) path.
split(path). ,
basename, /foo/bar/ bar,
basename() .
commonprefix(list)
list ( ), (
). list ,
().

21.2. os.path

281

dirname(path)
path. split(path).
exists(path)
1, path ( ) ,
0.
expanduser(path)
~ ~user,
. ~ HOME,
user
pwd. -
~, path .
expandvars(path)
$name ${name},
name. , , path .
Macintosh path .
getatime(path)
( , . time) () path. IOError,
.
getmtime(path)
( , . time)
() path.
IOError, .
getsize(path)
() path.
IOError, .
isabs(path)
1, path .
isfile(path)
1, path ,
0. ,
islink() isfile() .
isdir(path)
1, path , 0. , islink()
isdir() .
islink(path)
1, path ,
0. 0, .

282

21. , . . .

ismount(path)
1, path ,
path ()
(i-node) .
join(path1 [, path2 ...])
. -
, . path1,
path2 . ., os.sep. , os.sep.
normcase(path)
path . UNIX . , , . Windows
(os.altsep)
(os.sep).
normpath(path)
path.
,
A//B, A/./B A/foo/../B A/B. Windows
(os.altsep)
(os.sep). normpath()
normcase().
samefile(path1, path2)
(UNIX, Macintosh)
1, (), 0. IOError, os.stat()
- .
sameopenfile(file1, file2)
(UNIX, Macintosh)
1, file1 file2
( ),
0.
samestat(stat1, stat2)
(UNIX, Macintosh)
1, stat1 stat2 (,
fstat(), lstat() stat()) .
split(path)
path (head, tail), tail
head . tail os.sep: path , tail
. os.sep head ,
, path . join(head,
tail) , path.

21.3. stat os.stat()

283

splitdrive(path)
path (drive, tail), drive head .
, drive
. drive + tail == path
.
splitext(path)
path (root, ext) ,
root + ext == path ext
.
walk(path, visit, arg)
visit(arg, dirname, names) , path ( path). dirname ,
visit, names
dirname (os.listdir(dirname),
dirname). visit
names , , , , -
.

21.3

stat os.stat()

, (st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid,


st_size, st_atime, st_mtime, st_ctime ...),
os.stat(), os.lstat() os.fstat().
S_ISDIR(st_mode)
, st_mode .
S_ISCHR(st_mode)
, st_mode , /.
S_ISBLK(st_mode)
, st_mode , .
S_ISREG(st_mode)
, st_mode .
S_ISFIFO(st_mode)
, st_mode (FIFO).

284

21. , . . .

S_ISLNK(st_mode)
, st_mode .
S_ISSOCK(st_mode)
, st_mode (socket).
S_IMODE(st_mode)
,
os.chmod() , sticky bit, set-group-id set-user-id.
S_IFMT(st_mode)
, (
S_IS*(), ).
os.path.is*() (. os.path) .
,
,
stat() .
, os.stat(), os.fstat() os.lstat().
ST_MODE
.
ST_INO
(i-node).
ST_DEV
, .
ST_NLINK
() .
ST_UID
-.
ST_GID
-.
ST_SIZE
.
ST_ATIME
.
ST_MTIME
.

21.4. statvfs os.statvfs()

285

ST_CTIME
.
:
import os, sys
from stat import *
def visit(arg, dir, names):
for name in names:
fullname = os.path.join(dir, name)
mode = os.stat(fullname)[ST_MODE]
if S_ISDIR(mode):
print , fullname
elif S_ISREG(mode):
print , fullname
else:
print , fullname
if __name__ == __main__:
os.path.walk(sys.argv[1], visit, None)

21.4

statvfs os.statvfs()

, , os.statvfs(), .

.
F_BSIZE
.
F_FRSIZE
.
F_BLOCKS
.
F_BFREE
.
F_BAVAIL
, .
F_FILES
( ).

286

21. , . . .

F_FFREE
.
F_FAVAIL
, .
F_FLAG
, .
F_NAMEMAX
.

21.5

filecmp

filecmp
.
cmp(f1, f2 [, shallow])
f1 f21 . 1, , 0. ,
, os.stat(). ,
shallow, .

, , os.stat() .
cmpfiles(dir1, dir2, common [, shallow])
, common ( ), dir1 dir21 .
(match, mismatch, errors). match ,
, mismatch errros
, - (,
). shallow ,
cmp().
, , ( ):
dircmp(dir1, dir2 [, ignore])
, dir1
dir2. , ignore ( [RCS,
CVS, tags]), .
1

cmp() cmpfiles() .
, , .

21.5. filecmp

287

dircmp :
report()
(sys.stdout) .
report_partial_closure()
(sys.stdout) .
report_full_closure()
(sys.stdout) .
left_list
dir1, ignore.
right_list
dir2, ignore.
common
, dir1, dir2.
left_only
, dir1.
right_only
, dir2.
common_dirs
, dir1, dir2.
common_files
, dir1, dir2.
common_funny
, ,
os.stat().
same_files
, ( ,
os.stat()).
diff_files
, , .
funny_files
, , - (, ).

288

21. , . . .

subdirs
, common_dirs
dircmp .
, ,
.
, . .

21.6

popen2 /

UNIX Windows ( 2.0).


popen2 , . (
SHELL UNIX COMSPEC Windows). , ,
2.0, os,
, .
. bufsize mode ( 2.0)
, (t , , b ).
popen2(cmd [, bufsize [, mode]])
cmd , .
popen3(cmd [, bufsize [, mode]])
cmd
, ,
.
popen4(cmd [, bufsize [, mode]])
cmd
:
. , 2.0.
, ( UNIX ):

21.7. time

289

Popen3(cmd [, capturestderr [, bufsize]])


(UNIX)
, . capturestderr,
. bufsize
.
Popen4(cmd [, bufsize])
(UNIX)
Popen3,
.
Popen3 Popen4
:
poll()
-1, , .
wait()
.
fromchild
, .
Popen4 .
tochild
, .
childerr
, , capturestderr , None.
Popen4 None.
pid
.

21.7

time

time .
, .
.
, 0 1 .
UNIX 1970 .
, gmtime(0).

290

21. , . . .


.
C, . UNIX 2038 .
Python C , 2000 ,
, . , , , .
,
accept2dyear .
1, , PYTHONY2K
, accept2dyear . ,
, PYTHONY2K .
,
POSIX X/Open: 6999
19691999 068 20002068. 1001899 .
UTC Universal Coordinated Time, , GMT (Greenwich Mean Time, ).
DST Daylight Saving Time, () . . C
.
, , , , .
, time() sleep() , C UNIX:
, time() ( gettimeofday() C, ), sleep() ( select() C,
).
, gmtime(),
localtime() strptime() asctime(),
mktime() strftime(), 9 :


1993,

112

()

131

023

059

21.7. time

291


061; 60 61

06;
0

1366
( )
0, 1 -1;

, C,
112, 011. ,
. -1, ,
.
:
accept2dyear
, . 1, , PYTHONY2K ,
accept2dyear . ,
, PYTHONY2K
. accept2dyear
.
altzone()

UTC. ,
UTC ( ). ,
daylight .
asctime(time_tuple)
time_tuple, ( gmtime(), localtime() strptime()), 24
Sun Jun 20 23:21:05 1993. , C,
.
clock()
.
C. clock() , ,
.
ctime(secs)
secs, , . asctime(localtime(secs)).

292

21. , . . .

daylight
, (DST).
gmtime(secs)
secs, , (UTC).
localtime(secs)
secs, , . 1 ( ), (DST).
mktime(time_tuple)
, localtime(). time_tuple 9 , . time()
. time_tuple , OverflowError.
sleep(secs)
secs . secs . ,
, secs, sleep(),
. , secs
- .
strftime(format, time_tuple)
, time_tuple, format.
( ,
. . .
locale):

%a

%A

%b

%B

%c

( ) .

%d

( ), 01
31.

%H

, 0023.

%I

, 0112.

21.7. time

%j

293

, 001366.

%m

, 0112.

%M

, 0159.

%p

AM ( ) PM ( ).

%S

, 0061. 60 61
.

%U


, 0053. ,
, 0.

%w

, 06 (0
).

%W


, 0053. ,
, 0.

%x

( ) .

%X

( ) .

%y

( ), 0099.

%Y

(
).

%Z

( , ).

%%

%.

.
strptime(string [, format])
( UNIX)
string
format , . format
,
strftime(). format %a %b %d
%H:%M:%S %Y, , ctime().
string format,
ValueError.

294

21. , . . .

time()
(UTC)
. ,
, 1 .
timezone
( )
UTC ( ,
).
tzname
:

( , ).

21.8

sched

sched , :
scheduler(timefunc, delayfunc)
, . , . timefunc
(, ). delayfunc (
, timefunc), . ,
,
timefunc 0.
scheduler :
enterabs(time, priority, action, arguments)
. time
, ,
timefunc. action
arguments (). , ,
( priority).
, , cancel(),
.
enter(delay, priority, action, arguments)
. delay

21.9. getpass

295

, , timefunc, .
,
enterabs().
cancel(task)
. task,
RuntimeError.
empty()
1, , 0.
run()
. (
delayfunc, ) ,
, . . ,
.
, timefunc, delayfunc action
. action,
run().
:
>>> import sched, time
>>> s=sched.scheduler(time.time, time.sleep)
>>> def print_time():
...
print " print_time:", time.time()
...
>>> def print_some_times():
...
print time.time()
...
s.enter(5, 1, print_time, ())
...
s.enter(10, 1, print_time, ())
...
s.run()
...
print time.time()
...
>>> print_some_times()
930343690.257
print_time: 930343695.274
print_time: 930343700.273
930343700.276

21.9

getpass

getpass :

296

21. , . . .

getpass([prompt])
(UNIX, Windows, Macintosh)
.
prompt (
Password: ).
getuser()
(UNIX, Windows)
. LOGNAME, USER, LNAME USERNAME , .
, pwd ,
( ImportError).

21.10

getopt

getopt ,
(sys.argv). getopt() ,
C UNIX, --. , ,
GNU, , getopt().
getopt(args, options [, long_options])
args ( sys.argv[1:]).
options ,
. ,
options (:).
long_options,
, , -. , ,
(=).
:
(option, value) ( ) , ( args).
option
. value , .
, args.
.
GetoptError
error
, , , .

21.10. getopt

297

, , . GetoptError
:
msg
.
opt
, , ,
.
GetoptError 1.6.
error, GetoptError.
, :
>>> import getopt
>>> args = -a -b -cfoo -d bar a1 a2.split()
>>> args
[-a, -b, -cfoo, -d, bar, a1, a2]
>>> optlist, args = getopt.getopt(args, abc:d:)
>>> optlist
[(-a, ), (-b, ), (-c, foo), (-d, bar)]
>>> args
[a1, a2]
:
>>> s = --condition=foo --testing --output-file
... abc.def -x a1 a2
>>> args = s.split()
>>> args
[--condition=foo, --testing, --output-file,
abc.def, -x, a1, a2]
>>> optlist, args = getopt.getopt(args, x, [
...
condition=, output-file=, testing])
>>> optlist
[(--condition, foo), (--testing, ),
(--output-file, abc.def), (-x, )]
>>> args
[a1, a2]
getopt
:
import getopt, sys

298

21. , . . .

USAGE = """\
...
"""
def main():
try:
opts, args = getopt.getopt(sys.argv[1:],
ho:,
[help, output=])
except getopt.GetoptError:
# :
print << sys.stderr, USAGE
sys.exit(2)
output = None
for o, a in opts:
if o in (-h, --help):
print USAGE
sys.exit()
if o in (-o, --output):
output = a
# ...
if __name__ == __main__:
main()

21.11

tempfile

:
mktemp([suffix])
. , .
mktemp() . suffix,
() .
TemporaryFile([mode [, bufsize [, suffix]]])
( ) , .
. UNIX ,
, , ,
. , (
).
mode , .
w+b, ,

21.12. errno . . .

299

. bufsize ,
open(). suffix, () .
gettempprefix()
, ( ).
, , . ,
, from tempfile
import ... .
tempdir
None, ,
. mktemp().
TMPDIR, TEMP TMP. , (/var/tmp, /usr/tmp /tmp
UNIX) .
template
, None, .
mktemp(). @pid. UNIX, ~pid- Windows
NT, Python-Tmp- Macintosh tmp .

21.12

errno

.
, IOError ( errno).
errorcode
, . ,
errorcode[EPERM] EPERM.
, ,
os.strerror().
( POSIX.1, ISO C). ,
(
errno.errorcode.values()):

300

21. , . . .

EPERM
.
ENOENT
.
ESRCH
.
EINTR
.
EIO
/.
ENXIO
.
E2BIG
.
ENOEXEC
exec().
EBADF
.
ECHILD
.
EAGAIN
.
ENOMEM
.
EACCES
.
EFAULT
.
EBUSY
.
EEXIST
.
EXDEV
( , ).
ENODEV
.

21.12. errno . . .

301

ENOTDIR
.
EISDIR
.
EINVAL
.
ENFILE
( ).
EMFILE
.
ENOTTY
/ ( ).
ETXTBSY
(, ,
).
EFBIG
.
ENOSPC
.
ESPIPE
.
EROFS
.
EMLINK
.
EPIPE
(pipe).
EDOM
.
ERANGE
.
EDEADLK
.
ENAMETOOLONG
.

302

21. , . . .

ENOLCK
.
ENOSYS
.
ENOTEMPTY
.
EBADMSG
.
EILSEQ
.
EMSGSIZE
.
ETIMEDOUT
.
EINPROGRESS
.

21.13

glob

glob , ,
, UNIX shell.
, ~, , os.listdir()
fnmatch.fnmatch() (. fnmatch ). ,
os.path.expanduser().

glob(pathname)
(, ) ,
pathname. pathname , ( ) , , (. fnmatch).
2 .
, , 1.gif, 2.txt
card.gif. glob() ( , ):
2

[seq] ![seq] , .

21.14. fnmatch

303

>>> from glob import glob


>>> glob(./[0-9].*)
[./1.gif, ./2.txt]
>>> glob(*.gif)
[1.gif, card.gif]
>>> glob(?.gif)
[1.gif]

21.14

fnmatch

() , UNIX shell. ( ) re.


(
):

*
?

.
() .

[seq]

() ,
seq.

[!seq]

() ,
seq.

, (/, \, :)
.
* ?.

fnmatch(filename, pattern)
1, () pattern, 0. ,
os.path.normcase(). os.path.normcase()
os.altsep os.sep, , Windows, \
/ ( / \\
/, \\).
fnmatchcase(filename, pattern)
1, () pattern,
0. ,
.

304

21. , . . .

glob , , .

21.15

shutil

shutil .
: Macintosh . , , .

copyfile(src, dst)
src dst. dst
, .
copyfileobj(fsrc, fdst [, bufsize])
( ) fsrc (
) fdst. bufsize, ( , ).
copymode(src, dst)
dst ,
src.
copystat(src, dst)
dst , , src.
, .
copy(src, dst)
src dst. dst ,
( ) () , src.
.
copy2(src, dst)
copy(),
dst ,
src ( cp -p UNIX).
copytree(src, dst [, symlinks])
src dst. dst .
copy2(). symlinks,

21.16. signal

305

, , , . ,
, .
(. ), .
rmtree(path [, ignore_errors [, onerror]])
path.
ignore_errors, , , , onerror
( , onerror ).
onerror :
function, path excinfo. function , (os.remove() os.rmdir()), path , function, excinfo , sys.exc_info(). ,
, .

21.16

signal

. :
,
.
SIGCHLD,
.
.
, Python. ,
, C (,
), .
/ .
, SIGFPE
SIGSEGV.
:
SIGPIPE ( ,
) SIGINT KeyboardInterrupt.
.

306

21. , . . .

. : signal()
. alarm(),
getsignal() pause(),
. ,
.
signal :
SIG_DFL
signal() , getsignal() ,
( ) .
SIG_IGN
signal() , .
SIG*
.
, .
NSIG
,
.
alarm(time)
(UNIX)
time , SIGALRM time .
. ,
. time ,
,
. alarm() 0,
.
getsignal(signalnum)
signalnum.
, , : signal.SIG_IGN, signal.SIG_DFL None. None
, .
pause()
(UNIX)
,
.
signal(signalnum, handler)
handler signalnum.
handler , , : SIG_IGN SIG_DFL.
.

21.17. socket

307

handler signalnum
: ( None).

ValueError.
, alarm() , . ,
, .
os.open() . ,
, SIGALRM 5 : ,
.
import signal, os
def handler(signum, frame):
raise IOError("Couldnt open device!")
#
signal.signal(signal.SIGALRM, handler)
# 5
signal.alarm(5)
#
fd = os.open(/dev/ttyS0, os.O_RDWR)
#
signal.alarm(0)

21.17

socket

socket .
UNIX, Windows, Macintosh, BeOS,
OS/2 , , .

AF_UNIX (host, port) AF_INET, host , (, daring.cwi.nl) IP (,
100.50.200.5), port .
IP : INADDR_ANY <broadcast>
INADDR_BROADCAST.
setblocking().
socket :

308

21. , . . .

error
, . , , , ,
(. errno).
AF_UNIX
(UNIX)
AF_INET

socket() , (UNIX Internet).
SOCK_STREAM
SOCK_DGRAM
SOCK_RAW
SOCK_RDM
SOCK_SEQPACKET

socket() (
).
INADDR_*
IP_*
IPPORT_*
IPPROTO_*
MSG_*
SO_*
SOL_*
SOMAXCONN
setsockopt() getsockopt() ,
.
UNIX IP.
getfqdn([name])
name. name , . , ,
, gethostbyaddr(), ,
. , . ,
, . , 2.0.
gethostbyname(hostname)
, IP hostname.
hostname IP , .
gethostbyname_ex(hostname)
(mainhostname, aliaslist, ipaddrlist),
mainhostname , hostname,
aliaslist ( )

21.17. socket

309

ipaddrlist IP
( ).
gethostname()
, ,
Python. IP , gethostbyname(gethostname()). ,
gethostname()
getfqdn(gethostname()).
gethostbyaddr(ip_address)

(hostname,
aliaslist,
ipaddrlist),

hostname , IP ip_address,
aliaslist ( )
ipaddrlist IP
( ).
getprotobyname(protocolname)
, socket() protocolname.
,
(SOCK_RAW),
, .
getservbyname(servicename, protocolname)
servicename
protocolname. tcp udp.
socket(family, type [, proto])
.
family (AF_INET AF_UNIX), type
( SOCK_*) proto . proto
, .
fromfd(fd, family, type [, proto])
fd
. (
, ). ,
socket().
ntohl(x)
32- .
ntohs(x)
16- .

310

21. , . . .

htonl(x)
32- .
htons(x)
16- .
inet_aton(ip_string)
, IP ip_string ( 123.45.67.89) .
,
C.
inet_ntoa(packed_ip)
IP , packed_ip, .
SocketType
, socket().
, socket(), :
accept()
(conn, address), conn , ,
address . , accept(),
( bind()) ( listen()).
bind(address)
address. .
, (. ).
close()
, .
.
connect(address)
address.
, (. ).
connect_ex(address)
connect(), , connect() , . 0

21.17. socket

311

errno .
.
fileno()
( ).
select.select().
getpeername()
, .
, (.
). , ,
IP .
getsockname()
. , (. ). ,
, .
getsockopt(level, optname [, buflen])
optname. optname
SO_*, .
buflen , .
buflen , .
listen(backlog)
. backlog ( , 5).
makefile([mode [, bufsize]])
( file, . 11.7), . , ,
( ) . mode bufsize
, open().
recv(bufsize [, flags])
. , ,
bufsize. flags recv().
recvfrom(bufsize [, flags])
recv(), (string, address),
string address ,
. address , (. ).

312

21. , . . .

send(string [, flags])
. . flags , recv().
.
sendto(string [, flags], address)
address. . flags , recv().
. , (. ).
setblocking(flag)
flag 0, ,
.
. , recv() send()
, error.
recv() send()
, .
setsockopt(varlevel, optname, value)
optname value.
optname SO_*,
. value
.
shutdown(how)
. how 0,
. how 1, . how 2,
, .
, TCP/IP : , ( ), ,
. , socket(), bind(), listen(), accept() ( accept(),
), socket(), connect(). ,
send() recv() , , , accept().
#
import socket
#
HOST =
#
PORT = 50007

21.18. select /

313

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print , addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
#
import socket
#
HOST = daring.cwi.nl
# ,
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(Hello, world)
data = s.recv(1024)
s.close()
print :, data

21.18

select /

select() poll(). , Windows select() .


UNIX , , ,
, .
.
error
.

.
select(iwtd, owtd, ewtd [, timeout])
, fileno(), .
iwtd , owtd ewtd ( ). timeout

314

21. , . . .
, , ,
.
select() ,
iwtd, owtd ewtd , /.
,
.

poll()
( UNIX)
, /.
, poll(), :
register(fd [, eventmask])
( fileno(), ) fd. poll()
/. eventmask (
|) POLLIN, POLLPRI POLLOUT . .
.
unregister(fd)
( fileno(),
) fd. , , KeyError.
poll([timeout])

/ (fd, event), fd
, ,
event (. ),
. timeout , , ,
. ,
.
, eventmask register() ,
poll():
POLLIN
.
POLLPRI
.

21.19. mmap

315

POLLOUT
( ).
POLLERR
.
POLLHUP
.
POLLNVAL
: .

21.19

mmap

mmap UNIX Windows . , ,


, .
. ,
re .
(, mapped_file[i] = char mapped_file[i:j] = string)
, .
:
mmap(fd, size [, *platform_args])
size ,
fd. , ,
fileno().
(platform_args) . Windows (
). UNIX : flags
prot. flags MAP_SHARED (
) MAP_PRIVATE .
prot PROT_* ( PROT_READ | PROT_WRITE), .
, UNIX,
( ):
MAP_SHARED
.

316

21. , . . .

MAP_PRIVATE
. .
, .
PROT_READ
.
PROT_WRITE
.
, , :
close()
. .
find(string [, start])
, , string.
start ,
( 0).
flush([offset, size])
, .
, ,
. offset size,
( ) offset offset +
size, .
move(dest, src, count)
count , src, ,
dest.
read_byte()
,

1.
readline()
, , ( ) .
resize(newsize)
.
newsize .
seek(pos [, whence])
. whence : 0 ( ) , 1
2 .

21.19. mmap

317

size()
, .
tell()
.
write(string)
string , .

.
write_byte(byte)
byte ( 1).

318

22



thread

threading

Queue

22.1

thread

thread , . .

error
, .
LockType
.
start_new_thread(function, args [, kwargs])
function,
args () kwargs ().
exit()
exit_thread()
SystemExit. ( ) , . exit_thread()
.
allocate_lock()
, . .

22.1. thread

319

get_ident()
( ). .
, allocate_lock, :
acquire([waitflag])
() , ,
, ( None). waitflag ( ), : 1
( , ), 0 ( ) ,
. 1,
, 0.
release()
. ,
.
locked()
: 1, (), 0.
:
signal, ( KeyboardInterrupt)
. , signal ,
.
sys.exit() thread.exit()
SystemExit .
, C, /
, (
time.sleep() select.select(), read() ) .
acquire() ,
, KeyboardInterrupt
.

.
finally try .

320

22.2

22.

threading

threading
, thread. from threading import *.

activeCount()
, . , enumerate().
Condition([lock])
, . .
lock, , Lock()
RLock(). . RLock().
currentThread()
, .
threading,
.
enumerate()
, ,
threading ( ).
, , .
Event()
, . ( ) .
Lock()
, .
thread.allocate_lock().
RLock()
, . ,
Lock(), .
,
.
Semaphore([count])
, . count ( 1).
, .

22.2. threading

321

Thread([keyword_list])
.
(keyword_list). ,
,
target , . run() ,
args kwargs ( ). name ; Thread-N, N
.
.

22.2.1

Lock() RLock() , :
acquire([waitflag])
() , ,
, ( None). waitflag ( ), : 1
( , ), 0 ( ) ,
. 1,
, 0.
release()
. .
, RLock(),
.
, Lock(), ( ), ,
RLock(), acquire() , ,
release().

22.2.2

, Condition() ,
.
, , .

322

22.

, , acquire() release(), , . wait(), notify() notifyAll(),


, acquire().
wait() -
, notify() notifyAll().
. .
notify() notifyAll() , . , , wait(), , , notify() notifyAll()
.
. make_an_item_available() , get_an_available_item()
an_item_is_available() ,
( ) .
:
#
cv.acquire()
make_an_item_available()
cv.notify()
cv.release()
#
cv.acquire()
while not an_item_is_available():
cv.wait()
get_an_available_item()
cv.release()

acquire([...])
release()
, .
wait([timeout])
, , ,
notify() notifyAll(), . None
timeout ( ),
. .
, RLock(),
.

22.2. threading

323

notify()
, , .
notifyAll()
, .

22.2.3

, Semaphore() ,
, (. 22.2.1).
, acquire() release().
, Semaphore().
: acquire()
, ,
release().

22.2.4

, Event() :
. - . , . ( )
.
isSet()
1, ( ).
set()
( ).
, , .
clear()
( ).
wait([timeout])
, , ,
,
set(). None timeout ( ),
.
.

324

22.

22.2.5 ,
Thread , .
: ,
, target run()
. ,
, , . ,
(Thread.__init__()) ,
- .
, , start(). ,
run().
, Thread .
setName() getName().
, join() ,
. , join()
, , .
(daemon).
, .
.
setDaemon() getDaemon().
, .
. , , , threading.
. , join().

start()
( run() ) .
.
run()
,
. .
run() , (
target).
join([timeout])
( )
, .
None timeout ( ), -

22.3. Queue

325

. (
timeout None) .
. , () .
, .
getName()
.
setName(name)
. ,
.
. .
isAlive()
1, .
start() ( run()).
isDaemon()
, ,
.
setDaemon(daemonic)
, , , daemonic: ,
. . , .

.

22.3

Queue

Queue , (FIFO),
.
thread.
Queue(maxsize)
-. maxsize ( ) , .
, maxsize ,
.
Empty
get_nowait() ( get()
block ).

326

22.

Full
put_nowait() ( put()
block ).
Queue :

qsize()
( ).
empty()
1, ( ) , 0.
full()
1, ( )
, 0.
put(item [, block])
. block ,
, . block ,
, ,
Full.
put_nowait(item)
put(item, 0).
get([block])
() . block
, , . block
, ,
, Empty.
get_nowait()
get(0).
, qsize(), empty()
full(): .

327

23


, , , , .
1 .
Python , shelve.
anydbm

DBM.

dumbdbm

, DBM.

dbhash

DBM BSD.

dbm

(n)dbm.

gdbm

gdbm.

whichdb

, DBM .

bsddb

BSD.

23.1

DBM

anydbm DBM
: dbhash ( bsddb), gdbm dbm.
, ,
Python dumbdbm.
dbhash UNIX Windows DBM BSD db.
bsddb.
dbm gdbm UNIX.
, ,
.
1
,
.
, .

328

23.

23.1.1

- :
open(filename [, flag [, mode]])
filename
. , anydbm.open()
whichdb
. anydbm.open()
, .
flag :
r
( ).
w
.
c
. , .
n
( ) .
dbhash.open() , , l, .
gdbm.open() f
: (.
sync() 23.1.3).
mode , , (umask).
0666.
error
, , . ,
, KeyError.
dbhash.error bsddb.error.
anydbm , anydbm ( ) , .
- , ,
except, .
, open() , , : ,

23.1. DBM

329

, has_key() keys().
. , :
close()
.
, dbhash.open() gdbm.open(), , .

23.1.2

,
dbhash.open()

first()
.
, KeyError. first() next() .
next()
. , , ,
:
k, v = db.first()
try:
print k, v
k, v = db.next()
except KeyError:
pass
sync()
.

23.1.3

,
gdbm.open()

firstkey()
.
firstkey() nextkey().
nextkey(key)
, key.
, :
k = db.firstkey()
while k != None:
print k
k = db.nextkey(k)

330

23.

reorganize()
, .
(reorganize()
, ).
sync()
.

23.2

whichdb

, ,
: dbm, gdbm dbhash.

whichdb(filename)
None filename
, () .
(, gdbm),
.

23.3

bsddb BSD

bsddb BSD db2 . Hash, BTree


Record. , , .
: filename
, flag , , mode ( 0666), ,
(umask). flag
:
r
( ).
w
.
c
. , .
2

1.85. Python 2.0,


. , 1.85 2.0 db .

23.3. bsddb BSD

331

n
( )
.
, , l,
.
,
dbopen() BSD db.
hashopen(filename [, flag [, mode [, bsize [, ffactor
[, nelem [, cachesize [, hash [, lorder]]]]]]]])
Hash
.
btopen(filename [, flag [, mode [, btflags [, cachesize
[, maxkeypage [, minkeypage [, psize [, lorder]]]]]]]])
BTree
.
rnopen(filename [, flag [, mode [, rnflags [, cachesize
[, psize [, lorder [, reclen [, bval [, bfname]]]]]]]]])
Record
.
error
, , . ,
, KeyError.
, hashopen(), btopen() rnopen(), , : , , has_key() keys() (
). , :
close()
.
set_location(key)
key , .
, hashopen().
first()
.
, KeyError. first() next() .

332

23.

next()
. , , ,
:
k, v = db.first()
try:
print k, v
k, v = db.next()
except KeyError:
pass
last()
.
, KeyError.
last() previous()
. ,
hashopen().
previous()
.
, hashopen().
sync()
.
:
>>> import bsddb
>>> db = bsddb.btopen(/tmp/spam.db, c)
>>> for i in xrange(10): db[%d % i] = %d % (i*i)
...
>>> db[3]
9
>>> db.keys()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> db.first()
(0, 0)
>>> db.next()
(1, 1)
>>> db.last()
(9, 81)
>>> db.set_location(2)
(2, 4)
>>> db.previous()
(1, 1)
>>> db.sync()
0

333

24


zlib

, , gzip.

gzip

, gzip.

zipfile

zip-.

24.1

zlib , gzip

, , () zlib (http://www.info-zip.org/pub/infozip/zlib/,
RFC 1950). zlib C :
ZLIB_VERSION
.
level
Z_DEFAULT_COMPRESSION, 0 (Z_NO_COMPRESSION) 1
(Z_BEST_SPEED) 9 (Z_BEST_COMPRESSION) :
Z_NO_COMPRESSION
.
Z_BEST_SPEED
.
Z_BEST_COMPRESSION
.
Z_DEFAULT_COMPRESSION
,
. 6.
wbits ( 8 15) 2**wbits.

334

24.

. ( zlib zip-).
MAX_WBITS .
MAX_WBITS.
( method) :
Z_DEFLATED
DEFLATE (. RFC 1951).
:
error
.
adler32(string [, value])
Adler-32 string. , , CRC32,
. value,
, . . Adler-32 ,
.
compress(string [, level])
, string.
compressobj([level [, method [, wbits [, mem_level
[, strategy]]]]])
, . mem_level
: 1 ,
, 9 , . DEF_MEM_LEVEL (8). strategy Z_DEFAULT_STRATEGY, Z_FILTERED
Z_HUFFMAN_ONLY (. zlib C).
crc32(string [, value])
CRC32 (Cyclic Redundancy Check) string.
value, ,
. . CRC32 , .

24.1. zlib , gzip

335

decompress(string [, wbits [, bufsize]])


, string. bufsize (
).
decompressobj([wbits])
, . wbits
, decompress().
, , :
compress(string)
string
string. .
, .
flush([mode])
.
mode flush() :
Z_SYNC_FLUSH
.
.
Z_FULL_FLUSH
Z_SYNC_FLUSH, .
,
.
Z_FINISH
, .
.
, , :
unused_data
. ,
.
decompress(string)
string
string.
.
, .

336

24.

flush()
. .

24.2

gzip , gzip

, zlib, ,
GNU gzip. gzip zlib
GzipFile, gzip- (RFC 1952).
, GzipFile . ,
( compress pack), gzip (gunzip).
GzipFile(filename [, mode [, compresslevel [, fileobj]]])
, . GzipFile , , seek() tell().
None fileobj ( ),
/ ( filename
gzip- None),
filename.
mode : rb, ab wb.
rb.
compresslevel,
1 9. 9, .
close() GzipFile fileobj. ,
, getvalue() StringIO.
open(filename [, mode [, compresslevel]])
GzipFile(filename, mode, compresslevel).

24.3

zipfile zip-

, 1.6, zip.

24.3. zipfile zip-

337

error
, zip .
is_zipfile(path)
1, path zip-, 0.
, .
ZipFile(filename [, mode [, compression]])
, / / filename. mode
: r (), w ( ) a (
). r. compression ,
RuntimeError.
PyZipFile(filename [, mode [, compression]])
ZipFile ,
Python.
ZipInfo([filename [, date_time]])
, . filename
( NoName), date_time
( : , , , ,
, ).
(
compression ZipFile):
ZIP_STORED
( ).
ZIP_DEFLATED
zip- .
zlib.
ZipFile PyZipFile
:
namelist()
, .
infolist()
ZipInfo, , .

338

24.

printdir()
(sys.stdout) .
testzip()
.
, None,
.
getinfo(name)
ZipInfo, name.
read(name)
name
.
write(filename [, arcname [, compress_type]])
filename arcname ( ) compress_type (
, ).
writestr(zinfo, bytes)
.
bytes, , , . .
zinfo, ZipInfo.
close()
( ,
).
PyZipFile :
writepy(pathname [, basename])
pathname , .py-
, pathname ,
, pathname .py, . (.py-)
(.pyo .pyc).
ZipInfo () , , :
filename
.
date_time
, : , , , ,
, .

24.3. zipfile zip-


compress_type
.
comment
( ).
extra
.
CRC
CRC32 .
compress_size
.
file_size
.
FileHeader()
.

339

340

25


Python
, , Python. () ,
.
pdb

Python.

profile

Python.

pstats

25.1

Python

pdb , Python.
,
, , Python . , .
: Pdb ( ).
(
(Pdb) ):
>>> import pdb
>>> import mymodule
>>> pdb.run(mymodule.test())
> <string>(0)?()
(Pdb) continue
> <string>(1)?()
(Pdb) continue
NameError: "There is no ... named spam"
> <string>(1)?()
(Pdb)

25.1. Python

341

:
>>> import mymodule
>>> mymodule.test()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "mymodule.py", line 2, in test
print spam
NameError: There is no variable named spam
>>> import pdb
>>> pdb.pm()
> mymodule.py(2)test()
-> print spam
(Pdb)
pdb.py
:
/usr/local/lib/python1.5/pdb.py myscript.py

25.1.1

pdb , :
run(statements [, globals [, locals]])
statements ( exec)
. : . globals locals ,
;
__main__ (. 10.3.11).
runeval(expression [, globals [, locals]])
expression (
eval()) ( ) .
run().
runcall(function [, arg1 ...])
function ( , ) (
) , . .

342

25. Python

set_trace()
, .
,
, , .
post_mortem(tb)
tb ( traceback).
pm()
sys.last_traceback.

25.1.2

, . ; , h(elp) , h help ( he, hel, H, Help HELP).


. ([]),
(|).
.
: list,
11 .

Python, . , (!),
Python. :
.
, ,
.
, ;; (;
Python). , , ,
;; , .
/ .pdbrc, ,
(
, ).
.
h(elp) [command]
?[command]

. command.
help pdb ,

25.1. Python

343

, PAGER.
command , ! help exec.
w(here)
, .
d(own)
( ).
u(p)
( ).
b(reak) [([filename:]lineno | function) [, condition]]
lineno filename
( ) function.
condition,
, condition .
,
.
.
tbreak [([filename:]lineno | function) [, condition]]
break,
, .
cl(ear) [bpnumber [bpnumber ...]]
(bpnumber), . , .
disable [bpnumber [bpnumber ...]]
, .
enable.
enable [bpnumber [bpnumber ...]]
, .
ignore bpnumber [count]
, bpnumber
count ( 0) .
condition bpnumber [condition]
, : , condition
. condition ,
.
s(tep)

: , .

344

25. Python

n(ext)

. next step , step , next
.
r(eturn)
.
c(ont(inue))
() .
l(ist) [first [, last]]
. 11
, .
, first last , last
first, last , first.
a(rgs)
.
p expression
expression . ,
print Python,
print .
alias [name [command]]
name command. . %1, %2 . . , . .
, name, %* . command , name.
.
command , , .
, .
,
.pdbrc: alias pi for k, v in
%1.__dict__.items(): print "%1.", k, -", v pi,
, alias ps pi self ps, ,
.
unalias name
name.
[!]statements
statements Python . , ,

25.2.

345

( ) .
, global, :
(Pdb) global list_options; list_options = [-l]
(Pdb)
q(uit)
. .

25.2

profile pstats, ,
Python,
.
c 1994, by InfoSeek Corporation, all rights reserved.
Copyright
Permission to use, copy, modify, and distribute this Python software and its associated
documentation for any purpose (subject to the restriction in the following sentence) without
fee is hereby granted, provided that the above copyright notice appears in all copies, and that
both that copyright notice and this permission notice appear in supporting documentation,
and that the name of InfoSeek not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission. This permission is explicitly
restricted to the copying and modification of the software to remain in Python, compiled
Python, or other languages (such as C) wherein the modified or derived code is exclusively
imported into a Python module.
INFOSEEK CORPORATION DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL INFOSEEK CORPORATION BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

25.2.1

.
, .
, foo() (
foo() ), :

346

25. Python

import profile
profile.run(foo())
(, ),
profile.run():
import profile
profile.run(foo(), fooprof)
profile.py
, :
python /usr/local/lib/python1.5/profile.py myscript.py

pstats. ,
:
import pstats
p = pstats.Stats(fooprof)
pstats.Stats . profile.run()
, ,
. . ,
, :
p.sort_stats(name)
p.print_stats()
10 , ( pstats.Stats
,
):
p.sort_stats(cumulative).print_stats(10)
,
.
, , :

25.2.

347

p.print_stats(__init__)
, , , ,
:
p.print_callers(__init__)
p.print_callees(__init__)

25.2.2

profile

:
run(string [, filename ...])
string ( exec) filename (
sys.stdout).
string, , ( ) .
:
ncalls
( : ,
);
tottime
, , , ;
percall
, , , (tottime/ncalls);
cumtime
,
;
percall
,
(cumtime/ncalls);
filename:lineno(function)
, .
run()
Profile. , profile HotProfile
Profile, ,
, ( cumtime).

348

25. Python


run() pstats.Stats.

25.2.3

pstats

Stats([filename ...])
,
( , ) filename. profile,
(
).
add().
Stats :
strip_dirs()
( ).
, ,
() .
add([filename ...])

.
sort_stats([key ...])
. , . . . , sort_stats(name, file)
, .
, . (
, ):
calls
( );
cumulative
, , , ( );
file
;
module
;

25.2.

349

pcalls
( );
line
;
name
;
nfl
, , ( sort_stats(nfl)
sort_stats(name, file, line) );
stdname
, , ;
time
, , , ( ).
reverse_order()
.
print_stats([restriction ...])
( profile.run()). sort_stats().
.
( ),
0.0 1.0 ( ) ( , ).
, .
print_callers([restriction ...])
, .
, , .
print_stats().
print_callees([restriction ...])
, .
print_stats().
,
.

350

26


Python
. ,
open() ( ,
). , .
, ,
. : Web- (, Grail) ,
Python, Internet .
, ,
.
(restricted execution) . ,
. , , ,
( ) .
Python , , , ,
. , -
, .
, . ,
,
.
open() , IOError,
.
Python
__builtins__ , __builtin__
, , , . ,
. , func_globals
__dict__.
:

26.1. rexec
rexec

Bastion

26.1

351

rexec

RExec, r_eval(),
r_execfile(), r_exec() r_import(),
eval() execfile() exec import. , ,
, .
RExec , - .
, RExec (, ),
.
RExec([hooks [, verbose]])
, . hooks RHooks (
) ,
. hooks None,
( ).
verbose, .
hooks, RPC (Remote
Procedure Call) URL (
Grail).
RExec , .
.
( ).
.
nok_builtin_names
, .
RExec (open, reload, __import__). :

352

26.
class MyRExec(RExec):
...
nok_builtin_names = RExec.nok_builtin_names +
, .

ok_builtin_modules
,
. RExec (audioop, array, binascii,
cmath,
errno,
imageop,
marshal,
math,
md5,
operator, parser, regex, pcre, rotor, select,
strop, struct, time).
ok_path
,
. RExec sys.path
rexec.
ok_posix_names
, os, . RExec (error, fstat, listdir, lstat,
readlink, stat, times, uname, getpid, getppid,
getcwd, getuid, getgid, geteuid, getegid).
ok_sys_names
, sys, . RExec (ps1, ps2, copyright, version,
platform, exit, maxint).
RExec .
r_ s_ , sys.stdin, sys.stderr sys.stdout
.
r_eval(code)
s_eval(code)
Python, code. __main__ .
r_exec(code)
s_exec(code)
__main__ Python,
code.

26.1. rexec

353

r_execfile(filename)
s_execfile(filename)
__main__ Python, filename.
RExec ,
.
, (
r_).
r_import(modulename [, globals [, locals
[, fromlist]]])
s_import(modulename [, globals [, locals
[, fromlist]]])
__import__() (.
12) . ImportError,
.
r_open(filename [, mode [, bufsize]])
s_open(filename [, mode [, bufsize]])
open() (. 12).
r_open()
( r rb). ,
r_open() .
r_reload(module)
s_reload(module)
reload() (. 12)
.
r_unload()
s_unload()
(
sys.modules ).
,
/tmp:
from rexec import RExec
from os.path import normpath, islink
class TmpWriterRExec(RExec):
def r_open(self, file, mode=r, bufsize=-1):
if mode not in (r, rb):
file = normpath(file)

354

26.
if file[:5]!=/tmp/ or islink(file):
raise IOError(
"Cant write outside /tmp")
return open(file, mode, bufsize)

26.2

Bastion

rexec
.
Bastion(object [, filter [, name [, bastionclass]]])
bastionclass (
BastionClass), object, , attr_name filter(attr_name)
. filter, , , (_).
AttributeError. ( repr() ) <Bastion for name>. name
None, name repr(object).
BastionClass(getfunc, name)
( )
bastionclass Bastion() .
getfunc ( function), , , , AttributeError,
. name
.

355

27

Internet
,
Internet.
, .
cgi

CGI ( ), HTML .

urllib

URL.

urlparse

URL.

27.1

cgi CGI

, ,
CGI (Common Gateway Interface, ), Python.

27.1.1

CGI- HTTP-, ,
<FORM> <ISINDEX> HTML. HTTP-
( , URL, .) ,
.
. cgi .
, .
CGI- , . , , . :
# : HTML-
print "Content-Type: text/html"

356

27. Internet

# :
print
# : HTML-
print "<html>"
print "<title> CGI-</title>"
print "<body>"
print "<h1> CGI-</h1>"
print " !"
print "</body>"
print "</html>"

27.1.2

cgi

import cgi. from cgi


import *
, .

FieldStorage([**keyword_args])
cgi.
/
CGI1 . , FieldStorage
.

(keyword_args):

fp
( ) , . sys.stdin. GET.
headers
HTTP-.
.
environ
. os.environ.
keep_blank_values
FieldStorage
, ; ,
1

: POST
( URL ?).

27.1. cgi CGI

357

,
.
strict_parsing
, , . strict_parsing,
ValueError.
, FieldStorage , multipart/formdata.
MiniFieldStorage
, application/x-www-form-urlencoded.
FieldStorage MiniFieldStorage
:
name
None.
filename
, , None.
value
, (
) None. ,

.
file
( ) , ,
None, .
type
( Content-Type) None, .
type_options
, Content-Type.
disposition
( Content-Disposition) None.
disposition_options
, Content-Disposition.
headers
, .

358

27. Internet

FieldStorage , , has_key() keys().


:
getvalue(key [, default])
key default,
. ,
. default
None.
make_file(binary)

. tempfile.TemporaryFile(). ,
. binary
b, , . ( )
, .
CGI-, , name addr:
import cgi
print """\
Content-Type: text/html
<html>
<body>"""
form = cgi.FieldStorage()
if form.has_key("name") and form.has_key("addr"):
print """\
<p>: %s</p>
<p>: %s</p>"""
else:
print """\
<h1></h1>
<p>, , .</p>"""
print """\
</body>
</html>"""
, form[key], FieldStorage, MiniFieldStorage ( ) ,

27.1. cgi CGI

359

. getvalue()
. , type() :
value = form.getvalue("username", "")
if type(value) is type([]):
#
usernames = ",".join(value)
else:
#
#
usernames = value
, value
. . , ,
filename file:
fileitem = form["userfile"]
if fileitem.file:
# fileitem .
# ,
# .
linecount = 0
while 1:
if fileitem.file.readline()
linecount += 1
else:
break

HTML- ( multipart/*). , , .
type (obj.type and
obj.type.startswith(multipart/)).

27.1.3

cgi , ,
.
parse([**keyword_args])
/ CGI1 ,

360

27. Internet
.
fp, environ, keep_blank_values strict_parsing,
, FieldStorage (. 27.1.2).

parse_qs(qs [, **keyword_args])
, qs ( application/x-www-form-urlencoded), , .
keep_blank_values strict_parsing,
, FieldStorage (. 27.1.2).
parse_qsl(qs [, **keyword_args])
parse_qs(),
.
parse_multipart(fp, pdict)
multipart/form-data fp
, . pdict
, Content-Type.
, multipart/* . , ,
. FieldStorage .
parse_header(string)
MIME- string , . , string
, Content-Type:
text/plain; encoding=koi8-r text/plain;
encoding=koi8-r.
test()
CGI-, : HTTP- HTML. test()
cgi.py .
print_environ()
HTML.
print_form(form)
, form (
FieldStorage), HTML.
print_directory()
HTML.
print_environ_usage()
, CGI.

27.1. cgi CGI

361

escape(s [, quote])
&, < > s HTML.
,
. quote,
("),
(, a href= + escape(url, 1) + ).
, log-:
logfile
, log-.
, logfp .
logfp
( ) , log-.
log(format [, *args])
format % args + \n log-, logfile logfp .
, .

27.1.4

: , , (, os.system(), os.popen*(), os.exec*(), os.spawn*(),


open()) , .
URL ,
.
, ,
shell , , ( , ).

27.1.5

CGI-

, CGI- (
cgi-bin). , , HTTP-,
. UNIX
#!,
, :
#!/usr/local/bin/python

362

27. Internet

, UNIX, HTTP-
, ,
Python.
, , , HTTP-, . , , (
PATH PYTHONPATH) , .
, ,
, sys.path , . :
import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
, ,
sys.path. , /usr/home/joe/lib/python, .

27.1.6

, CGI- , ,
. ,
:
.
,
( cgi.py) CGI-,
,
. , cgi.py cgi-bin,
:
http://hostname/cgi-bin/cgi.py?name=Joe&addr=At+Home
404 ;
, .
(, 500)
, , . , ,

( addr At home name
Joe) cgi.py .
test() cgi ,
:

27.2. urllib URL

363

import cgi
cgi.test()
, cgi.py.
Python ,
, . (sys.stderr), log-
. ,

import sys
sys.stderr = sys.stdout
try ... except
, :
import cgi
print Content-Type: text/html\n
try:
# CGI-
...
except:
cgi.print_exception(limit=10)

27.2

urllib URL

, . urlopen()
open(), URL (Uniform Resource Locator, ) . , ,
:
seek().

proxy-, . proxy- ,
, (Windows) Internet
Config (Macintosh). UNIX proxy (
) http_proxy, ftp_proxy gopher_proxy URL, proxy- .

364

27. Internet

urlopen(url [, data])
, url. URL
(scheme identifier) file, .
.
, IOError.
HTTP GET. , POST, data
application/x-www-form-urlencoded (.
urlencode() ).
urlretrieve(url [, filename [, reporthook [, data]]])
url . URL
, .
(filename, headers), filename
headers None, url , , info() ,
.
filename , . tempfile.mktemp(). reporthook . ( , )
reporthook
: ,
(-1, ). data
, urlopen().
urlcleanup()
, urlretrieve()2 .
quote(string [, safe])
string
%xx . ,
_, ,, . -. safe
, ;
/.
quote_plus(string [, safe])
quote(), +,
. +
safe, %2b.
unquote(string)
%xx .
2

,
.

27.2. urllib URL

365

unquote_plus(string)
unquote(), + , .
urlencode(dict)
dict ( -
-) application/x-www-form-urlencoded. data urlopen()
urlretrieve() open() URLopener
.
.
key=value , &,
key value quote_plus().
, , read(), readline(),
readlines(), fileno() close(), (.
11.7), :
info()
mimetools.Message, . HTTP . FTP
Content-Length ,
.
Date , Content-Length Content-Type
.
geturl()
URL . HTTP- URL. , URL,
.
urlopen() urlretrieve() FancyURLopener. .
FancyURLopener, URLopener .
URLopener([proxies [, **x509]])
, .
- FancyURLopener.
None proxies,
(scheme identifier) URL proxy .
URL proxy- , .

366

27. Internet
HTTPS
(x509) key_file cert_file.

FancyURLopener([proxies [, **x509]])
URLopener HTTP- 301, 302 401.
301 302 Location URL.
401 . ,
URLopener.
URLopener FancyURLopener
:
open(url [, data])
url , , (. ). , proxy- open_scheme(), scheme
( - _),
open_unknown(), . data , urlopen().
open_unknown(url [, data])
URL
. IOError.
retrieve(url [, filename [, reporthook [, data]]])
url . URL
, . (filename, headers), filename
headers None, url
, , info() , (. ).
filename , . tempfile.mktemp(). reporthook . ( , )
reporthook
: ,
(-1, ). data
, urlopen().
version
, HTTP-. Python-urllib/urllib_ver, urllib_ver

27.3. urlparse URL

367

urllib. version , , .
, URL (scheme identifier) , FTP .
.
. , urllib .
GET
HTTP:
>>>
>>>
...
...
>>>
...
...
>>>

import urllib
params = urllib.urlencode({spam : 1,
eggs : 2,
bacon: 0})
f = urllib.urlopen(
"http://www.musi-cal.com/cgi-bin/query?" +
params)
print f.read()

, POST:
>>>
>>>
...
...
>>>
...
...
>>>

27.3

import urllib
params = urllib.urlencode({spam : 1,
eggs : 2,
bacon: 0})
f = urllib.urlopen(
"http://www.musi-cal.com/cgi-bin/query?",
params)
print f.read()

urlparse URL

URL (Uniform Resource Locator, , RFC 1738) , URL


URL (RFC 1808).
urlparse(urlstring [, default_scheme [, allow_fragments]])
URL : (scheme identifier), , , ,

368

27. Internet
.
scheme://netloc/path;parameters?query#fragment
(scheme, netloc, path, parameters, query, fragment).
URL - , .
, :
>>> import urlparse
>>> urlparse.urlparse(
...
http://www.cwi.nl:80/%7Eguido/Python.html)
(http, www.cwi.nl:80, /%7Eguido/Python.html, ,
, )
default_scheme, (scheme identifier) ,
URL .
allow_fragments, URL ( ) .

urlunparse(tuple)
URL , tuple.
urlparse() urlunparse()
(, URL ), URL.
urljoin(base, rel_url [, allow_fragments])
URL, URL base URL rel_url. :
>>> urljoin(
...
http://www.cwi.nl/%7Eguido/Python.html,
...
FAQ.html)
http://www.cwi.nl/%7Eguido/FAQ.html
allow_fragments, URL ( ) .

369

28

,
Internet
, , Internet. ,
, 29.
rfc822

( RFC 822).

mimetools

MIME.

MimeWriter

MIME.

multifile

, (, MIME).

xdrlib

XDR .

28.1

rfc822

rfc822 Message, (. RFC 822). , .


AddressList, RFC 822, .
Message(file [, seekable])
Message file
(,
readline()).
file .
seek() tell() file rewindbody() Message. ,
unread() .
,
.

370

28. , Internet
seekable 1, seek() tell()
tell().
. , seekable , file
(, ).
, , CR-LF
LF; CR-LF LF.

AddressList(field)
, , RFC 822,
. field None,
.
parsedate(date)
, RFC 822 (, Mon, 20 Nov 1995 19:12:08 -0500).
,
.
,
time.mktime() (
time), None. , 6, 7 8
.
parsedate_tz(date)
parsedate(), None, . ,
. ,
time.timezone
(time.timezone POSIX, RFC 822). date ,
None. , 6, 7 8
.
mktime_tz(tuple)
(,
parsedate_tz()) , (UTC timestamp).
tuple None, ,
tuple .
.
formatdate([tuple])
tuple (
time),
RFC 822 RFC 1123.
Message ( )

28.1. rfc822

371

(has_key(), keys(), values(), items(), get()). ,


m[From], m[from] m[FROM] .
. ,
:
rewindbody()
.
, tell() seek().
isheader(line)
, line RFC 822 , None (,
).
.
islast(line)
, line , , .
, . .
, .
iscomment(line)
, line ,
.
, .
getallmatchingheaders(name)
, name.
, ,
. ,
.
getfirstmatchingheader(name)
, name.
, None.
getrawheader(name)
, (
, ) name, . ,

, .
, None.
getheader(name [, default])
get() .

372

28. , Internet

getaddr(name)
( )
, name. , (None, None). , , m, jack@cwi.nl (Jack
Jansen) ( Jack Jansen <jack@cwi.nl>), m.getaddr(From)
(Jack Jansen, jack@cwi.nl).
getaddrlist(name)
getaddr(), ( ) name (, To
Cc)
. ,
.
getdate(name)
name
(.
parsedate()) None, (
parsedate()).
getdate_tz(name)
getdate(), ;
(. parsedate_tz()) None.
headers
.
.
( ) .
fp
( ) , .
.
AddressList ( a b)
(. 9.7.3) :
len(a)
.
str(a)
( ) . "name" <e_mail>.
a + b
AddressList , ( ).

28.2. mimetools MIME

373

a - b
AddressList ,
a, b ( ).
, AddressList :
addresslist
( ) :
.

28.2

mimetools MIME

Message, rfc822.Message,
, MIME (Multipurpose
Internet Mail Extensions, ).
Message(fp [, seekable])
rfc822.Message
, .
, rfc822.Message (. rfc822).
choose_boundary()
, . IP-, , , ,
, , .
decode(input, output, encoding)
MIME- encoding input output. encoding
: base64, quoted-printable, uuencode
( x-uuencode, uue
x-uue), 7bit 8bit.
encode(input, output, encoding)
input, MIME- encoding
output. encoding
, decode().
copyliteral(input, output)
input ( )
output.

374

28. , Internet

copybinary(input, output)
input ( )
output.
8192 .
Message rfc822.Message
:
getplist()
() content-type. name=value name .
, Content-type: text/html;
spam=1; Spam=2; Spam, getplist() [spam=1,
spam=2, Spam].
getparam(name)
(value) name=value ( )
content-type. "value" <value>, .
getencoding()
, contenttransfer-encoding. , 7bit. .
gettype()
_/,
content-type. , text/plain.
.
getmaintype()
, content-type. ,
text. .
getsubtype()
, content-type. ,
plain. .

28.3

MimeWriter MIME

MimeWriter, , , MIME-:

28.3. MimeWriter MIME

375

MimeWriter(fp)
MIME- fp (
).
MimeWriter :
addheader(name, value [, prefix])
name value.
prefix , : 0 ( ) , 1 .
flushheaders()
( addheader()) . ,
() , ,
message/rfc822, , .
startbody(ctype [, plist [, prefix]])
, ,
() . ctype , content-type ( ).
plist, (name, value),
contenttype. prefix , addheader(),
0 ( ).
startmultipartbody(subtype [, boundary [, plist [, prefix]]])
, ,
, . multipart, boundary
(
mimetools.choose_boundary()), plist content-type. prefix ,
startbody().
nextpart().
nextpart()
MimeWriter, multipart/*. , ,
, . nextpart() startmultipartbody().
lastpart()
,
( multipart/*).

376

28. , Internet

28.4

multifile ,

MultiFile, ,
: readline()
.
MIME, , ,
.

MultiFile(fp [, seekable])
, . fp
( ) , . fp
readline(), seek() tell(). .
seekable, seek() tell() fp .
Error

.
MultiFile
: , .
, .
.
MultiFile :
push(str)
. , , ,
.
MultiFile ,
pop()
next().

, ,
( , Error).
readline()
.
.

( ), Error.

28.4. multifile , . . .

377

readlines()
.
read()
.
next()
, , 0, (
) 1.
pop()
.
seek(pos [, whence])
. ,
seek() (. 11.7).
tell()
.
is_data(str)
1, str
( ), ( ) 0.
, --
( MIME).
:
0, , .
section_divider(str)
str ( ,
) , . , --
( MIME). ,
.
end_marker(str)
str ( ,
) , . , --
( MIME). ,
.
, MultiFile :

378

28. , Internet

level
.
last
(1), .
, (
MIME) , (
, ):
import mimetools
import multifile
import StringIO
def extract_mime_part_matching(stream, mimetype):
msg = mimetools.Message(stream)
msgtype = msg.gettype()
params = msg.getplist()
data = StringIO.StringIO()
if msgtype.startswith(multipart/):
file = multifile.MultiFile(stream)
file.push(msg.getparam(boundary))
while file.next():
submsg = mimetools.Message(file)
try:
data = StringIO.StringIO()
mimetools.decode(file, data,
submsg.getencoding())
except ValueError:
continue
if submsg.gettype() == mimetype:
break
file.pop()
return data.getvalue()

28.5

xdrlib XDR

xdrlib XDR (eXternal


Data Representation, - )
RFC 10141 , .
1
XDR Sun Microsystems 1987 ,
RFC 1832.

28.5. xdrlib XDR

379

( ) 20.
: XDR-
.

Packer()
XDR-.
Unpacker(data)
XDR-,
( , ) data.
Packer :
get_buffer()

( ).
reset()
.
pack_uint(value)
pack_int(value)
pack_enum(value)
pack_bool(value)
pack_uhyper(value)
pack_hyper(value)
pack_float(value)
pack_double(value)
XDR- value
.
pack_fstring(n, s)
pack_fopaque(n, s)
XDR- s n. , . ,
4 .
pack_string(s)
pack_opaque(s)
pack_bytes(s)
XDR- s (
, ).
pack_list(list, pack_item)
XDR- list,

380

28. , Internet
. 1 ( ), , () pack_item.
0 ( ).
, :
import xdrlib
p = xdrlib.Packer()
p.pack_list([1, 2, 3], p.pack_int)

pack_farray(n, array, pack_item)


XDR- array
n. , , len(array), ValueError. ()
pack_item.
pack_array(array, pack_item)
XDR- array
. , , () pack_item .
Unpacker
:
reset(data)
data.
get_position()
.
set_position(pos)
pos . ,
.
get_buffer()
.
done()
. ,
.

28.5. xdrlib XDR

381

unpack_uint()
unpack_int()
unpack_enum()
unpack_bool()
unpack_uhyper()
unpack_hyper()
unpack_float()
unpack_double()
XDR- .
unpack_fstring(n)
unpack_fopaque(n)
XDR-
n. ,
4 .
.
unpack_string()
unpack_opaque()
unpack_bytes()
XDR- . , .
.
unpack_list(unpack_item)
XDR-
. , 1 , 0. ()
unpack_item, .
unpack_farray(n, unpack_item)
XDR- n.
() unpack_item,
.
unpack_array(unpack_item)
XDR- . , .
() unpack_item,
.
:

382

28. , Internet

Error
. msg, .
ConversionError
unpack_*()
Unpacker, XDR- , pack_*() Packer,
.

383

29



, , : SGML (Standard Generalized Markup Language, ), HTML (Hypertext Markup Language,
) XML (Extensible Markup Language, ).
sgmllib

SGML (,
HTML).

htmllib

HTML-.

htmlentitydefs

HTML.

xml.parsers.expat

XML- ( DTD) Expat C.

xml.sax

SAX2 XML.

xml.sax.handler

SAX-.

xml.sax.saxutils

,
SAX.

xml.sax.xmlreader

, XML SAX-.

xmllib

XML-.

29.1

sgmllib SGML-

SGMLParser, SGML (Standard Generalized Markup Language, ). SGML,


HTML ( sgmllib htmllib).

SGMLParser()

384

29.
, SGML. :

=""...> </> .

<

&#;.
(entity) &;.
<!---->.
SGMLParser ( ,
, , DTD):
reset()
. . .
setnomoretags()
.
(CDATA).
<PLAINTEXT> HTML.
setliteral()
.
(CDATA).
feed(data)
data .
, ,
close().
close()
.
, .
.
get_starttag_text()
.
.
handle_starttag(tag, method, attributes)
,
start_tag() do_tag(). tag ,
, method ,
. attributes
(name, value) , , name , , value
. method(attributes).

29.1. sgmllib SGML-

385

handle_endtag(tag, method)
,
end_tag(). tag , , method , . method().
handle_data(data)
.
: .
handle_charref(ref)
&#ref;. 0 255
chr() handle_data(). ref ,
unknown_charref(ref) .
handle_entityref(ref)
&ref;. ( ) entitydefs,
.
ref, handle_data() , unknown_entityref(ref).
entitydefs amp, apos, gt, lt
quot.
handle_comment(comment)
. comment , <!-- -->.
.
report_unbalanced(tag)
, tag,
.
unknown_starttag(tag)
( start_tag() do_tag()).
: .
unknown_endtag(tag)
( end_tag()).
: .
unknown_charref(ref)
&#ref; (. handle_charref()).
: .

386

29.

unknown_entityref(ref)

&ref; (. handle_entityref()). : .
, .
:
( tag ,
, , ).
attributes (name, value) , , name ,
, value .
start_tag(attributes)
tag. do_tag().
do_tag(attributes)
tag,
.
end_tag()
tag.
, . ,
start_tag(). end_tag() .
, do_tag() unknown_tag()
end_tag() .

29.2

htmllib HTML-

HTMLParser ( sgmllib.SGMLParser),
, HTML (Hypertext Markup Language, ). HTML 2.01 .
HTMLParser , . formatter
(
, ).
1

http://www.w3.org/hypertext/WWW/MarkUp/html-spec/html-spec_toc.html

29.2. htmllib HTML-

387

HTMLParser(formatter)
, HTML.
,
HTML 2.0 ( htmlentitydefs),
HTML 2.0 HTML 3.0 3.2.
, ( sgmllib.SGMLParser), HTMLParser :
formatter
, ,
.
nofill
,
handle_data() save_end(),
.
<pre>.
anchor_bgn(href, name, type)
, . <a> ( , ). , , ,
anchorlist.
anchor_end()
, . [index], index
( anchorlist).
handle_image(src, alt [, ismap [, align [, width
[, height]]]])
. <img> ( width height
). handle_data(alt).
save_bgn()
, , , ( formatter ).
save_end().
save_end()
,
, . nofill
, .

388

29.

29.3

htmlentitydefs HTML

, htmllib entitydefs htmllib.HTMLParser.


(entity) HTML 2.0,
Latin-1 (ISO-8859-1). , Latin-1, &#ref;, ref
Unicode.
entitydefs
, HTML 2.0 Latin-1
Unicode &#ref;.

29.4

xml.parsers.expat XML Expat

xml.parsers.expat , 2.0 Expat, XML- DTD2 . ,


:
ErrorString(err_code)
err_code.
ParserCreate([encoding [, namespace_separator]])
, XML.
None, , :
UTF-8, UTF-16 ISO-8859-1 ( UTF-8 UTF-16).
None namespace_separator (
), .
, - , StartElementHandler()
EndElementHandler() namespace_URI + namespace_separator +
name, namespace_URI URI name
. namespace_separator \000,
.
, namespace_separator
:
2

xml.parsers.expat pyexpat.
pyexpat .

29.4. xml.parsers.expat . . .

389

<?xml version="1.0"?>
<root xmlns
= "http://default-namespace.org/"
xmlns:py = "http://www.python.org/ns/">
<py:elem1 />
<elem2 xmlns="" />
</root>
StartElementHandler()
:
http://default-namespace.org/ root
http://www.python.org/ns/ elem1
elem2
error
, XML- .
errors
, XML_ERROR_* . ErrorCode , -
ParserCreate().
XMLParserType
, ParserCreate().
, - ParserCreate(), :
Parse(data [, isfinal])
data, .
isfinal .
ParseFile(file)
,
file ( read() , , ).
SetBase(base)
, URI : base ExternalEntityRefHandler, NotationDeclHandler
UnparsedEntityDeclHandler.
GetBase()
,
SetBase(), None, SetBase() .
, - ParserCreate(), :

390

29.

returns_unicode
1 ( ), -,
, Unicode, 0 , UTF-8.
, .
.
, Parse() ParseFile() error.
ErrorByteIndex
( ), , .
ErrorCode
.
ErrorString() , errors.
ErrorColumnNumber
, .
ErrorLineNumber
, .
,
obj obj.handler = func, handler
func ,
. , ,
.
StartElementHandler(name, attributes)
. name
attributes , .
EndElementHandler(name)
. name
.
ProcessingInstructionHandler(name, data)
(PI, Processing Instruction)
<?name data?> ( <?xml data?>).
CharacterDataHandler(data)
.
UnparsedEntityDeclHandler(entityName, base, systemId,
publicId, notationName)
(NDATA).

29.4. xml.parsers.expat . . .

391

NotationDeclHandler(notationName, base, systemId,


publicId)
(<!NOTATION ...>).
StartNamespaceDeclHandler(prefix, uri)
, ( )
.
EndNamespaceDeclHandler(prefix)
, .
CommentHandler(data)
.
StartCdataSectionHandler()
CDATA.
EndCdataSectionHandler()
CDATA.
DefaultHandler(data)
XML-, . data .
DefaultHandlerExpand(data)
XML-, . data
.
NotStandaloneHandler()
, XML-
(standalone="no" ).

ExternalEntityRefHandler(context, base, systemId,


publicId)
.
:
from xml.parsers import expat
def start_element(name, attrs):
print :, name, attrs
def end_element(name):
print :, name
def char_data(data):
print :, repr(data)

392

29.

p = expat.ParserCreate()
p.returns_unicode = 0
p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data
p.Parse("""\
<?xml version="1.0"?>
<parent id="top">
<child1 name="paul">Text goes here</child1>
<child2 name="fred">More text</child2>
</parent>""")
:
: parent {id: top}
: child1 {name: paul}
: Text goes here
: child1
: \012
: child2 {name: fred}
: More text
: child2
: \012
: parent

29.5

xml.sax SAX2 XML-

, 2.0 SAX (Simple API for XML,


XML) .
xml.sax :
make_parser([parser_list])

SAX

(
xml.sax.xmlreader.XMLReader ), XML-.
.
parser_list ( ), ,
.
parse(filename_or_stream, handler [, error_handler])
,

XML-,

29.5. xml.sax SAX2 . . .

393

filename_or_stream.
filename_or_stream ( )
. handler
ContentHandler, .
error_handler (
ErrorHandler) ,
SAXParseException.
parseString(string, handler [, error_handler])
parse(), XML-, string.
SAX- , , SAX-, -
, XML-. , . InputSource, Locator, + AttributesImpl XMLReader
xml.sax.xmlreader, xml.sax.handler. xml.sax
InputSource, ContentHandler ErrorHandler.
:
SAXException
.
SAXException
, , , .
getMessage() getException() ( None).
SAXParseException
XML-.
SAXParseException getColumnNumber(),
getLineNumber(), getPublicId() getSystemId(), , , ,
, None.
SAXNotRecognizedException
,
.
SAXNotSupportedException
, .
SAXReaderNotAvailable
,

394

29.
,
.

29.6

xml.sax.handler SAX-

(, 2.0) SAX (. xml.sax) XML-,


DTD (Document Type Definition, ),
.
.
ContentHandler()
SAX-
XML- SAX.
DTDHandler()
DTD ( ).
ErrorHandler()
.
EntityResolver()
.
xml.sax.handler (feature_*)
(property_*). getFeature(), setFeature(), getProperty() setProperty() xml.sax.xmlreader.XMLReader . ,
/ XML-.
feature_namespaces
( ).
feature_namespace_prefixes
,
( ).
feature_string_interning
intern() ,
, URI . . (
, ).

29.6. xml.sax.handler . . .

395

feature_validation
DTD.
feature_external_ges
.
feature_external_pes
, DTD.
all_features
, .
property_lexical_handler
(, ).
2.0 .
property_declaration_handler
, DTD (
). 2.0 .
property_dom_node
,
(DOM).
.
property_xml_string
, .
.
all_properties
.

29.6.1

ContentHandler

ContentHandler :
setDocumentLocator(locator)
XML- . locator ( xml.sax.xmlreader.Locator)
.
. , locator
.
startDocument()
.

396

29.

endDocument()
(
, ).
startPrefixMapping(prefix, uri)
. : XML- prefix URI uri , feature_namespaces ( ). startPrefixMapping() startElement(),
startPrefixMapping() .
endPrefixMapping(prefix)
.
endPrefixMapping()
endElement(),
endPrefixMapping() .
startElement(name, attrs)
( ). name ,
attrs xml.sax.xmlreader.AttributesImpl, .
endElement(name)
( ).
name .
startElementNS(name, qname, attrs)
( ).
name , URI , qname
( None,
feature_namespaces) attrs
xml.sax.xmlreader.AttributesNSImpl, .
endElementNS(name, qname)
( ).
name , URI , qname
( None,
feature_namespaces).
characters(content)
( content).
. ,
. content
, Unicode.

29.6. xml.sax.handler . . .

397

ignorableWhitespace(whitespace)
( whitespace) , .
. ,
.
processingInstruction(target, data)
<?target data?>.
<?xml ...>.
skippedEntity(name)
,
(,
DTD).

29.6.2

DTDHandler

DTDHandler :
notationDecl(name, publicId, systemId)
(<!NOTATION ...>).
unparsedEntityDecl(name, publicId, systemId, ndata)
(NDATA).

29.6.3

ErrorHandler

ErrorHandler :
error(exception)
, . exception.
fatalError(exception)
, , .
exception.
warning(exception)
.
(sys.stdout) exception.

398

29.6.4

29.

EntityResolver

EntityResolver :
resolveEntity(publicId, systemId)
. ,
xml.sax.xmlreader.InputSource, . systemId.

29.7

xml.sax.saxutils
, SAX

(, 2.0) ,
, SAX.
escape(data [, entities])
&, < > data .
, entities ,
.
XMLGenerator([out [, encoding]])
ContentHandler, SAX- XML-. ,
XMLGenerator , XML-, .
( ) out,
sys.stdout. encoding
( iso-8859-1).
XMLFilterBase(base)
base ( xml.sax.xmlreader.XMLReader
), XML-, SAX-. . , .
prepare_input_source(source [, base])
xml.sax.xmlreader.InputSource,
. source , ( )

29.8. xml.sax.xmlreader , . . .

399

xml.sax.xmlreader.InputSource. base ( ) URL ( ).


prepare_input_source() source parse() ,
XML-.

29.8

xml.sax.xmlreader , XML

XML- SAX-
Python, create_parser(), -.
xml.sax.make_parser() .
XML- ,
XMLReader.
xml.sax.xmlreader :
XMLReader()
XML-. SAX-.
IncrementalParser()
parse() , . , .
IncrementalParser() parse(), . .
Locator()
, SAX .
InputSource([systemId])
, : , ,
. , .
AttributesImpl(attrs)

startElement() . attrs
.

400

29.

AttributesNSImpl(attrs, qnames)
AttributesImpl, startElement() . attrs qnames
,
URI ,
.

29.8.1

XMLReader

XMLReader :
parse(source)
XML-, . source
( URL), ( ) InputSource.
getContentHandler()
, , ( xml.sax.handler.ContentHandler ).
setContentHandler(handler)
handler , , ( xml.sax.handler.ContentHandler
). ( ) , .
getDTDHandler()
, , DTD
( xml.sax.handler.DTDHandler ).
setDTDHandler(handler)
handler , ,
DTD ( xml.sax.handler.DTDHandler ). ( ) ,
.
getEntityResolver()
, ( xml.sax.handler.EntityResolver
).
setEntityResolver(resolver)
resolver ,
( xml.sax.handler.EntityResolver

29.8. xml.sax.xmlreader , . . .

401

). ( ) , , (
).
getErrorHandler()

(
xml.sax.handler.ErrorHandler ).
setErrorHandler(handler)
handler . ( ) ,

(sys.stdout).
setLocale(locale)
.
getFeature(featurename)
featurename.
, SAXNotRecognizedException.

xml.sax.handler.
setFeature(featurename, value)
featurename.
SAXNotRecognizedException,
SAXNotSupportedException.
getProperty(propertyname)
propertyname.
, SAXNotRecognizedException.
xml.sax.handler.
setProperty(propertyname, value)
propertyname.
SAXNotRecognizedException,

SAXNotSupportedException.

29.8.2

IncrementalParser

IncrementalParser XMLReader, :
feed(data)
data.

402

29.

close()
.
reset()
close()
.

29.8.3

Locator

Locator :
getColumnNumber()
, , (-1, ).
getLineNumber()
, , (-1, ).
getPublicId()
(None, ).
getSystemId()
(None, ).

29.8.4

InputSource

InputSource :
setPublicId(id)
id.
getPublicId()
.
setSystemId(id)
id.
getSystemId()
.
setEncoding(encoding)
. encoding ,

29.8. xml.sax.xmlreader , . . .

403

XML-. , , .
getEncoding()
None, .
setByteStream(bytefile)
( , ), .
setEncoding. , , ( ) Unicode.
getByteStream()
, .
getEncoding.
setCharacterStream(charfile)
( ,
Unicode), .
getCharacterStream()
, .

29.8.5

AttributesImpl AttributesNSImpl

AttributesImpl AttributesNSImpl , , . AttributesImpl (


name ) ,
AttributesNSImpl : URI . ( qname )
.
(copy(), get(), has_key(), items(), keys() values())
:
getLength()
.
getNames()
( ).

404

29.

getType(name)
name ( CDATA).
getValue(name)
name.
getValueByQName(qname)
qname.
AttributesImpl getValue().
getNameByQName(qname)
( ) qname.
AttributesImpl
KeyError.
getQNameByName(name)
name.
AttributesImpl KeyError.
getQNames()
.
AttributesImpl getNames().

29.9

xmllib XML-

xmllib xml.sax.
XMLParser,
, XML3 (Extensible
Markup Language, ).

XMLParser([**keyword_args])
,
XML.
(keyword_args):
accept_unquoted_attributes
, , . 0.
accept_missing_endtag_name
, (</>). 0.
3

http://www.w3.org/TR/REC-xml, http://www.w3.org/XML/

29.9. xmllib XML-

405

map_case
,
. 0.
accept_utf8
,
UTF-8. 0.
translate_attribute_references
,
. 1.
XMLParser ,
(DTD):
attributes
,
( None,
).
.
elements
( , ), None,
unknown_starttag() unknown_endtag().

.
entitydefs
. , lt, gt, amp, quot apos
( ).
reset()
. . .
setnomoretags()
. (CDATA).
setliteral()
.
(CDATA). ,
.
feed(data)
data .

406

29.
, ,
close().

close()
.
, .
.
translate_references(data)
(&#ref;) (&ref;)
data .
getnamespace()
( ) URI (Uniform Resource Identifier,
).
handle_xml(encoding, standalone)
<?xml ...?>. ( None
no ). .
handle_doctype(tag, pubid, syslit, data)
. tag
, pubid ( None, ), syslit
data DTD (Document Type
Definition, ) None,
DTD. .
handle_starttag(tag, method, attributes)
, elements. tag , method (), , attributes , , , (
). , <A
HREF="http://www.cwi.nl/ obj.handle_starttag(A,
obj.elements[A][0], {HREF: http://www.cwi.nl/}).
handle_starttag method(attributes).
handle_endtag(tag, method)
, elements. tag , method (), . , </A>
obj.handle_endtag(A, obj.elements[A][1]).
handle_endtag method().

29.9. xmllib XML-

407

handle_data(data)
.
: .
handle_charref(ref)
&#ref;. 0 255
chr() handle_data(). ref ,
unknown_charref(ref) .
handle_comment(comment)
. comment , <!-- -->.
.
handle_cdata(data)
CDATA ( <![CDATA[ ]]>).
:
.
handle_proc(name, data)
(PI, Processing Instruction) <?name
data?>. , <?xml data?> handle_xml().
handle_proc() : .
handle_special(data)
<!data>. , <!DOCTYPE ...>
handle_doctype().
handle_special() : .
syntax_error(message)
, ,
(
RuntimeError).
message , . RuntimeError.
unknown_starttag(tag)
. : .
unknown_endtag(tag)
. : .

408

29.

unknown_charref(ref)
&#ref;. :
.
unknown_entityref(ref)

&ref;. :
syntax_error() .
xmllib XML. (, ), , URI, ,
, . , <html xmlns=http://www.w3.org/TR/REC-html40>
http://www.w3.org/TR/REC-html40 html
<html:a href=http://frob.com> http://www.w3.org/TR/REC-html40 a
http://www.w3.org/TR/REC-html40 href.

409

30

fileinput

ConfigParser

shlex

cmd

calendar

,
cal.

30.1

fileinput

fileinput , , / , .
:
import fileinput
for line in fileinput.input():
process(line)
, (sys.argv[1:]), ,
. -
sys.stdin. (
) input().
, .

input([files [, inplace [, backup]]])


FileInput,
. .

410

30.

FileInput, input(). input() close() RuntimeError. ,


.
filename()
, . ,
( nextfile()), None.
<stdin>.
lineno()
. , (
nextfile()), 0.
filelineno()
. ,
(
nextfile()), 0.
isfirstline()
1,
, 0.
isstdin()
1,
(sys.stdin), 0.
nextfile()
. ,
, .
.
close()
close() , input().
:
FileInput([files [, inplace [, backup]]])
, . files
. sys.argv[1:] ,
. - ,
sys.stdin.

30.1. fileinput

411

inplace,
, backup ( .bak) , , .
,
, , , print. .
(in-place filtering) .
MS-DOS,
.
FileInput ,
( for), :
filename()
, . ,
( nextfile()), None.
<stdin>.
lineno()
. ,
(
nextfile()), 0.
filelineno()
. ,
( nextfile()), 0.
isfirstline()
1,
, 0.
isstdin()
1,
(sys.stdin), 0.
nextfile()
. ,
, .
.
close()
.
readline()
.

412

30.
, obj.readline() for line in obj
( RuntimeError).

30.2

ConfigParser

ConfigParser, , .ini- Windows.


,
[] : .
RFC 822.
=. ,
. ,
DEFAULT ( ):
foodir: %(dir)s/whatever
dir=frob
%(dir)s dir
( frob).
. , # ; .

ConfigParser([defaults])
, . defaults :
, , %()s. , __name__ ,
.
MAX_INTERPOLATION_DEPTH
.
: .
:
Error
, , .
NoSectionError
( section ) .

30.2. ConfigParser

413

DuplicateSectionError
( section ) .
NoOptionError
( option )
( section).
InterpolationError
%()s
( reference , section option).
InterpolationDepthError
(MAX_INTERPOLATION_DEPTH)
(
section option
).
MissingSectionHeaderError
. , , ,
filename, lineno line .
ParsingError
. filename errors
, .
ConfigParser :
defaults()
.
sections()
. DEFAULT .
add_section(section)
section. ,
DuplicateSectionError.
has_section(section)
1, section, 0.
DEFAULT .
options(section)
section.

414

30.

has_option(section, option)
1, section
option, 0. , 1.6.
read(filenames)
. filenames
, .
readfp(fp [, filename])
,
( ) fp ( readline()).
filename .
filename , fp.name <???>,
fp name.
get(section, option [, raw [, vars]])
option section. raw , get() , %.
, vars.
, vars
, .
getint(section, option)
option section .
getfloat(section, option)
option section
.
getboolean(section, option)
option section 0
1.
0 1, ValueError.
set(section, option, value)
section,
option value. section DEFAULT, value option .
NoSectionError. set()
, 1.6.
write(fp)
, ( ) fp. , 1.6.
remove_option(section, option)
option section. section DEFAULT, option .

30.3. shlex

415

, section ,
NoSectionError. , 1,
0. remove_option() , 1.6.
remove_section(section)
section. , 1,
0.

30.3

shlex

shlex, , ,
UNIX shell. -, , , (.
ConfigParser).
shlex([stream [, file]])
, .
stream ( ,
read() readline()) ,
sys.stdin. file,
( infile).
shlex :
get_token()
. (
push_token()) .
.
push_token(str)
str .
read_token()
( ) .
.
sourcehook(filename)
.
filename , (
source). sourcehook() ,
( ) .

416

30.

error_leader([file [, line]])
"file", line line: .
file / line ,
.
Emacs UNIX.
shlex , :
commenters
, .
.
#.
wordchars
, . ,
.
whitespace
, ( ). \t\r\n.
quotes
, . , ,
( ,
). .
infile
( None, ). .
instream
, .
source
None. ,
. source ,
. .
debug
, , . debug 0,
.
lineno
(
1).

30.4. cmd

417

token
. .
, , wordchars, whitespace
quotes, . ,
,
. , aint ain#d\nt
"aint".

30.4

cmd

Cmd,
, . Python ( pdb).
Cmd()
.
, .
Cmd :
cmdloop([intro])
: ,
, , .
intro () ,
intro.
foo ,
do_foo(). ? ! help
shell , EOF.
do_help bar
help_bar(). do_help() ,
(
help_*()), . Cmd do_shell() do_EOF().
do_*() None. ( postcmd() ), .
onecmd(str)
str,
.

418

30.

emptyline()
, .
.
default(line)
, (
do_*()). .
precmd(line)
( line). .
postcmd(stop, line)
. stop line ,
do_*(), , precmd(). , , ,
. stop .
preloop()
(
cmdloop()) . .
postloop()
. .
prompt
, .
(Cmd) .
identchars
,
. , 1 .
lastcmd
, (
).
intro
, , . ,
cmdloop() , None.
doc_header
( do_*() help_*()).
1

30.5. calendar

419

misc_header
, ( ,
help_*(), do_*()).
undoc_header
( do_*(), help_*()).
ruler
, .
, . ruler
=.

30.5

calendar

, cal. , . , ,
setfirstweekday().
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
0 () 6 (),
.
setfirstweekday(weekday)
weekday ( 0 6) . ,
:
import calendar
calendar.setfirstweekday(calendar.SUNDAY)
firstweekday()
0 6, , (
) .
isleap(year)
1, year ( ) , 0.

420

30.

leapdays(y1, y2)
y1 y2 - 1 ().
weekday(year, month, day)
, . year
(. time), month ( 1 12)
day ( 1 31). ,
2000 , 13 :
>>> from calendar import weekday, FRIDAY
>>> for month in xrange(1, 13):
...
if weekday(2000, month, 13)==FRIDAY:
...
print month
...
10
monthrange(year, month)
, ( 0
6) ( year) (
month).
monthcalendar(year, month)
( ),
( year) ( month).

. , , .
,
setfirstweekday().
month(theyear, themonth [, datewidth [, linesperweek]])

( theyear) ( themonth). datewidth
linesperweek ,
.
prmonth(theyear, themonth [, datewidth [, linesperweek]])
(sys.stdout) . , month().
calendar(year [, datewidth [, linesperweek [, spaces]]])
year. datewidth, linesperweek spaces ,
, , .
prcal()
(sys.stdout) .
, calendar().

30.5. calendar

421

timegm(time_tuple)
, ( 1970 ) ,
time_tuple (. time).

425

Python
:
python [options] [-c command | file | -] [arguments]
python ( , , , ), options , command
Python, file Python arguments
, sys.argv[1:].
:
-d
. PYTHONDEBUG (.
).
-i
, .
PYTHONINSPECT (. ).
-O
-.
PYTHONOPTIMIZE (. ).
-OO
( -O) - .
-S
site .
-t
.

426

A. . . .

-tt
TabError .
-u
.

PYTHONUNBUFFERED (. ). CGI-.
-U
Unicode, ... u.... , - , .
, 1.6.
-v
. PYTHONVERBOSE
(. ).
-x
.
,
UNIX.
-X
. 1.6, .
-h
.
, 2.0.
-V
. , 2.0.
,
:
PYTHONDEBUG
, .
PYTHONINSPECT
,
,
.

427
PYTHONOPTIMIZE
, -.
PYTHONUNBUFFERED
,
. CGI-.
PYTHONVERBOSE
, .
PYTHONSTARTUP
, .
PYTHONPATH
, ;, .
sys.path (. sys).
PYTHONHOME

sys.prefix
,
sys.exec_prefix.
prefix[;exec_prefix] (. sys).

428


:
NAME
().
NUMBER
.
STRING
.
NEWLINE
( ),
.
ENDMARKER
().
INDENT
.
DEDENT
.
:
single_input
.
file_input
, .
eval_input
-, eval() ,
input().
single_input:

NEWLINE |
simple_stmt |
compound_stmt NEWLINE

429

file_input:

(NEWLINE | stmt)* ENDMARKER

eval_input:

testlist NEWLINE* ENDMARKER

funcdef:

def NAME parameters : suite

parameters:

( [varargslist] )

varargslist:

(fpdef [= test] ,)*


(* NAME [, ** NAME] | ** NAME) |
fpdef [= test] (, fpdef [= test])*
[,]

fpdef:

NAME | ( fplist )

fplist:

fpdef (, fpdef)* [,]

stmt:

simple_stmt | compound_stmt

simple_stmt:

small_stmt (; small_stmt)* [;]


NEWLINE

small_stmt:

expr_stmt | print_stmt | del_stmt |


pass_stmt | flow_stmt | import_stmt |
global_stmt | exec_stmt | assert_stmt

expr_stmt:

testlist (augassign testlist |


(= testlist)*)

augassign:

+= | -= | *= | /= | %= | &=
| |= | ^= | <<= | >>= | **=

print_stmt:

print ( [ test (, test)* [,] ] |


>> test [ (, test)+ [,] ] )

del_stmt:

del exprlist

pass_stmt:

pass

flow_stmt:

break_stmt | continue_stmt |
return_stmt | raise_stmt

break_stmt:

break

430

B.

continue_stmt:

continue

return_stmt:

return [testlist]

raise_stmt:

raise [test [, test [, test]]]

import_stmt:

import dotted_as_name
(, dotted_as_name)* |
from dotted_name import
(* | import_as_name
(, import_as_name)*)

import_as_name: NAME [NAME NAME]


dotted_as_name: dotted_name [NAME NAME]
dotted_name:

NAME (. NAME)*

global_stmt:

global NAME (, NAME)*

exec_stmt:

exec expr [in test [, test]]

assert_stmt:

assert test [, test]

compound_stmt:

if_stmt | while_stmt | for_stmt |


try_stmt | funcdef | classdef

if_stmt:

if test : suite
(elif test : suite)*
[else : suite]

while_stmt:

while test : suite


[else : suite]

for_stmt:

for exprlist in testlist : suite


[else : suite]

try_stmt:

(try : suite
(except_clause : suite)+
[else : suite] |
try : suite
finally : suite)

except_clause:

except [test [, test]]

431
suite:

simple_stmt |
NEWLINE INDENT stmt+ DEDENT

test:

and_test (or and_test)* | lambdef

and_test:

not_test (and not_test)*

not_test:

not not_test | comparison

comparison:

expr (comp_op expr)*

comp_op:

< | > | == | >= | <= | <>


| != | in | not in| is
|is not

expr:

xor_expr (| xor_expr)*

xor_expr:

and_expr (^ and_expr)*

and_expr:

shift_expr (& shift_expr)*

shift_expr:

arith_expr ((<< | >>) arith_expr)*

arith_expr:

term ((+ | -) term)*

term:

factor ((* | / | %) factor)*

factor:

(+ | - | ~) factor | power

power:

atom trailer* (** factor)*

atom:

( [testlist] ) |
[ [listmaker] ] |
{ [dictmaker] } |
testlist |
NAME | NUMBER | STRING+

listmaker:

test ( list_for | (, test)* [,] )

lambdef:

lambda [varargslist] : test

trailer:

( [arglist] ) |
[ subscriptlist ] | . NAME

subscriptlist:

subscript (, subscript)* [,]

subscript:

. . . | test |

432

B.
[test] : [test] [sliceop]

sliceop:

: [test]

exprlist:

expr (, expr)* [,]

testlist:

test (, test)* [,]

dictmaker:

test : test (, test : test)*


[,]

classdef:

class NAME [( testlist )] :


suite

arglist:

(argument ,)* (argument [,]| *


test [, ** test] | ** test)

argument:

[test =] test

list_iter:

list_for | list_if

list_for:

for exprlist in testlist


[list_iter]

list_if:

if test [list_iter]

433

anydbm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
atexit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

locale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

B
Bastion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
bisect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
bsddb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330

C
calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
cgi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
cmath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
codecs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
ConfigParser . . . . . . . . . . . . . . . . . . . . . . . . . . 412
cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
cStringIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .231

D
dbhash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
dbm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
dumbdbm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327

E
errno . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299

F
filecmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
fileinput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .409
fnmatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303

G
gc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
gdbm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
getopt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
getpass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
gettext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
glob . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
gzip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336

H
htmlentitydefs . . . . . . . . . . . . . . . . . . . . . . . . 388
htmllib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386

I
imp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

M
marshal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
mimetools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .373
MimeWriter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
mmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
multifile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .376

O
operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
os.path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280

P
pdb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
pickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
popen2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
pprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
pstats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348

Q
Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325

R
random . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
repr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
rexec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
rfc822 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

S
sched . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
sgmllib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
shelve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
shlex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
shutil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
stat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
statvfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
StringIO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

434
struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
sys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

T
tempfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .320
time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
traceback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .208
types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

U
urllib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
urlparse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
UserDict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
UserList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
UserString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255

W
whichdb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
whrandom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

X
xdrlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
xml.parsers.expat . . . . . . . . . . . . . . . . . . . . 388
xml.sax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
xml.sax.handler . . . . . . . . . . . . . . . . . . . . . . 394
xml.sax.saxutils . . . . . . . . . . . . . . . . . . . . . 398
xml.sax.xmlreader . . . . . . . . . . . . . . . . . . . . 399
xmllib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404

Z
zipfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

435


(), . . . . . . .46, 107, 148, 149, 156
*
. . . 27, 108, 133, 135, 161, 204, 205
. . .43, 44,
46, 107
import . . . . . . . . . . . 60, 66, 118
**
. . . . . . . . . . . . . . . . . . . . . . 108, 134, 161
. . 44, 46,
108
**=, . . . . . . . . . . . . . . . . . . . . . . . 114
*=, . . . . . . . . . . . . . . . . . . . . 114, 162
+
. . 27, 108, 133, 135, 161,
204, 205
. . . . . . . .108, 134, 160, 204
+=, . . . . . . . . . . . . . . . . . . . . 114, 162
. . . . . . 108, 133, 161, 204
. . . . . . . .108, 134, 160, 204
-=, . . . . . . . . . . . . . . . . . . . . 114, 162
., . . . . . . . . . 83, 85, 86, 106, 151, 155
... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
.pdbrc, . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
.pythonrc.py, . . . . . . . . . . . . . . . . 22, 191
/, . . . . . . . . . . . . . . . . 108, 134, 161, 204
/=, . . . . . . . . . . . . . . . . . . . . 114, 162
<, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
<=, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
<>, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
<<, . . . . . . . . . . . . . . .108, 134, 161, 205
<<=, . . . . . . . . . . . . . . . . . . 114, 162
=, . . . . . . . . . . . . . . . . . . . . . . 24, 113
==, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
>, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
>=, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
>>, . . . . . . . . . . . . . . . . . . . .108, 134, 161
>>=, . . . . . . . . . . . . . . . . . . 114, 162
[], 28, 107, 135, 145147, 157, 166,
206
%, . . 68, 108, 134, 137, 159, 161, 204
%=, . . . . . . . . . . . . . . . . . . . . . . . . . 114
&, . . . . . . . . . . . . . . . . 108, 134, 161, 205
&=, . . . . . . . . . . . . . . . . . . . . 114, 162
^, . . . . . . . . . . . . . . . . 108, 134, 161, 205
^=, . . . . . . . . . . . . . . . . . . . . 114, 162
|, . . . . . . . . . . . . . . . . 108, 134, 161, 205
|=, . . . . . . . . . . . . . . . . . . . . 114, 162

~, . . . . . . . . . . . . . . . . 108, 134, 160, 205


_, . . . . . . . . . . . . . . . . . 25
__abs__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
operator . . . . . . . . . . . . . . . . . . . . 205
__add__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 204
__all__ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65, 66
__and__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 205
__bases__, class . . . .152
__builtins__ . . . . . . . . . . . . . . . . . . . . . . . . . . 129
__call__(), . . . . . . . 127, 151, 156
__class__, instance 153
__cmp__(), . . . . . . . . . . . . . 109, 154
__coerce__(), . . . . . . . . . . . . . . 161
__complex__(), . . . . . . . . . . . . . 160
__concat__(), operator . . . . 205
__contains__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
operator . . . . . . . . . . . . . . . . . . . . 205
__debug__ . . . . . . . . . . . . . . . . . . . . . . . . . . . 61, 120
__del__(), . . . . . . . . . . . . . 153, 199
__delattr__(), . . . . . . . . 115, 156
__delattr__()(), . . . . . . . . . . 153
__delitem__()
. . . . . . . . . . . . . . . . . . . . . . . . . 115, 157
operator . . . . . . . . . . . . . . . . . . . . 206
__delslice__()
. . . . . . . . . . . . . . . . . . . . . . . . . 115, 158
operator . . . . . . . . . . . . . . . . . . . . 206
__dict__
class . . . . . .149, 152, 350
instance . . 91, 153, 156,
350
module . . . . . . . . . . . . . . 151
__div__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 204
__divmod__(), . . . . . . . . . . . . . . 161
__doc__

builtin_function_or_method . . . 150
class . . . . . . . . . . . . . . . . 152

436
function . . . . . . . . . . . .149
instance method . . 150
module . . . . . . . . . . . . . . 151
type . . . . . . . . . . . . . . . . . 165
__file__, module . . . .151
__float__(), . . . . . . . . . . . . . . . . 160
__getattr__(), . . . 98, 153, 155,
159
__getinitargs__(),
259
__getitem__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
operator . . . . . . . . . . . . . . . . . . . . 206
__getslice__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
operator . . . . . . . . . . . . . . . . . . . . 206
__getstate__(), 259
__hash__(), . . . . . . . . . . . . 155, 256
__hex__(), . . . . . . . . . . . . . . . . . . 159
__iadd__(), . . . . . . . . . . . . . . . . . 162
__iand__(), . . . . . . . . . . . . . . . . . 162
__idiv__(), . . . . . . . . . . . . . . . . . 162
__ilshift__(), . . . . . . . . . . . . . 162
__imod__(), . . . . . . . . . . . . . . . . . 162
__import__(), . . . .119,
170
__imul__(), . . . . . . . . . . . . . . . . . 162
__init__(), . . . 86, 128, 151, 153
__init__.py, . . . . . . . . . . . . . . . . . . . 64, 66
__int__(), . . . . . . . . . . . . . . . . . . 160
__inv__(), operator . . . . . . . . 205
__invert__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
operator . . . . . . . . . . . . . . . . . . . . 205
__ior__(), . . . . . . . . . . . . . . . . . . 162
__ipow__(), . . . . . . . . . . . . . . . . . 162
__irshift__(), . . . . . . . . . . . . . 162
__isub__(), . . . . . . . . . . . . . . . . . 162
__ixor__(), . . . . . . . . . . . . . . . . . 162
__len__(), . . . . . . . . 157, 159, 175
__long__(), . . . . . . . . . . . . . . . . . 160
__lshift__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 205
__members__,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
__methods__,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
__mod__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161


operator . . . . . . . . . . . . . . . . . . . . 204
__module__, class . . 152
__mul__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 204
__name__ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

builtin_function_or_method . . . 150
class . . . . . . . . . . . 152, 182
function . . . . . . . . . . . .149
instance method . . 150
module . . . . . . . . . . . . . . 151
type . . . . . . . . . . . . . . . . . 165
__neg__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
operator . . . . . . . . . . . . . . . . . . . . 204
__nonzero__(), . . . . . . . . . . . . . 155
__not__(), operator . . . . . . . . 205
__oct__(), . . . . . . . . . . . . . . . . . . 159
__or__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 205
__pos__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
operator . . . . . . . . . . . . . . . . . . . . 204
__pow__(), . . . . . . . . . . . . . . . . . . 161
__radd__(), . . . . . . . . . . . . . . . . . 162
__rand__(), . . . . . . . . . . . . . . . . . 162
__rcmp__(), . . . . . . . . . . . . 109, 154
__rdiv__(), . . . . . . . . . . . . . . . . . 162
__rdivmod__(), . . . . . . . . . . . . . 162
__repeat__(), operator . . . . 205
__repr__(), . . . . . . . . . . . . . . . . . 159
__rlshift__(), . . . . . . . . . . . . . 162
__rmod__(), . . . . . . . . . . . . . . . . . 162
__rmul__(), . . . . . . . . . . . . . . . . . 162
__ror__(), . . . . . . . . . . . . . . . . . . 162
__rpow__(), . . . . . . . . . . . . . . . . . 162
__rrshift__(), . . . . . . . . . . . . . 162
__rshift__(), . . . . . . . . . . . . . . 161
__rsub__(), . . . . . . . . . . . . . . . . . 162
__rxor__(), . . . . . . . . . . . . . . . . . 162
__self__,
builtin_function_or_method . . . 151
__setattr__(), . . . 98, 113, 153,
156
__setitem__()
. . . . . . . . . . . . . . . . . . . . . . . . . 113, 157
operator . . . . . . . . . . . . . . . . . . . . 206


__setslice__()
. . . . . . . . . . . . . . . . . . . . . . . . . 113, 158
operator . . . . . . . . . . . . . . . . . . . . 206
__setstate__(), 259
__stderr__, sys . . . . . . . . . . . . . . 197
__stdin__, sys . . . . . . . . . . . . . . . 197
__stdout__, sys . . . . . . . . . . . . . . 197
__str__(), . . . . . . . . . . . . . . . . . . 159
__sub__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 204
__xor__()
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
operator . . . . . . . . . . . . . . . . . . . . 205
_exit(), os . . . . . . . . . . . . . . 186, 277
in, for, . for
__builtins__ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
, . . . . 68, 159, 179

A
abort(), os . . . . . . . . . . . . . . . . . . . 276
abs()
operator . . . . . . . . . . . . . . . . . . . . 205
. . . . . . 25, 160, 171, 205
abspath(), os.path . . . . . . . . . . 280
accept(), socket . . . . . . . . . . . . 310
accept2dyear, time . . . . . . . . . . 291
access(), os . . . . . . . . . . . . . . . . . . 273
acos()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .247
math . . . . . . . . . . . . . . . . . . . . . . . . . . 245
acosh(), cmath . . . . . . . . . . . . . . . 247
activeCount(), threading . .320
add(), operator . . . . . . . . . . . . . . 204
AddressList(), rfc822 . . . . . . 370
adler32(), zlib . . . . . . . . . . . . . . 334
AF_INET, socket . . . . . . . . . . . . . . 308
AF_UNIX, socket . . . . . . . . . . . . . . 308
alarm(), signal . . . . . . . . . . . . . . 306
all_features,
xml.sax.handler . . . . . . . . . . . . . . . . . . 395
all_properties,
xml.sax.handler . . . . . . . . . . . . . . . . . . 395
allocate_lock(), thread . . . 318
altsep, os . . . . . . . . . . . . . . . . . . . . . 280
altzone(), time . . . . . . . . . . . . . . 291
and, . . . . . . . . . . . . . . . . . . . . . . . . 56, 111
and_(), operator . . . . . . . . . . . . 205
append(), list . 41, 47, 48,
146
apply(), . . . . . . . 46, 171

437
aRepr, repr . . . . . . . . . . . . . . . . . . . 215
argv, sys . . . . . . . . . . . . . . . . . . . . . . 192
ArithmeticError, . . . . . . . . . 183
array, array . . . . . . . . . . . . . . . . . . 145
array(), array . . . . . . . . . . . . . . . 252
ArrayType, array . . . . . . . . . . . . 253
as, import . . . . . . . . . . . . . . . . 118
asctime(), time . . . . . . . . . . . . . . 291
asin()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .247
math . . . . . . . . . . . . . . . . . . . . . . . . . . 245
asinh(), cmath . . . . . . . . . . . . . . . 247
assert, . . . . . . . . . . . . . 61, 120, 183
AssertionError, . . . . . 120, 183
atan()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .247
math . . . . . . . . . . . . . . . . . . . . . . . . . . 245
atan2(), math . . . . . . . . . . . . . . . . .245
atanh(), cmath . . . . . . . . . . . . . . . 248
atof()
locale . . . . . . . . . . . . . . . . . . . . . . . 239
string . . . . . . . . . . . . . . . . . . . . . . . 218
atoi()
locale . . . . . . . . . . . . . . . . . . . . . . . 239
string . . . . . . . . . . . . . . . . . . . . . . . 218
atol(), string . . . . . . . . . . . . . . . 218
AttributeError, . . . . . 107, 183
AttributesImpl(),
xml.sax.xmlreader . . . . . . . . . . . . . . . 399
AttributesNSImpl(),
xml.sax.xmlreader . . . . . . . . . . . . . . . 400

B
basename(), os.path . . . . . . . . 280
Bastion(), Bastion . . . . . . . . . . 354
BastionClass(), Bastion . . . 354
betavariate(), random . . . . . . 249
big-endian . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193, 235
bind(), socket . . . . . . . . . . . . . . . 310
bindtextdomain(), gettext 241
bisect(), bisect . . . . . . . . . . . . 251
BOM, codecs . . . . . . . . . . . . . . . . . . . 235
BOM32_BE, codecs . . . . . . . . . . . . 235
BOM32_LE, codecs . . . . . . . . . . . . 235
BOM64_BE, codecs . . . . . . . . . . . . 235
BOM64_LE, codecs . . . . . . . . . . . . 235
BOM_BE, codecs . . . . . . . . . . . . . . . 235
BOM_LE, codecs . . . . . . . . . . . . . . . 235
break, . . . . . . . . . . . . . . . . . . . 39, 116
btopen(), bsddb . . . . . . . . . . . . . . 331
buffer, . . . . . . . 135, 145, 202

438
buffer(), . . . . .145, 171
BufferType, types . . . . . . . . . . . 202
builtin_function_or_method,
. . . . . . . . . . . . . . . . . 150, 203
builtin_module_names, sys 193
BuiltinFunctionType, types
203
BuiltinMethodType, types . .203
byteorder, sys . . . . . . . . . . . . . . . 192

C
C_BUILTIN, imp . . . . . . . . . . . . . . . 212
C_EXTENSION, imp . . . . . . . . . . . . 212
calcsize(), struct . . . . . . . . . . 264
calendar(), calendar . . . . . . . 420
callable(), . . 148, 171
cancel(), sched . . . . . . . . . . . . . . 295
capitalize()
string unicode . . . . 142
string . . . . . . . . . . . . . . . . . . . . . . . 218
capwords(), string . . . . . . . . . . 218
Catalog(), gettext . . . . . . . . . . 242
ceil(), math . . . . . . . . . . . . . . . . . . 246
center()
string unicode . . . . 140
string . . . . . . . . . . . . . . . . . . . . . . . 220
CGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
CHAR_MAX, locale . . . . . . . . . . . . 238
charmap_decode(), codecs . .234
charmap_encode(), codecs . .234
chdir(), os . . . . . . . . . . . . . . . . . . . 273
chmod(), os . . . . . . . . . . . . . . . . . . . 273
choice()
random . . . . . . . . . . . . . . . . . . . . . . . 250
whrandom . . . . . . . . . . . . . . . . . . . . 251
choose_boundary(), mimetools
373
chown(), os . . . . . . . . . . . . . . . . . . . 273
chr(), . . . . . . . . . . . . . . 171
class
. . . . . . . . . . . . . . . . . . . . . . . . . . 85, 128
. . . . . . . . . . . 85, 151, 152, 203
ClassType, types . . . . . . . . . . . . 203
clear(), dictionary . . 148
clock(), time . . . . . . . . . . . . . . . . .291
close()
file . . . . . . . . . . . . . . . . . . . 163
fileinput . . . . . . . . . . . . . . . . . . . 410
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
socket . . . . . . . . . . . . . . . . . . . . . . . 310
closed, file . . . . . . . . . 164


Cmd(), cmd . . . . . . . . . . . . . . . . . . . . . 417
cmp()
filecmp . . . . . . . . . . . . . . . . . . . . . . 286
. . . . . 147, 154, 171, 239
cmpfiles(), filecmp . . . . . . . . 286
co_argcount, code . . 167
co_code, code . . . . . . . . 167
co_consts, code . . . . . 167
co_filename, code . . 167
co_firstlineno, code
167
co_flags, code . . . . . . 167
co_lnotab, code . . . . . 167
co_name, code . . . . . . . . 167
co_names, code . . . . . . 167
co_nlocals, code . . . .167
co_stacksize, code . 167
co_varnames, code . . 167
code, . . . . . . . . . . 166, 203, 263
Codec(), codecs . . . . . . . . . . . . . . 234
CodeType, types . . . . . . . . . . . . . . 203
coerce(), . . . . . . . . . . 171
collect(), gc . . . . . . . . . . . . . . . . .199
commonprefix(), os.path . . . 280
compatible_formats, pickle
cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
compile()
re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
. . . . . 117, 167, 172, 173
complex, . . . . . . . 24, 131, 202
complex(), . . . . 24, 132,
160, 172
ComplexType, types . . . . . . . . . . 202
compress(), zlib . . . . . . . . . . . . 334
compressobj(), zlib . . . . . . . . 334
concat(), operator . . . . . . . . . . 205
Condition(), threading . . . . 320
ConfigParser(), ConfigParser
412
confstr(), os . . . . . . . . . . . . . . . . .279
confstr_names, os . . . . . . . . . . . 279
conjugate(), complex 133
connect(), socket . . . . . . . . . . . 310
connect_ex(), socket . . . . . . . 310
contains(), operator . . . . . . . 205
ContentHandler()
xml.sax.handler . . . . . . . . . . . 394
xml.sax . . . . . . . . . . . . . . . . . . . . . . 393
continue, . . . . . . . . . . . . . . . 39, 116
ConversionError, xdrlib . . . 382


copy()
dictionary . . . . . . . . . . . 148
shutil . . . . . . . . . . . . . . . . . . . . . . . 304
copy2(), shutil . . . . . . . . . . . . . . 304
copybinary(), mimetools . . . 374
copyfile(), shutil . . . . . . . . . . 304
copyfileobj(), shutil . . . . . . 304
copyliteral(), mimetools . .373
copymode(), shutil . . . . . . . . . . 304
copyright, sys . . . . . . . . . . . . . . . 193
copystat(), shutil . . . . . . . . . . 304
copytree(), shutil . . . . . . . . . . 304
cos()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 246
cosh()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 246
count()
list . . . . . . . . . . . . . . . 47, 146
string unicode . . . . 140
string . . . . . . . . . . . . . . . . . . . . . . . 219
countOf(), operator . . . . . . . . 206
crc32(), zlib . . . . . . . . . . . . . . . . .334
ctermid(), os . . . . . . . . . . . . . . . . .268
ctime(), time . . . . . . . . . . . . . . . . .291
cunifvariate(), random . . . . 249
curdir, os . . . . . . . . . . . . . . . . . . . . . 280
currentThread(), threading
320

D
daylight, time . . . . . . . . . . . . . . . 292
DEBUG_COLLECTABLE, gc . . . . . . 200
DEBUG_INSTANCES, gc . . . . . . . . 200
DEBUG_LEAK, gc . . . . . . . . . . . . . . . 200
DEBUG_OBJECTS, gc . . . . . . . . . . . 200
DEBUG_SAVEALL, gc . . . . . . . . . . . 200
DEBUG_STATS, gc . . . . . . . . . . . . . . 200
DEBUG_UNCOLLECTABLE, gc . . . 200
decode(), mimetools . . . . . . . . 373
decompress(), zlib . . . . . . . . . . 335
decompressobj(), zlib . . . . . . 335
def, . . . . . . . . . . . . . . . . . 40, 125, 149
DEF_MEM_LEVEL, zlib . . . . . . . . 334
defpath, os . . . . . . . . . . . . . . . . . . . 280
del, . . . . . . . . 52, 55, 115, 145, 147
delattr(), . . . . . . . . 172
delitem(), operator . . . . . . . . 206
delslice(), operator . . . . . . . 206
dgettext(), gettext . . . . . . . . 241

439
dictionary, . . . 55, 95, 147,
155, 203
DictionaryType, types . . . . . . 203
DictType, types . . . . . . . . . . . . . . 203
digits, string . . . . . . . . . . . . . . . 217
dir(), . . . . . . . . . . 63, 172
dircmp(), filecmp . . . . . . . . . . . 286
dirname(), os.path . . . . . . . . . . 281
disable(), gc . . . . . . . . . . . . . . . . .198
div(), operator . . . . . . . . . . . . . . 204
divmod(), . . . . .161, 172
dllhandle, sys . . . . . . . . . . . . . . . 193
DOTALL, re . . . . . . . . . . . . . . . . . . . . . 226
DST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
DTD . . . . . . . . . . . . . . . . . . . . . . . 384, 394, 405, 406
DTDHandler(),
xml.sax.handler . . . . . . . . . . . . . . . . . . 394
dump()
marshal . . . . . . . . . . . . . . . . . . . . . . 263
pickle cPickle . . . . . . . . . .261
dumps()
marshal . . . . . . . . . . . . . . . . . . . . . . 263
pickle cPickle . . . . . . . . . .261
dup(), os . . . . . . . . . . . . . . . . . . . . . . 271
dup2(), os . . . . . . . . . . . . . . . . . . . . . 271
DuplicateSectionError,
ConfigParser . . . . . . . . . . . . . . . . . . . . . . 413

E
e
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 247
E2BIG, errno . . . . . . . . . . . . . . . . . . 300
EACCES, errno . . . . . . . . . . . . . . . . .300
EAGAIN, errno . . . . . . . . . . . . . . . . .300
EBADF, errno . . . . . . . . . . . . . . . . . . 300
EBADMSG, errno . . . . . . . . . . . . . . . 302
EBUSY, errno . . . . . . . . . . . . . . . . . . 300
ECHILD, errno . . . . . . . . . . . . . . . . .300
EDEADLK, errno . . . . . . . . . . . . . . . 301
EDOM, errno . . . . . . . . . . . . . . . . . . . 301
EEXIST, errno . . . . . . . . . . . . . . . . .300
EFAULT, errno . . . . . . . . . . . . . . . . .300
EFBIG, errno . . . . . . . . . . . . . . . . . . 301
EILSEQ, errno . . . . . . . . . . . . . . . . .302
EINPROGRESS, errno . . . . . . . . . . 302
EINTR, errno . . . . . . . . . . . . . . . . . . 300
EINVAL, errno . . . . . . . . . . . . . . . . .301
EIO, errno . . . . . . . . . . . . . . . . . . . . . 300
EISDIR, errno . . . . . . . . . . . . . . . . .301
elif, if . . . . . . . . . . .36, 122
Ellipsis, . . . . . . . . . . . . . . . . . . . . . . . . 166

440
ellipsis, . . . . . . . . . 166, 203
EllipsisType, types . . . . . . . . 203
else
if . . . . . . . . . . . . . . . . 36, 122
try . . . . . . . . . . . . . . 78, 124
while for . . 39, 116, 122,
123
EMFILE, errno . . . . . . . . . . . . . . . . .301
EMLINK, errno . . . . . . . . . . . . . . . . .301
Empty, Queue . . . . . . . . . . . . . . . . . . 325
empty(), sched . . . . . . . . . . . . . . . 295
EMSGSIZE, errno . . . . . . . . . . . . . . 302
enable(), gc . . . . . . . . . . . . . . . . . . 198
ENAMETOOLONG, errno . . . . . . . . 301
encode()
string unicode . . . . 142
mimetools . . . . . . . . . . . . . . . . . . . 373
EncodedFile(), codecs . . . . . . 233
endswith(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
ENFILE, errno . . . . . . . . . . . . . . . . .301
ENODEV, errno . . . . . . . . . . . . . . . . .300
ENOENT, errno . . . . . . . . . . . . . . . . .300
ENOEXEC, errno . . . . . . . . . . . . . . . 300
ENOLCK, errno . . . . . . . . . . . . . . . . .302
ENOMEM, errno . . . . . . . . . . . . . . . . .300
ENOSPC, errno . . . . . . . . . . . . . . . . .301
ENOSYS, errno . . . . . . . . . . . . . . . . .302
ENOTDIR, errno . . . . . . . . . . . . . . . 301
ENOTEMPTY, errno . . . . . . . . . . . . 302
ENOTTY, errno . . . . . . . . . . . . . . . . .301
enter(), sched . . . . . . . . . . . . . . . 294
enterabs(), sched . . . . . . . . . . . 294
entitydefs, htmlentitydefs
388
EntityResolver(),
xml.sax.handler . . . . . . . . . . . . . . . . . . 394
enumerate(), threading . . . . 320
environ, os . . . . . . . . . . . . . . . . . . . 267
EnvironmentError, . . . . . . . 184
ENXIO, errno . . . . . . . . . . . . . . . . . . 300
EOFError, . . . . . . . . . . . . . 178, 183
EPERM, errno . . . . . . . . . . . . . . . . . . 300
EPIPE, errno . . . . . . . . . . . . . . . . . . 301
ERANGE, errno . . . . . . . . . . . . . . . . .301
EROFS, errno . . . . . . . . . . . . . . . . . . 301
Error
ConfigParser . . . . . . . . . . . . . . . 412
locale . . . . . . . . . . . . . . . . . . . . . . . 236
multifile . . . . . . . . . . . . . . . . . . . 376
xdrlib . . . . . . . . . . . . . . . . . . . . . . . 382
error

bsddb . . . . . . . . . . . . . . . . . . . . . . . . .331
getopt . . . . . . . . . . . . . . . . . . . . . . . 296
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
select . . . . . . . . . . . . . . . . . . . . . . . 313
socket . . . . . . . . . . . . . . . . . . . . . . . 308
struct . . . . . . . . . . . . . . . . . . . . . . . 264
thread . . . . . . . . . . . . . . . . . . . . . . . 318
xml.parsers.expat . . . . . . . . 389
zipfile . . . . . . . . . . . . . . . . . . . . . . 337
zlib . . . . . . . . . . . . . . . . . . . . . . . . . . 334
anydbm, dumbdbm, dbhash, dbm
gdbm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
errorcode, errno . . . . . . . . . . . . 299
ErrorHandler()
xml.sax.handler . . . . . . . . . . . 394
xml.sax . . . . . . . . . . . . . . . . . . . . . . 393
errors, xml.parsers.expat 389
ErrorString(),
xml.parsers.expat . . . . . . . . . . . . . . . 388
escape()
cgi . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
xml.sax.saxutils . . . . . . . . . .398
ESPIPE, errno . . . . . . . . . . . . . . . . .301
ESRCH, errno . . . . . . . . . . . . . . . . . . 300
ETIMEDOUT, errno . . . . . . . . . . . . 302
ETXTBSY, errno . . . . . . . . . . . . . . . 301
eval(), . . 117, 119, 130,
167, 172
Event(), threading . . . . . . . . . . 320
exc_info, sys . . . . . . . . . . . .124, 193
exc_info(), sys . . . . . . . . . . . . . . 169
exc_traceback, sys . . . . . 125, 193
exc_type, sys . . . . . . . . . . . .125, 193
exc_value, sys . . . . . . . . . . 125, 193
except, try . . . 21, 77, 93,
124, 182
Exception, . . . . . . . . . . . . . 93, 182
EXDEV, errno . . . . . . . . . . . . . . . . . . 300
exec, . . . . . . . . . 117, 119, 130, 167
exec_prefix, sys . . . . . . . . . . . . 193
execfile(), . 117, 130,
173
execl(), os . . . . . . . . . . . . . . . . . . . 276
execle(), os . . . . . . . . . . . . . . . . . . 276
execlp(), os . . . . . . . . . . . . . . . . . . 276
executable, sys . . . . . . . . . . . . . . 194
execv(), os . . . . . . . . . . . . . . . . . . . 276
execve(), os . . . . . . . . . . . . . . . . . . 276
execvp(), os . . . . . . . . . . . . . . . . . . 276
execvpe(), os . . . . . . . . . . . . . . . . .277


exists(), os.path . . . . . . . . . . . 281
exit()
sys . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
thread . . . . . . . . . . . . . . . . . . . . . . . 318
exit_thread(), thread . . . . . . 318
exitfunc, sys . . . . . . . . . . . . . . . . .194
exp()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 246
expandtabs()
string unicode . . . . 141
string . . . . . . . . . . . . . . . . . . . . . . . 219
expanduser(), os.path . . . . . . 281
expandvars(), os.path . . . . . . 281
expovariate(), random . . . . . . 249
extend(), list . . . . . . . . 146
extract_stack(), traceback
209
extract_tb(), traceback . . . 209

F
f_back, frame . . . . . . . . 168
F_BAVAIL, statvfs . . . . . . . . . . . 285
F_BFREE, statvfs . . . . . . . . . . . . 285
F_BLOCKS, statvfs . . . . . . . . . . . 285
F_BSIZE, statvfs . . . . . . . . . . . . 285
f_builtins, frame . . 168
f_code, frame . . . . . . . . 168
f_exc_traceback, frame
169
f_exc_type, frame . . 169
f_exc_value, frame . 169
F_FAVAIL, statvfs . . . . . . . . . . . 286
F_FFREE, statvfs . . . . . . . . . . . . 286
F_FILES, statvfs . . . . . . . . . . . . 285
F_FLAG, statvfs . . . . . . . . . . . . . . 286
F_FRSIZE, statvfs . . . . . . . . . . . 285
f_globals, frame . . . .168
f_lasti, frame . . . . . . 168
f_lineno, frame . . . . . 168
f_locals, frame . . . . . 168
F_NAMEMAX, statvfs . . . . . . . . . . 286
F_OK, os . . . . . . . . . . . . . . . . . . . . . . . 273
f_restricted, frame 168
f_trace, frame . . . . . . 169
fabs(), math . . . . . . . . . . . . . . . . . . 246
FancyURLopener(), urllib . .366
fdopen(), os . . . . . . . . . . . . . . . . . . 269
feature_*, xml.sax.handler
394

441
FieldStorage(), cgi . . . . . . . . 356
FIFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48, 325
file, . . . . . . 72, 163, 203, 311
FileInput(), fileinput . . . . 410
filelineno(), fileinput . . . 410
filename(), fileinput . . . . . . 410
fileno()
file . . . . . . . . . . . . . . . . . . . 163
socket . . . . . . . . . . . . . . . . . . . . . . . 311
FileType, types . . . . . . . . . . . . . . 203
filter(), . . . . . . 49, 173
finally, try 80, 124, 186
find()
string unicode . . . . 141
gettext . . . . . . . . . . . . . . . . . . . . . . 241
string . . . . . . . . . . . . . . . . . . . . . . . 219
find_module(), imp . . . . . . . . . . 211
findall(), re . . . . . . . . . . . . . . . . .227
firstweekday(), calendar . .419
float, . . . . .24, 131, 132, 202
float(), . 25, 132, 160,
173
FloatingPointError, . . . . . 183
FloatType, types . . . . . . . . . . . . 202
floor(), math . . . . . . . . . . . . . . . . .246
flush(), file . . . . . . . . . . 163
fmod(), math . . . . . . . . . . . . . . . . . . 246
fnmatch(), fnmatch . . . . . . . . . . 303
fnmatchcase(), fnmatch . . . . 303
for
. . . . . . . . . . . . . . . . . 36, 39, 116, 123
. . . . . . . . . . . . . . . . . . 51
fork(), os . . . . . . . . . . . . . . . . . . . . . 277
forkpty(), os . . . . . . . . . . . . . . . . .277
format(), locale . . . . . . . . . . . . 239
format_exception(),
traceback . . . . . . . . . . . . . . . . . . . . . . . . . . 209
format_exception_only(),
traceback . . . . . . . . . . . . . . . . . . . . . . . . . . 209
format_list(), traceback . .209
format_stack(), traceback 210
format_tb(), traceback . . . . 210
format_version, pickle
cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
formatdate(), rfc822 . . . . . . . 370
fpathconf(), os . . . . . . . . . . . . . . 271
frame, . . . . . . . . . . . . . 168, 204
FrameType, types . . . . . . . . . . . . 204
frexp(), math . . . . . . . . . . . . . . . . .246
FRIDAY, calendar . . . . . . . . . . . . 419
from, import . . . . . .59, 65, 118

442
fromfd(), socket . . . . . . . . . . . . 309
fstat(), os . . . . . . . . . . . . . . . . . . . 271
fstatvfs(), os . . . . . . . . . . . . . . . 271
ftruncate(), os . . . . . . . . . . . . . . 271
Full, Queue . . . . . . . . . . . . . . . . . . . 326
func_code, function
149, 167
func_defaults,
function . . . . . . . . . . . . . . . . . . . . . . . . . . . .149
func_doc, function . 149
func_globals, function
149, 350
func_name, function 149
function, 125, 149, 152, 203
FunctionType, types . . . . . . . . 203

G
gamma(), random . . . . . . . . . . . . . . 249
garbage, gc . . . . . . . . . . . . . . . . . . . 199
gauss(), random . . . . . . . . . . . . . . 249
get(), dictionary . . . . 148
get_debug(), gc . . . . . . . . . . . . . . 199
get_ident(), thread . . . . . . . . 319
get_magic(), imp . . . . . . . . . . . . 211
get_suffixes(), imp . . . . . . . . 211
get_threshold(), gc . . . . . . . . 199
getatime(), os.path . . . . . . . . 281
getattr(), . . . . . . . . 173
getcwd(), os . . . . . . . . . . . . . . . . . . 273
getdefaultencoding(), sys 194
getdefaultlocale(), locale
238
getegid(), os . . . . . . . . . . . . . . . . .268
geteuid(), os . . . . . . . . . . . . . . . . .268
getfqdn(), socket . . . . . . . . . . . 308
getgid(), os . . . . . . . . . . . . . . . . . . 268
getgroups(), os . . . . . . . . . . . . . . 268
gethostbyaddr(), socket . . . 309
gethostbyname(), socket . . . 308
gethostbyname_ex(), socket
308
gethostname(), socket . . . . . . 309
getitem(), operator . . . . . . . . 206
getlocale(), locale . . . . . . . . 238
getlogin(), os . . . . . . . . . . . . . . . 268
getmtime(), os.path . . . . . . . . 281
getopt(), getopt . . . . . . . . . . . . 296
GetoptError, getopt . . . . . . . . 296
getpass(), getpass . . . . . . . . . . 296
getpeername(), socket . . . . . . 311
getpgrp(), os . . . . . . . . . . . . . . . . .268


getpid(), os . . . . . . . . . . . . . . . . . . 268
getppid(), os . . . . . . . . . . . . . . . . .268
getprotobyname(), socket . .309
getrecursionlimit(), sys . .194
getrefcount(), sys . . . . . . . . . . 194
getservbyname(), socket . . . 309
getsignal(), signal . . . . . . . . 306
getsize(), os.path . . . . . . . . . . 281
getslice(), operator . . . . . . . 206
getsockname(), socket . . . . . . 311
getsockopt(), socket . . . . . . . 311
gettempprefix(), tempfile 299
gettext(), gettext . . . . . . . . . . 241
getuid(), os . . . . . . . . . . . . . . . . . . 268
getuser(), getpass . . . . . . . . . . 296
glob(), glob . . . . . . . . . . . . . . . . . . 302
global, . . 40, 105, 117, 119, 128,
185
globals(), . . . 119, 174
GMT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
gmtime(), time . . . . . . . . . . . . . . . 292
GNUTranslations(), gettext
243
GzipFile(), gzip . . . . . . . . . . . . 336

H
has_key(), dictionary 55,
148
hasattr(), . . . . . . . . 174
hash(), . . . . . . . 155, 174
hashopen(), bsddb . . . . . . . . . . . 331
hex(), . . . . . . . . . 159, 174
hexdigits, string . . . . . . . . . . . 217
hexversion, sys . . . . . . . . . . . . . . 194
HotProfile(), profile . . . . . . 347
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
HTMLParser(), htmllib . . . . . . 387
htonl(), socket . . . . . . . . . . . . . . 310
htons(), socket . . . . . . . . . . . . . . 310
hypot(), math . . . . . . . . . . . . . . . . .246

I
I, re . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
id(), . . . . . . . . . . . . . . . 174
if
. . . . . . . . . . . . . . . . . . . . . 36, 110, 122
. . . . . . . . . . . . . . . . . . 52
IGNORECASE, re . . . . . . . . . . . . . . . 226
im_class, instance
method . . . . . . . . . . . . . . . . . . . . . . . . . 150, 152
im_func, instance
method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150


im_self, instance
method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
imag, complex . . . . . . . . 133
import, . . . . 59, 65, 117, 170, 211
ImportError, 65, 184, 211, 212
in, . . . . . . . . . . . 56, 110, 135, 159, 205
INADDR_*, socket . . . . . . . . . . . . 308
IncrementalParser(),
xml.sax.xmlreader . . . . . . . . . . . . . . . 399
index()
list . . . . . . . . . . . . . . . 47, 146
string unicode . . . . 141
string . . . . . . . . . . . . . . . . . . . . . . . 219
IndexError, . . 29, 94, 123, 135,
185
indexOf(), operator . . . . . . . . 206
inet_aton(), socket . . . . . . . . 310
inet_ntoa(), socket . . . . . . . . 310
input()
fileinput . . . . . . . . . . . . . . . . . . . 409
. . . . . . . . . . 129, 174, 197
InputSource()
xml.sax.xmlreader . . . . . . . . 399
xml.sax . . . . . . . . . . . . . . . . . . . . . . 393
InputType, cStringIO . . . . . . . 232
insert(), list . . . . . 47, 146
insort(), bisect . . . . . . . . . . . . 251
install(), gettext . . . . . . . . . . 242
instance, 86, 151, 152, 203
instance method, . 87, 149
InstanceType, types . . . . . . . . 203
int, . . . . . . . 23, 131, 132, 202
int(), 25, 132, 160, 174
intern(), . . . . . . . . . . 175
Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
InterpolationDepthError,
ConfigParser . . . . . . . . . . . . . . . . . . . . . . 413
InterpolationError,
ConfigParser . . . . . . . . . . . . . . . . . . . . . . 413
IntType, types . . . . . . . . . . . . . . . 202
inv(), operator . . . . . . . . . . . . . . 205
invert(), operator . . . . . . . . . . 205
IOError, . . . . . . . . . . . . . . . 163, 184
IP_*, socket . . . . . . . . . . . . . . . . . . 308
IPPORT_*, socket . . . . . . . . . . . . 308
IPPROTO_*, socket . . . . . . . . . . . 308
is, . . . . . . . . . . . . . . . . . . . . . . . . . . 56, 109
is not, . . . . . . . . . . . . . . . . . . . . 56, 110
is_zipfile(), zipfile . . . . . . 337
isabs(), os.path . . . . . . . . . . . . 281
isatty()

443
file . . . . . . . . . . . . . . . . . . . 163
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
isCallable(), operator . . . . 206
isdecimal(), unicode 144
isdigit(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
isdir(), os.path . . . . . . . . . . . . 281
isenabled(), gc . . . . . . . . . . . . . . 199
isfile(), os.path . . . . . . . . . . . 281
isfirstline(), fileinput . .410
isinstance(), . . . . 175
isleap(), calendar . . . . . . . . . . 419
islink(), os.path . . . . . . . . . . . 281
islower(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
isMappingType(), operator 206
ismount(), os.path . . . . . . . . . . 282
isNumberType(), operator . .207
isnumeric(), unicode 144
isreadable(), pprint . . . . . . . 214
isrecursive(), pprint . . . . . . 214
isSequenceType(), operator
207
isspace(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
isstdin(), fileinput . . . . . . . 410
issubclass(), . . . . 175
istitle(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
isupper(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
items(), dictionary . . 148

J
join()
string unicode . . . . 142
os.path . . . . . . . . . . . . . . . . . . . . . . 282
string . . . . . . . . . . . . . . . . . . . . . . . 219
joinfields(), string . . . . . . . 219

K
KeyboardInterrupt, . . . 21, 77,
184
KeyError, . . . . .55, 147, 157, 185
keys(), dictionary 55, 148
kill(), os . . . . . . . . . . . . . . . . . . . . . 277

L
L, re . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
lambda, . . . . . . . . . . . . . . . 45, 111, 149
LambdaType, types . . . . . . . . . . . 203
LANG, . . . . . . . 240, 242
LANGUAGE, . . 240, 242

444
last_traceback, sys . . . 169, 195
last_type, sys . . . . . . . . . . . . . . . 195
last_value, sys . . . . . . . . . . . . . . 195
LC_ALL
. . . . . . . . . . . . 240, 242
locale . . . . . . . . . . . . . . . . . . . . . . . 240
LC_COLLATE, locale . . . . . . . . . . 239
LC_CTYPE, locale . . . . . . . . . . . . 239
LC_MESSAGES
. . . . . . . . . . . . 240, 242
locale . . . . . . . . . . . . . . . . . . . . . . . 240
LC_MONETARY, locale . . . . . . . . 240
LC_NUMERIC, locale . . . . . . . . . . 240
LC_TIME, locale . . . . . . . . . . . . . . 239
ldexp(), math . . . . . . . . . . . . . . . . .246
leapdays(), calendar . . . . . . . 420
len(), . .30, 33, 38, 135,
147, 157, 175
letters, string . . . . . . . . . . . . . . 217
LIFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
lineno(), fileinput . . . . . . . . 410
linesep, os . . . . . . . . . . . . . . . . . . . 280
link(), os . . . . . . . . . . . . . . . . . . . . . 273
list, . . . . 32, 47, 48, 51, 135,
145, 202
list(), . . . . . . . . . . . . 175
listdir(), os . . . . . . . . . . . . . . . . .274
listen(), socket . . . . . . . . . . . . 311
ListType, types . . . . . . . . . . . . . . 202
little-endian . . . . . . . . . . . . . . . . . . . . . . . . . . 193, 235
ljust()
string unicode . . . . 140
string . . . . . . . . . . . . . . . . . . . . . . . 220
load()
marshal . . . . . . . . . . . . . . . . . . . . . . 263
pickle cPickle . . . . . . . . . .261
load_module(), imp . . . . . . . . . . 211
loads()
marshal . . . . . . . . . . . . . . . . . . . . . . 263
pickle cPickle . . . . . . . . . .261
LOCALE, re . . . . . . . . . . . . . . . . . . . . . 226
localeconv(), locale . . . . . . . 237
locals(), . . . . .119, 175
localtime(), time . . . . . . . . . . . 292
Locator(), xml.sax.xmlreader
399
Lock(), threading . . . . . . . . . . . 320
LockType, thread . . . . . . . . . . . . 318
log()
cgi . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248


math . . . . . . . . . . . . . . . . . . . . . . . . . . 246
log10()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 246
logfile, cgi . . . . . . . . . . . . . . . . . . 361
logfp, cgi . . . . . . . . . . . . . . . . . . . . . 361
lognormvariate(), random . .249
long int, . . . . 131, 132, 202
long(), . . . 25, 132, 160,
176
LongType, types . . . . . . . . . . . . . . 202
lookup(), codecs . . . . . . . . . . . . 233
LookupError, . . . . . . . . . . . . . . 184
lower()
string unicode . . . . 143
string . . . . . . . . . . . . . . . . . . . . . . . 219
lowercase, string . . . . . . . . . . . 217
lseek(), os . . . . . . . . . . . . . . . . . . . 271
lshift(), operator . . . . . . . . . . 205
lstat(), os . . . . . . . . . . . . . . . . . . . 274
lstrip()
string unicode . . . . 141
string . . . . . . . . . . . . . . . . . . . . . . . 219
lvalue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

M
M, re . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
make_parser(), xml.sax . . . . 392
makedirs(), os . . . . . . . . . . . . . . . 274
makefile(), socket . . . . . . . . . . 311
maketrans(), string . . . . . . . . 218
map(), . . . . . 49, 176, 207
MAP_PRIVATE, mmap . . . . . . . . . . . 316
MAP_SHARED, mmap . . . . . . . . . . . . 315
match(), re . . . . . . . . . . . . . . . . . . . 227
max(), . . . . . . . . . . . . . . 176
MAX_INTERPOLATION_DEPTH,
ConfigParser . . . . . . . . . . . . . . . . . . . . . . 412
maxint, sys . . . . . . . . . . . . . . . . . . . 195
MemoryError, . . . . . . . . . . . . . . 185
Message()
mimetools . . . . . . . . . . . . . . . . . . . 373
rfc822 . . . . . . . . . . . . . . . . . . . . . . . 369
method, . . . . . . . . . . . . . . . . . 203
MethodType, types . . . . . . . . . . . 203
MIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373, 374
MimeWriter(), MimeWriter . .375
min(), . . . . . . . . . . . . . . 176
MiniFieldStorage, cgi . . . . . . 357
MissingSectionHeaderError,
ConfigParser . . . . . . . . . . . . . . . . . . . . . . 413
mkdir(), os . . . . . . . . . . . . . . . . . . . 274


mkfifo(), os . . . . . . . . . . . . . . . . . . 274
mktemp(), tempfile . . . . . . . . . . 298
mktime(), time . . . . . . . . . . . . . . . 292
mktime_tz(), rfc822 . . . . . . . . 370
mmap(), mmap . . . . . . . . . . . . . . . . . . 315
mod(), operator . . . . . . . . . . . . . . 204
mode, file . . . . . . . . . . . . 164
modf(), math . . . . . . . . . . . . . . . . . . 246
module, . . . . . . . . . . . . 151, 203
modules, sys . . . . . . . . . . . . . 118, 195
ModuleType, types . . . . . . . . . . . 203
MONDAY, calendar . . . . . . . . . . . . 419
month(), calendar . . . . . . . . . . . 420
monthcalendar(), calendar 420
monthrange(), calendar . . . . 420
MSG_*, socket . . . . . . . . . . . . . . . . .308
mul(), operator . . . . . . . . . . . . . . 204
MultiFile(), multifile . . . . 376
MULTILINE, re . . . . . . . . . . . . . . . . .226
MutableString(), UserString
256

N
name
file . . . . . . . . . . . . . . . . . 165
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
NameError, . . . . 53, 77, 105, 123,
129, 185
neg(), operator . . . . . . . . . . . . . . 204
new_module(), imp . . . . . . . . . . . 212
nextfile(), fileinput . . . . . . 410
nice(), os . . . . . . . . . . . . . . . . . . . . . 277
None
. . . . . . . . . . . . . . . . . . . . . . 41, 43, 110, 165
. . . . . . . . . . . . . . . . . . . . 165, 202
NoneType, types . . . . . . . . . . . . . . 202
NoOptionError, ConfigParser
413
normalize(), locale . . . . . . . . 238
normalvariate(), random . . . 249
normcase(), os.path . . . . . . . . 282
normpath(), os.path . . . . . . . . 282
NoSectionError, ConfigParser
412
not, . . . . . . . . . . . . . . . . . . . 56, 111, 205
not in, . . . . . . . . . . 56, 110, 135, 159
not_(), operator . . . . . . . . . . . . 205
NotImplementedError, . . . 185
NSIG, signal . . . . . . . . . . . . . . . . . . 306
ntohl(), socket . . . . . . . . . . . . . . 309
ntohs(), socket . . . . . . . . . . . . . . 309

445
NullTranslations(), gettext
242

O
O_APPEND, os . . . . . . . . . . . . . . . . . . 272
O_BINARY, os . . . . . . . . . . . . . . . . . . 273
O_CREAT, os . . . . . . . . . . . . . . . . . . . 272
O_DSYNC, os . . . . . . . . . . . . . . . . . . . 272
O_EXCL, os . . . . . . . . . . . . . . . . . . . . . 272
O_NDELAY, os . . . . . . . . . . . . . . . . . . 272
O_NOCTTY, os . . . . . . . . . . . . . . . . . . 273
O_NONBLOCK, os . . . . . . . . . . . . . . . 272
O_RDONLY, os . . . . . . . . . . . . . . . . . . 272
O_RDWR, os . . . . . . . . . . . . . . . . . . . . . 272
O_RSYNC, os . . . . . . . . . . . . . . . . . . . 272
O_SYNC, os . . . . . . . . . . . . . . . . . . . . . 272
O_TEXT, os . . . . . . . . . . . . . . . . . . . . . 273
O_TRUNC, os . . . . . . . . . . . . . . . . . . . 272
O_WRONLY, os . . . . . . . . . . . . . . . . . . 272
oct(), . . . . . . . . . 159, 176
octdigits, string . . . . . . . . . . . 217
open()
codecs . . . . . . . . . . . . . . . . . . . . . . . 233
gzip . . . . . . . . . . . . . . . . . . . . . . . . . . 336
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
shelve . . . . . . . . . . . . . . . . . . . . . . . 262
urllib . . . . . . . . . . . . . . . . . . . . . . . 366
anydbm, dumbdbm, dbhash, dbm
gdbm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
. . . . . . . . . . . 72, 163, 176
open_unknown(), urllib . . . . 366
openpty(), os . . . . . . . . . . . . . . . . .271
or, . . . . . . . . . . . . . . . . . . . . . . . . . . 56, 111
or_(), operator . . . . . . . . . . . . . . 205
ord(), . . . . . . . . . . . . . . 177
OSError, . . . . . . . . . . . . . . . 184, 267
OutputType, cStringIO . . . . . . 232
OverflowError, . .174, 183, 292

P
P_DETACH, os . . . . . . . . . . . . . . . . . . 277
P_NOWAIT, os . . . . . . . . . . . . . . . . . . 277
P_NOWAITO, os . . . . . . . . . . . . . . . . .277
P_OVERLAY, os . . . . . . . . . . . . . . . . .277
P_WAIT, os . . . . . . . . . . . . . . . . . . . . . 277
pack(), struct . . . . . . . . . . . . . . . 264
Packer(), xdrlib . . . . . . . . . . . . 379
pardir, os . . . . . . . . . . . . . . . . . . . . . 280
paretovariate(), random . . . 249
parse()

446
cgi . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
xml.sax . . . . . . . . . . . . . . . . . . . . . . 392
parse_header(), cgi . . . . . . . . 360
parse_multipart(), cgi . . . . 360
parse_qs(), cgi . . . . . . . . . . . . . . 360
parse_qsl(), cgi . . . . . . . . . . . . 360
parsedate(), rfc822 . . . . . . . . 370
parsedate_tz(), rfc822 . . . . 370
ParserCreate(),
xml.parsers.expat . . . . . . . . . . . . . . . 388
parseString(), xml.sax . . . . 393
ParsingError, ConfigParser
413
pass, . . . . . . . . . . . . . . . . . . . . 39, 115
path
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
sys . . . . . . . . . . . . . . . . . . . . . . 119, 195
pathconf(), os . . . . . . . . . . . . . . . 274
pathconf_names, os . . . . . . . . . . 274
pathsep, os . . . . . . . . . . . . . . . . . . . 280
pause(), signal . . . . . . . . . . . . . . 306
Pdb(), pdb . . . . . . . . . . . . . . . . . . . . . 340
pformat(), pprint . . . . . . . . . . . 214
PI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390, 407
pi
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 247
PickleError, pickle
cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Pickler(), pickle cPickle
260
PicklingError, pickle
cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
pipe(), os . . . . . . . . . . . . . . . . . . . . . 272
PKG_DIRECTORY, imp . . . . . . . . . . 212
platform, sys . . . . . . . . . . . . . . . . .196
plock(), os . . . . . . . . . . . . . . . . . . . 277
pm(), pdb . . . . . . . . . . . . . . . . . . . . . . 342
poll(), select . . . . . . . . . . . . . . . 314
POLLERR, select . . . . . . . . . . . . . . 315
POLLHUP, select . . . . . . . . . . . . . . 315
POLLIN, select . . . . . . . . . . . . . . . 314
POLLNVAL, select . . . . . . . . . . . . 315
POLLOUT, select . . . . . . . . . . . . . . 315
POLLPRI, select . . . . . . . . . . . . . . 314
pop(), list . . . . . . . . . 48, 146
popen(), os . . . . . . . . . . . . . . . . . . . 270
popen2()
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
popen2 . . . . . . . . . . . . . . . . . . . . . . . 288
Popen3(), popen2 . . . . . . . . . . . . 288


popen3()
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
popen2 . . . . . . . . . . . . . . . . . . . . . . . 288
Popen4(), popen2 . . . . . . . . . . . . 289
popen4()
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
popen2 . . . . . . . . . . . . . . . . . . . . . . . 288
pos(), operator . . . . . . . . . . . . . . 204
post_mortem(), pdb . . . . . . . . . . 342
pow()
math . . . . . . . . . . . . . . . . . . . . . . . . . . 246
. . . . . . . . . . . . . . . 161, 177
pprint(), pprint . . . . . . . . . . . . 214
prcal(), calendar . . . . . . . . . . . 420
prefix, sys . . . . . . . . . . . . . . . . . . . 196
prepare_input_source(),
xml.sax.saxutils . . . . . . . . . . . . . . . . . 398
PrettyPrinter(), pprint . . . 213
print, . . . . . . 27, 35, 68, 115, 159
print_directory(), cgi . . . . 360
print_environ(), cgi . . . . . . . 360
print_environ_usage(), cgi
360
print_exc(), traceback . . . . 208
print_exception(), traceback
208
print_form(), cgi . . . . . . . . . . . 360
print_last(), traceback . . . 208
print_stack(), traceback . .209
print_tb(), traceback . . . . . . 208
printable, string . . . . . . . . . . . 218
prmonth(), calendar . . . . . . . . 420
Profile(), profile . . . . . . . . . . 347
property_*, xml.sax.handler
394
PROT_READ, mmap . . . . . . . . . . . . . . 316
PROT_WRITE, mmap . . . . . . . . . . . . 316
ps1, sys . . . . . . . . . . . . . . . . . . . . . . . 196
ps2, sys . . . . . . . . . . . . . . . . . . . . . . . 196
punctuation, string . . . . . . . . 217
putenv(), os . . . . . . . . . . . . . . . . . . 268
PY_COMPILED, imp . . . . . . . . . . . . 212
PY_FROZEN, imp . . . . . . . . . . . . . . . 212
PY_RESOURCE, imp . . . . . . . . . . . . 212
PY_SOURCE, imp . . . . . . . . . . . . . . . 212
PYTHONDEBUG, . . . 426
PYTHONHOME, . . . . 427
PYTHONINSPECT, 426
PYTHONOPTIMIZE,
61, 427


PYTHONPATH, . 61, 62,
119, 196, 427
PYTHONSTARTUP, 21,
191, 427
PYTHONUNBUFFERED,
427
PYTHONVERBOSE, 427
PYTHONY2K, 290, 291
PyZipFile(), zipfile . . . . . . . 337

Q
Queue(), Queue . . . . . . . . . . . . . . . 325
quote(), urllib . . . . . . . . . . . . . . 364
quote_plus(), urllib . . . . . . . 364

R
R_OK, os . . . . . . . . . . . . . . . . . . . . . . . 273
raise, . . . . . . . . . . . . . . . . . . . 92, 120
randint()
random . . . . . . . . . . . . . . . . . . . . . . . 250
whrandom . . . . . . . . . . . . . . . 250, 251
random()
random . . . . . . . . . . . . . . . . . . . . . . . 250
whrandom . . . . . . . . . . . . . . . 250, 251
randrange()
random . . . . . . . . . . . . . . . . . . . . . . . 250
whrandom . . . . . . . . . . . . . . . 250, 251
range(), . . . . . . . 37, 177
raw_input(), 178, 197
read()
file . . . . . . . . . . . . . . . 73, 163
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
readline(), file . . 73, 163
readlines(), file .73, 164
readlink(), os . . . . . . . . . . . . . . . 274
real, complex . . . . . . . . 133
recv(), socket . . . . . . . . . . . . . . . 311
recvfrom(), socket . . . . . . . . . . 311
reduce(), . 51, 178, 207
register()
codecs . . . . . . . . . . . . . . . . . . . . . . . 233
select . . . . . . . . . . . . . . . . . . . . . . . 314
reload(), 179, 195, 211
remove()
list . . . . . . . . . . . . . . . 47, 146
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
removedirs(), os . . . . . . . . . . . . 274
rename(), os . . . . . . . . . . . . . . . . . . 275
renames(), os . . . . . . . . . . . . . . . . .275
repeat(), operator . . . . . . . . . . 205
replace()
string unicode . . . . 141

447
string . . . . . . . . . . . . . . . . . . . . . . . 220
Repr(), repr . . . . . . . . . . . . . . . . . . 215
repr()
repr . . . . . . . . . . . . . . . . . . . . . . . . . . 215
. . . . . . . . . . . 68, 159, 179
resetlocale(), locale . . . . . . 238
retrieve(), urllib . . . . . . . . . . 366
return, . . . . . . . . . . . . . . . . . . . . . 117
reverse(), list . . . 48, 146
RExec(), rexec . . . . . . . . . . . . . . . 351
rfind()
string unicode . . . . 141
string . . . . . . . . . . . . . . . . . . . . . . . 219
RHooks(), rexec . . . . . . . . . . . . . . 351
rindex()
string unicode . . . . 141
string . . . . . . . . . . . . . . . . . . . . . . . 219
rjust()
string unicode . . . . 140
string . . . . . . . . . . . . . . . . . . . . . . . 220
RLock(), threading . . . . . . . . . . 320
rmdir(), os . . . . . . . . . . . . . . . . . . . 275
rmtree(), shutil . . . . . . . . . . . . 305
rnopen(), bsddb . . . . . . . . . . . . . . 331
round(), . . . . . . . . . . . 179
rstrip()
string unicode . . . . 141
string . . . . . . . . . . . . . . . . . . . . . . . 219
run()
pdb . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
profile . . . . . . . . . . . . . . . . . . . . . . 347
sched . . . . . . . . . . . . . . . . . . . . . . . . .295
runcall(), pdb . . . . . . . . . . . . . . . 341
runeval(), pdb . . . . . . . . . . . . . . . 341
RuntimeError, . . . . . . . . . . . . . 185

S
S, re . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
S_IFMT(), stat . . . . . . . . . . . . . . . 284
S_IMODE(), stat . . . . . . . . . . . . . . 284
S_ISBLK(), stat . . . . . . . . . . . . . . 283
S_ISCHR(), stat . . . . . . . . . . . . . . 283
S_ISDIR(), stat . . . . . . . . . . . . . . 283
S_ISFIFO(), stat . . . . . . . . . . . . 283
S_ISLNK(), stat . . . . . . . . . . . . . . 284
S_ISREG(), stat . . . . . . . . . . . . . . 283
S_ISSOCK(), stat . . . . . . . . . . . . 284
saferepr(), pprint . . . . . . . . . . 214
samefile(), os.path . . . . . . . . 282
sameopenfile(), os.path . . . 282
samestat(), os.path . . . . . . . . 282

448
SATURDAY, calendar . . . . . . . . . . 419
SAXException, xml.sax . . . . . . 393
SAXNotRecognizedException,
xml.sax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
SAXNotSupportedException,
xml.sax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
SAXParseException, xml.sax
393
SAXReaderNotAvailable,
xml.sax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
scheduler(), sched . . . . . . . . . . 294
search(), re . . . . . . . . . . . . . . . . . . 227
seed()
random . . . . . . . . . . . . . . . . . . . . . . . 250
whrandom . . . . . . . . . . . . . . . 250, 251
seek(), file . . . . . . 164, 177
select(), select . . . . . . . . . . . . 313
Semaphore(), threading . . . . 320
send(), socket . . . . . . . . . . . . . . . 312
sendto(), socket . . . . . . . . . . . . 312
sep, os . . . . . . . . . . . . . . . . . . . . . . . . . 280
sequenceIncludes(), operator
205
set_debug(), gc . . . . . . . . . . . . . . 199
set_threshold(), gc . . . . . . . . 199
set_trace(), pdb . . . . . . . . . . . . 342
setattr(), . . . . . . . . 180
setblocking(), socket . . . . . . 312
setcheckinterval(), sys . . . 196
setdefault(),
dictionary . . . . . . . . . . . . . . . . . . . . . . . . . 148
setdefaultencoding(), sys 196
setegid(), os . . . . . . . . . . . . . . . . .268
seteuid(), os . . . . . . . . . . . . . . . . .268
setfirstweekday(), calendar
419
setgid(), os . . . . . . . . . . . . . . . . . . 268
setitem(), operator . . . . . . . . 206
setlocale(), locale . . . . . . . . 236
setpgid(), os . . . . . . . . . . . . . . . . .269
setpgrp(), os . . . . . . . . . . . . . . . . .269
setprofile(), sys . . . . . . . . . . . 196
setrecursionlimit(), sys . .197
setregid(), os . . . . . . . . . . . . . . . 269
setreuid(), os . . . . . . . . . . . . . . . 269
setsid(), os . . . . . . . . . . . . . . . . . . 269
setslice(), operator . . . . . . . 206
setsockopt(), socket . . . . . . . 312
settrace(), sys . . . . . . . . . . . . . . 197
setuid(), os . . . . . . . . . . . . . . . . . . 269
SGML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
SGMLParser(), sgmllib . . . . . . 383


shlex(), shlex . . . . . . . . . . . . . . . 415
shutdown(), socket . . . . . . . . . . 312
SIG*, signal . . . . . . . . . . . . . . . . . . 306
SIG_DFL, signal . . . . . . . . . . . . . . 306
SIG_IGN, signal . . . . . . . . . . . . . . 306
signal(), signal . . . . . . . 184, 306
sin()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 246
sinh()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 247
sleep(), time . . . . . . . . . . . . . . . . .292
slice, . . . . . . . . . . . . . 166, 203
slice(), . . . . . . 166, 180
SliceType, types . . . . . . . . . . . . 203
SO_*, socket . . . . . . . . . . . . . . . . . . 308
SOCK_DGRAM, socket . . . . . . . . . . 308
SOCK_RAW, socket . . . . . . . . . . . . 308
SOCK_RDM, socket . . . . . . . . . . . . 308
SOCK_SEQPACKET, socket . . . . 308
SOCK_STREAM, socket . . . . . . . . 308
socket(), socket . . . . . . . . . . . . 309
SocketType, socket . . . . . . . . . . 310
softspace, file . . . . 115,
116, 165
SOL_*, socket . . . . . . . . . . . . . . . . .308
SOMAXCONN, socket . . . . . . . . . . . 308
sort(), list . . . .48, 55, 147
spawnv(), os . . . . . . . . . . . . . . . . . . 277
spawnve(), os . . . . . . . . . . . . . . . . .277
split()
string unicode . . . . 142
os.path . . . . . . . . . . . . . . . . . . . . . . 282
re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
string . . . . . . . . . . . . . . . . . . . . . . . 219
splitdrive(), os.path . . . . . . 283
splitext(), os.path . . . . . . . . 283
splitfields(), string . . . . . . 219
splitlines(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
sqrt()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 247
ST_ATIME, stat . . . . . . . . . . . . . . . 284
ST_CTIME, stat . . . . . . . . . . . . . . . 285
ST_DEV, stat . . . . . . . . . . . . . . . . . . 284
ST_GID, stat . . . . . . . . . . . . . . . . . . 284
ST_INO, stat . . . . . . . . . . . . . . . . . . 284
ST_MODE, stat . . . . . . . . . . . . . . . . .284


ST_MTIME, stat . . . . . . . . . . . . . . . 284
ST_NLINK, stat . . . . . . . . . . . . . . . 284
ST_SIZE, stat . . . . . . . . . . . . . . . . .284
ST_UID, stat . . . . . . . . . . . . . . . . . . 284
StandardError, . . . . . . . . . . . .183
start, slice . . . . . . . . . 166
start_new_thread(), thread
318
startfile(), os . . . . . . . . . . . . . . 278
startswith(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
stat(), os . . . . . . . . . . . . . . . . . . . . . 275
Stats(), pstats . . . . . . . . . . . . . . 348
statvfs(), os . . . . . . . . . . . . . . . . .275
stderr, sys . . . . . . . . . . . . . . 163, 197
stdin, sys . . . . . . . . . . . . . . . . 163, 197
stdout, sys . . . . . . . . . . . . . . 163, 197
step, slice . . . . . . . . . . 166
stop, slice . . . . . . . . . . 166
str()
locale . . . . . . . . . . . . . . . . . . . . . . . 239
. . . . . . . . 68, 71, 159, 180
strcoll(), locale . . . . . . . . . . . 239
StreamReader(), codecs . . . . 234
StreamReaderWriter(), codecs
234
StreamRecoder(), codecs . . . 235
StreamWriter(), codecs . . . . 234
strerror(), os . . . . . . . . . . . . . . . 267
strftime(), time . . . . . . . . . . . . 292
string, . . .26, 135, 136, 145,
202
StringIO(), pickle cPickle
232
StringType, types . . . . . . . . . . . 202
strip()
string unicode . . . . 141
string . . . . . . . . . . . . . . . . . . . . . . . 219
strptime(), time . . . . . . . . . . . . 293
strxfrm(), locale . . . . . . . . . . . 239
sub()
operator . . . . . . . . . . . . . . . . . . . . 204
re . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
subn(), re . . . . . . . . . . . . . . . . . . . . . 228
SUNDAY, calendar . . . . . . . . . . . . 419
swapcase()
string unicode . . . . 143
string . . . . . . . . . . . . . . . . . . . . . . . 219
symlink(), os . . . . . . . . . . . . . . . . .275
SyntaxError, . . . . . . . . . . 28, 185
sysconf(), os . . . . . . . . . . . . . . . . .279
sysconf_names, os . . . . . . . . . . . 279

449
system(), os . . . . . . . . . . . . . . . . . . 278
SystemError, . . . . . . . . . . . . . . 186
SystemExit, .186, 194, 318, 319

T
T, re . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
TabError, . . . . . . . . . . . . . . . . . . 426
tan()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 247
tanh()
cmath . . . . . . . . . . . . . . . . . . . . . . . . .248
math . . . . . . . . . . . . . . . . . . . . . . . . . . 247
tb_frame, traceback
168, 169
tb_lasti, traceback 169
tb_lineno, traceback
169
tb_lineno(), traceback . . . . 210
tb_next, traceback . 169
tcgetpgrp(), os . . . . . . . . . . . . . . 272
tcsetpgrp(), os . . . . . . . . . . . . . . 272
tell(), file . . . . . . . . . . . 164
tempdir, tempfile . . . . . . . . . . . 299
TEMPLATE, re . . . . . . . . . . . . . . . . . . 226
template, tempfile . . . . . . . . . . 299
tempnam(), os . . . . . . . . . . . . . . . . .275
TemporaryFile(), tempfile 298
test(), cgi . . . . . . . . . . . . . . . . . . . 360
textdomain(), gettext . . . . . . 241
Thread(), threading . . . . . . . . 321
THURSDAY, calendar . . . . . . . . . . 419
time(), time . . . . . . . . . . . . . . . . . . 294
timegm(), calendar . . . . . . . . . . 421
times(), os . . . . . . . . . . . . . . . . . . . 278
timezone, time . . . . . . . . . . . . . . . 294
title(), string
unicode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
TMP_MAX, os . . . . . . . . . . . . . . . . . . . 275
tmpfile(), os . . . . . . . . . . . . . . . . .270
tmpnam(), os . . . . . . . . . . . . . . . . . . 275
traceback, . . 169, 193, 204,
208
tracebacklimit, sys . . . . . . . . 197
TracebackType, types . . . . . . . 204
translate()
string . . . . . . . . . . . . . . . . 142
unicode . . . . . . . . . . . . . . . 144
string . . . . . . . . . . . . . . . . . . . . . . . 219
translation(), gettext . . . . 242
truncate(), file . . . . . . 164
truth(), operator . . . . . . . . . . . 205

450
try, . . . . . . . . . . . . . 21, 77, 124, 182
ttyname(), os . . . . . . . . . . . . . . . . .272
TUESDAY, calendar . . . . . . . . . . . 419
tuple, . . . . .53, 135, 144, 202
tuple(), . . . . . . . . . . . 180
TupleType, types . . . . . . . . . . . . 202
type, . . . . . . . . . . . . . . . 165, 202
type(), . . . . . . . 165, 180
TypeError, . . . . . . . . . 44, 77, 186
TypeType, types . . . . . . . . . . . . . . 202
tzname, time . . . . . . . . . . . . . . . . . . 294

U
U, re . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
umask(), os . . . . . . . . . . . . . . . . . . . 269
uname(), os . . . . . . . . . . . . . . . . . . . 269
UnboundLocalError, . . . . . . 185
UnboundMethodType, types . .203
unichr(), . . . . . . . . . . 180
UNICODE, re . . . . . . . . . . . . . . . . . . . 227
unicode, . 30, 135, 136, 143,
145, 202
unicode(), . . . . 31, 180
UnicodeError, . . . 109, 142, 186
UnicodeType, types . . . . . . . . . . 202
uniform()
random . . . . . . . . . . . . . . . . . . . . . . . 250
whrandom . . . . . . . . . . . . . . . 250, 251
unlink(), os . . . . . . . . . . . . . . . . . . 274
unpack(), struct . . . . . . . . . . . . 264
Unpacker(), xdrlib . . . . . . . . . . 379
Unpickler(), pickle
cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
UnpicklingError, pickle
cPickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
unquote(), urllib . . . . . . . . . . . 364
unquote_plus(), urllib . . . . 365
unregister(), select . . . . . . . 314
update(), dictionary 148
upper()
string unicode . . . . 143
string . . . . . . . . . . . . . . . . . . . . . . . 219
uppercase, string . . . . . . . . . . . 218
URI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388, 406
URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363, 367
urlcleanup(), urllib . . . . . . . 364
urlencode(), urllib . . . . . . . . 365
urljoin(), urlparse . . . . . . . . 368
urlopen(), urllib . . . . . . . . . . . 364
URLopener(), urllib . . . . . . . . 365
urlparse(), urlparse . . . . . . . 367
urlretrieve(), urllib . . . . . . 364


urlunparse(), urlparse . . . . 368
UserDict(), UserDict . . . . . . . 257
UserList(), UserList . . . . . . . 256
UserString(), UserString . .255
UTC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
utime(), os . . . . . . . . . . . . . . . . . . . 276

V
ValueError, . . . . . . . . . . . . . . . . 186
values(), dictionary 148
vars(), . . . . . . . . .72, 181
VERBOSE, re . . . . . . . . . . . . . . . . . . . 226
version
sys . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
urllib . . . . . . . . . . . . . . . . . . . . . . . 366
version_info, sys . . . . . . . . . . . 198
vonmisesvariate(), random 249

W
W_OK, os . . . . . . . . . . . . . . . . . . . . . . . 273
wait(), os . . . . . . . . . . . . . . . . . . . . . 278
waitpid(), os . . . . . . . . . . . . . . . . .278
walk(), os.path . . . . . . . . . . . . . . 283
WEDNESDAY, calendar . . . . . . . . 419
weekday(), calendar . . . . . . . . 420
weibullvariate(), random . .250
WEXITSTATUS(), os . . . . . . . . . . . 279
whichdb(), whichdb . . . . . . . . . . 330
while, . . . . . 34, 39, 110, 116, 122
whitespace . . . . . . . . . . . . . . . . . . . . . . . . . . . 143, 218
whitespace, string . . . . . . . . . . 218
whrandom(), whrandom . . . . . . . 250
WIFEXITED(), os . . . . . . . . . . . . . . 279
WIFSIGNALED(), os . . . . . . . . . . . 279
WIFSTOPPED(), os . . . . . . . . . . . . 278
WindowsError, . . . . . . . . . . . . . 184
winver, sys . . . . . . . . . . . . . . . . . . . 198
WNOHANG, os . . . . . . . . . . . . . . . . . . . 278
write()
file . . . . . . . . . . 74, 116, 164
os . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
writelines(), file . . . 164
WSTOPSIG(), os . . . . . . . . . . . . . . . 279
WTERMSIG(), os . . . . . . . . . . . . . . . 279

X
X, re . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
X_OK, os . . . . . . . . . . . . . . . . . . . . . . . 273
XDR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388, 392, 404
XML_ERROR_*,
xml.parsers.expat.errors . . . . . . 389


XMLFilterBase(),
xml.sax.saxutils . . . . . . . . . . . . . . . . . 398
XMLGenerator(),
xml.sax.saxutils . . . . . . . . . . . . . . . . . 398
XMLParser(), xmllib . . . . . . . . 404
XMLParserType,
xml.parsers.expat . . . . . . . . . . . . . . . 389
XMLReader(),
xml.sax.xmlreader . . . . . . . . . . . . . . . 399
xor(), operator . . . . . . . . . . . . . . 205
xrange, . . . . . . . 135, 144, 202
xrange(), . . . . . . 37, 181
XRangeType, types . . . . . . . . . . . 202

Z
Z_BEST_COMPRESSION, zlib . .333
Z_BEST_SPEED, zlib . . . . . . . . . . 333
Z_DEFAULT_COMPRESSION, zlib
333
Z_DEFAULT_STRATEGY, zlib . .334
Z_DEFLATED, zlib . . . . . . . . . . . . 334
Z_FILTERED, zlib . . . . . . . . . . . . 334
Z_FINISH, zlib . . . . . . . . . . . . . . . 335
Z_FULL_FLUSH, zlib . . . . . . . . . . 335
Z_HUFFMAN_ONLY, zlib . . . . . . . 334
Z_NO_COMPRESSION, zlib . . . . 333
Z_SYNC_FLUSH, zlib . . . . . . . . . . 335
ZeroDivisionError, . . 77, 183
zfill(), string . . . . . . . . . . . . . . 218
zip(), . . . . . . . . . . 50, 181
ZIP_DEFLATED, zipfile . . . . . . 337
ZIP_STORED, zipfile . . . . . . . . 337
ZipFile(), zipfile . . . . . . . . . . 337
ZipInfo(), zipfile . . . . . . . . . . 337
ZLIB_VERSION, zlib . . . . . . . . . . 333

. . . . . . . . . . . . . . . . . . 42
. . . . . . . . . . . 43, 44, 46, 107, 108
. . . . . . . . . . . . . . . . 43, 44, 46, 107
23, 108, 133, 134,
160
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83, 86
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

. . . . . . . . . . . . . . . . . . 108, 160

. . . . . . . . . . . . . . . . . . . . . . . . . 143, 218

451
. . . . . . . . . . . . . . . . . . . . . . . . . . . 143, 217

, . 163, 178, 197, 288


, . float
. . . . . . . . . . . . . . . . . . . . . . . . . . 298

__import__() . . . . . . . . . . . . . . . . . . . . 119, 170
abs() . . . . . . . . . . . . . . . . . . . . 25, 160, 171, 205
apply() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46, 171
buffer() . . . . . . . . . . . . . . . . . . . . . . . . . 145, 171
callable() . . . . . . . . . . . . . . . . . . . . . . .148, 171
chr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
cmp() . . . . . . . . . . . . . . . . . . . 147, 154, 171, 239
coerce() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
compile() . . . . . . . . . . . . . . 117, 167, 172, 173
complex() . . . . . . . . . . . . . . . 24, 132, 160, 172
delattr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
dir() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63, 172
divmod() . . . . . . . . . . . . . . . . . . . . . . . . . 161, 172
eval() . . . . . . . . . . . . . 117, 119, 130, 167, 172
execfile() . . . . . . . . . . . . . . . . . .117, 130, 173
filter() . . . . . . . . . . . . . . . . . . . . . . . . . . 49, 173
float() . . . . . . . . . . . . . . . . . . 25, 132, 160, 173
getattr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
globals() . . . . . . . . . . . . . . . . . . . . . . . . 119, 174
hasattr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
hash() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155, 174
hex() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159, 174
id() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
input() . . . . . . . . . . . . . . . . . . . . . .129, 174, 197
int() . . . . . . . . . . . . . . . . . . . . 25, 132, 160, 174
intern() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
isinstance() . . . . . . . . . . . . . . . . . . . . . . . . . 175
issubclass() . . . . . . . . . . . . . . . . . . . . . . . . . 175
len() . . . . . . . . 30, 33, 38, 135, 147, 157, 175
list() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
locals() . . . . . . . . . . . . . . . . . . . . . . . . . 119, 175
long() . . . . . . . . . . . . . . . . . . . 25, 132, 160, 176
map() . . . . . . . . . . . . . . . . . . . . . . . . . .49, 176, 207
max() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
min() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
oct() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159, 176
open() . . . . . . . . . . . . . . . . . . . . . . . . 72, 163, 176
ord() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
pow() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161, 177
range() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37, 177
raw_input() . . . . . . . . . . . . . . . . . . . . . 178, 197
reduce() . . . . . . . . . . . . . . . . . . . . . 51, 178, 207
reload() . . . . . . . . . . . . . . . . . . . . 179, 195, 211
repr() . . . . . . . . . . . . . . . . . . . . . . . . 68, 159, 179
round() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179

452
setattr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
slice() . . . . . . . . . . . . . . . . . . . . . . . . . . . 166, 180
str() . . . . . . . . . . . . . . . . . . . . . . 68, 71, 159, 180
tuple() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
type() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165, 180
unichr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
unicode() . . . . . . . . . . . . . . . . . . . . . . . . . 31, 180
vars() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72, 181
xrange() . . . . . . . . . . . . . . . . . . . . . . . . . . 37, 181
zip() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50, 181

buffer . . . . . . . . . . . . . . . . . . . . . . . 135, 145, 202
builtin_function_or_method . 150, 203
class . . . . . . . . . . . . . . . . . . . . 85, 151, 152, 203
code . . . . . . . . . . . . . . . . . . . . . . . . . . 166, 203, 263
complex . . . . . . . . . . . . . . . . . . . . . . . 24, 131, 202
dictionary . . . . . . . . . . 55, 95, 147, 155, 203
ellipsis . . . . . . . . . . . . . . . . . . . . . . . . . 166, 203
file . . . . . . . . . . . . . . . . . . . . . . 72, 163, 203, 311
float . . . . . . . . . . . . . . . . . . . . 24, 131, 132, 202
frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168, 204
function . . . . . . . . . . . . . . . 125, 149, 152, 203
instance . . . . . . . . . . . . . . . . 86, 151, 152, 203
instance method . . . . . . . . . . . . . . . . . 87, 149
int . . . . . . . . . . . . . . . . . . . . . . . 23, 131, 132, 202
list . . . . . . . . . . 32, 47, 48, 51, 135, 145, 202
long int . . . . . . . . . . . . . . . . . . . . 131, 132, 202
method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
module . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151, 203
None . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165, 202
slice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166, 203
string . . . . . . . . . . . . . . 26, 135, 136, 145, 202
traceback . . . . . . . . . . . . . . 169, 193, 204, 208
tuple . . . . . . . . . . . . . . . . . . . . 53, 135, 144, 202
type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165, 202
unicode . . . . . . . . 30, 135, 136, 143, 145, 202
xrange . . . . . . . . . . . . . . . . . . . . . . . 135, 144, 202
, . . . . 115, 163, 178,
197, 288
. . . . . . . 46, 107, 148, 149, 156
. . . . . . . . . . . . . . . . . . . . . . . . . . .104, 113
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
, . long int
40, 45, 61, 149152, 168
. 83, 85, 86, 106,
151, 155
/
28, 107, 135, 145, 147, 157, 206

. . . . . . . . . . . . . . . . . 105

. . . . . . . . . . . . . . . . . . . . . . . . . . . 105
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
. . . . . . . . . 145
. 43, 44, 46, 107, 108
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

assert . . . . . . . . . . . . . . . . . . . . . . . . 61, 120, 183


break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39, 116
class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .85, 128
continue . . . . . . . . . . . . . . . . . . . . . . . . . . 39, 116
def . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40, 125, 149
del . . . . . . . . . . . . . . . . . . . 52, 55, 115, 145, 147
exec . . . . . . . . . . . . . . . . . . . . . 117, 119, 130, 167
for . . . . . . . . . . . . . . . . . . . . . . . . 36, 39, 116, 123
global . . . . . . . . . 40, 105, 117, 119, 128, 185
if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36, 110, 122
import . . . . . . . . . . . . . . . 59, 65, 117, 170, 211
pass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39, 115
print . . . . . . . . . . . . . . . . . . 27, 35, 68, 115, 159
raise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .92, 120
return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
try . . . . . . . . . . . . . . . . . . . . . . . . 21, 77, 124, 182
while . . . . . . . . . . . . . . . . . 34, 39, 110, 116, 122
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
. . . . . . . . . . . . . . . . . . . . . . . 24, 113
. . . . . . . . . . . . . . . . . . . . . . . . . . . 76, 120
ArithmeticError . . . . . . . . . . . . . . . . . . . . . 183
AssertionError . . . . . . . . . . . . . . . . . 120, 183
AttributeError . . . . . . . . . . . . . . . . . 107, 183
EnvironmentError . . . . . . . . . . . . . . . . . . . 184
EOFError . . . . . . . . . . . . . . . . . . . . . . . . . 178, 183
Exception . . . . . . . . . . . . . . . . . . . . . . . . . 93, 182
FloatingPointError . . . . . . . . . . . . . . . . . 183
ImportError . . . . . . . . . . . . 65, 184, 211, 212
IndexError . . . . . . . . . . 29, 94, 123, 135, 185
IOError . . . . . . . . . . . . . . . . . . . . . . . . . . . 163, 184
KeyboardInterrupt . . . . . . . . . . 21, 77, 184
KeyError . . . . . . . . . . . . . . . . 55, 147, 157, 185
LookupError . . . . . . . . . . . . . . . . . . . . . . . . . . 184
MemoryError . . . . . . . . . . . . . . . . . . . . . . . . . . 185
NameError . . . . . . 53, 77, 105, 123, 129, 185
NotImplementedError . . . . . . . . . . . . . . . 185
OSError . . . . . . . . . . . . . . . . . . . . . . . . . . . 184, 267
OverflowError . . . . . . . . . . . . . 174, 183, 292


RuntimeError . . . . . . . . . . . . . . . . . . . . . . . . . 185
StandardError . . . . . . . . . . . . . . . . . . . . . . . 183
SyntaxError . . . . . . . . . . . . . . . . . . . . . . 28, 185
SystemError . . . . . . . . . . . . . . . . . . . . . . . . . . 186
SystemExit . . . . . . . . . . . . 186, 194, 318, 319
TabError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
TypeError . . . . . . . . . . . . . . . . . . . . . 44, 77, 186
UnboundLocalError . . . . . . . . . . . . . . . . . . 185
UnicodeError . . . . . . . . . . . . . . . 109, 142, 186
ValueError . . . . . . . . . . . . . . . . . . . . . . . . . . . .186
WindowsError . . . . . . . . . . . . . . . . . . . . . . . . . 184
ZeroDivisionError . . . . . . . . . . . . . . 77, 183
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
. . . . . . . . . . . . . . . . . . . . . . . . . . 110, 205

, . class
. . . . . . . . . . . . . . . . . . . . . . . . . . .105
, . complex
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
. . . . . . . . . . . . . . . . . . . . . . . 334
, . tuple

. . . . . . . . . . . . 57

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
. . . . . . . . . . . . . . . . . . 106
. . . . . . . . . . . . . . . . 56, 110
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

, .
builtin_function_or_method
, .
instance method
, . instance method
. . . . . . . . . . . . . . 34
, . module

. . . . . . . . . . . . . . . . . . . . . . . . .84

27, 135, 205

Ellipsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
None . . . . . . . . . . . . . . . . . . . . . . . 41, 43, 110, 165

() . . . . . . . . . . . . . . . . . . . .46, 107, 148, 149, 156


* . . . . . . . . . . . 27, 108, 133, 135, 161, 204, 205

453
** . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 161
+, 27, 108, 133, 135, 161, 204, 205
+, . . . . . . . . . . . . . . . 108, 134, 160, 204
-, . . . . . . . . . . . . . 108, 133, 161, 204
-, . . . . . . . . . . . . . . . 108, 134, 160, 204
. . . . . . . . . . . . . . . . . . . 83, 85, 86, 106, 151, 155
/ . . . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 161, 204
< . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
<= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
<> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
<< . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 161, 205
== . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
>= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
>> . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 161
[] . . . . 28, 107, 135, 145147, 157, 166, 206
% . . . . . . . . . . . 68, 108, 134, 137, 159, 161, 204
& . . . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 161, 205
^ . . . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 161, 205
| . . . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 161, 205
~ . . . . . . . . . . . . . . . . . . . . . . . . . 108, 134, 160, 205
and . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56, 111
in . . . . . . . . . . . . . . . . . . . .56, 110, 135, 159, 205
is . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56, 109
is not . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56, 110
lambda . . . . . . . . . . . . . . . . . . . . . . . . 45, 111, 149
not . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56, 111, 205
not in . . . . . . . . . . . . . . . . . . . 56, 110, 135, 159
or . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56, 111
. . . . . . . . . . . . . . . 46, 107, 148, 149, 156
83, 85, 86, 106, 151, 155
/ . . 28,
107, 135, 145, 147, 157, 206
. .27, 135,
205
. 27, 135,
205
. . . . . . . . . . . . . . . . . 28, 107, 135, 146, 206
. . . . . . . . . . . . . . 107, 166
. . . . . . . . . . . . . . . 68, 137, 159

. . . . . . 23, 108, 133, 134, 160


. . . . . . . . . . . . . . . . . . . . . . . . . . . . 108, 160
. . . . . . . . . . . . . . . . . . . . . . . . . . 56, 110
. . . . . . . . . . . . . . . . . . . . . . 34, 108, 109
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .128
. . . . . . . . . . . . . . . . . .120
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .147
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48, 325

454
, . . . . 163, 197, 288

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

LANG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240, 242
LANGUAGE . . . . . . . . . . . . . . . . . . . . . . . . . 240, 242
LC_ALL . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240, 242
LC_MESSAGES . . . . . . . . . . . . . . . . . . . . . 240, 242
PYTHONDEBUG . . . . . . . . . . . . . . . . . . . . . . . . . . 426
PYTHONHOME . . . . . . . . . . . . . . . . . . . . . . . . . . . .427
PYTHONINSPECT . . . . . . . . . . . . . . . . . . . . . . . 426
PYTHONOPTIMIZE . . . . . . . . . . . . . . . . . . 61, 427
PYTHONPATH . . . . . . . . . . 61, 62, 119, 196, 427
PYTHONSTARTUP . . . . . . . . . . . . . . . 21, 191, 427
PYTHONUNBUFFERED . . . . . . . . . . . . . . . . . . . 427
PYTHONVERBOSE . . . . . . . . . . . . . . . . . . . . . . . 427
PYTHONY2K . . . . . . . . . . . . . . . . . . . . . . . . 290, 291
. . . . . . . 43, 44, 46, 107
. . . . . . . . . . . . . . . 192
. . . . . . . . . . . . . . . . . . . . . . .135
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
. . . . . . . . . . . . . . . . . . . . . . . . . 24, 113
. . . . . . . . . . . . . . . . . . . . . . . . . . . 34
. . . . . . . . . . . . . . . . . . . . 143, 218
. . . . . . . . . . . . . . . . . . . . . . . . . 83
. . . . . . . . . . . . . . . . . . . . . . . 128
. . . . . . . . . . . . . . . . . . . . . . 112


27, 135, 205
. . . . . . . . . . . 107, 166
. . . . . . . . . . . . . . . . . . . 220

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
, . whitespace
, . dictionary
. . . . . . . . . . . . . . . . . . . . 121
. . . . . . . . . . . . . . . . . . . . . . 153
, . list
. . . . . . . . . . . . 34, 108, 109

. . . . . . . . . . . . . . 107, 166
. . . . . . . . . 28, 107, 135, 146, 206

. . . . . . . . . . . . . . . . . . . . . . . 163, 197, 288
. . . . . . . . . . . . . . . . . . . . .163, 178, 197, 288
. . . . . . . . . . . . . . 115, 163, 178, 197, 288
. . . . . . . . . . . . . . . . . . . . . 90
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


, . string
. . . . . 40, 45, 61, 149152, 168
Unicode, . unicode
. . . . . . . . 68, 159, 179
. . . . . . . . . . . . . . . . . . . . . . 136
. . . . . . . . . . . . . . . . . . . . . 143, 217

. . . . . . . . . . . . . . . . . . . . . . . 56

, . . . . . . . . . . . . . . . . . . . . . . . . . 298
. . . . . . . 68, 137, 159

, .
builtin_function_or_method
, . function

. . . . . . . . . . . . . . . . . . . 134
, . int

. . . . . . . . . . . . . . . . . . . . . . . . . .88

, . float
, . long int
, . complex
, . float
, . int
. . . . . . . . . . . . . . . . . . . . . . . 131

, . instance
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289

Вам также может понравиться