Python Cookbook

Second Edition April 2005
ISBN 978-0-596-00797-3
Seiten 844
EUR48.00, SFR78.90


Weitere Informationen zu diesem Buch

Inhaltsverzeichnis | Index | Probekapitel | Kolophon | Rezensionen |


Index

	
[ Symbols ], [ Numbers ], [ A ], [ B ], [ C ], [ D ], [ E ], [ F ], [ G ], [ H ], [ I ], [ J ], [ K ], [ L ], [ M ], [ N ], [ O ], [ P ], [ Q ], [ R ], [ S ], [ T ], [ U ], [ V ], [ W ], [ X ], [ Z ],

Symbols[ Top ]
\ (backslash), 5, 58, 717
, (comma), 15
".join (empty string joiner), 9, 33
+ operator, 13
<< operator, 83
#! (shebang), 68
/ (slash), 58
% (string-formatting operator), 7, 13, 37
_ (underscore), 563

Numbers[ Top ]
4Suite package, 464

A[ Top ]
Access, 289
accessing
      attributes of instance objects, 230
      MySQL database, 310
Active Server Pages (ASP), 526
ActivePython, 326
ActiveX Data Objects (ADO), 162
Adapter Design Pattern, 88
adaptive sorting algorithms, 194
_ _add_ _, 232
adding items to sequences while preserving sortedness, 206
ADO (ActiveX Data Objects), 162
      using Microsoft Jet via, 325
algorithms, 643-688
      performance issues, 205
antispam system, configuring, 406
Apache
      authenticating SSL client over HTTPS, 582
      calculating hits per IP address, 398
      calculating rate of client cache hits on, 400
APIs, cross-platform, file locking using, 103
append method (list objects), 15
applications
      message loops, Windows, 382
      multithreaded, 372-374
      relational database design inappropriateness for, 289
      Win32, message processing with MsgWaitForMultipleObjects, 381-384
application-specific languages, 587-589
archiving tree of files into compressed tar file, 80
*args syntax, 163
arithmetic
      binary floating-kpoint, simulation, 693
      decimal, 135
      floating-point, simulating, 682-685
      with error propagation, 677-679
arrays
      C, translating Python sequence into, 631-634
      transposing two-dimensional, 161
ASCII characters in text strings, 4
ASP (Active Server Pages), 526
assert, 269
assigning/testing expression results, 180-183
asynchat module, 559
asyncore module, 559
      performance benefits, 356
atomic operations, 357
attachments, removing from email messages, 499-501
attributes
      adding to classes, 240
      checking objects for, 266-269
      hiding those supplied by delegate, 247
      named, tuple items accessible as, 250-252
      restricting setting in classes, 240
      settings for
            restricting in classes, 240
            _ _setattr_ _ method, 237
authentication
      HTTPS navigation through proxies, 541
      remote logins
            SSH, 579-581
            Telnet, 576-579
      SSL client over HTTPS, 582
      via POP server, 397
automatic caching, 29, 656
automatic delegation, 248
      as alternative to inheritance, 244-247
      wrapping by, 246

B[ Top ]
backslash (\), 5, 58, 717
backups, 403
      versioning filenames, 105
backwards compatibility
      classic classes for new code development, 282
      inheritance in Python, 234
bag (multiset), 662-666
basestring type, 9
Berkeley DB (Berkeley database), persisting data with, 307-309
big-O analysis and notation, 199
binary data, sending to Windows standard output, 82
binary files
      randomly reading bytes from, 74
      sequentially reading bytes from, 59, 66
binary large objects (BLOBs), 290
binary mode versus text mode (files), 59
binary search algorithm, 211
binary strings, formatting integers as, 671-675
binding attributes of instance objects, 230
bisect (binary search), 211
bisect_right function, 211
bits, printing integer as string of, 683
BLOBs (binary large objects), 290
      storing in
            MySQL, 312
            PostgreSQL, 313
            SQLite, 315
Borg class, 276
      avoiding Singleton Design Pattern with, 273-277
Borg design nonpattern, alternative to, 275
bound methods, 42
      held by objects, pickling, 300-302
      maintaining references to without inhibiting garbage collection, 256
      weak references to, 258
bounded precision, 113
bsddb package, 307-309
bsddb3 package, 307-309
building
      C extensions, 619-622
            with Pyrex, 623-624
      classes via metaclasses, 236
      dictionaries, 166-169
      empty class instance, 254
      list comprehensions, 609-611
      lists, 7, 151, 155
      modules, tools for, 617
_ _builtin_ _ module, 188
built-in type, inheriting, 235
bytecodes, multiple, 357
bytes, as distinguished from characters, 1
      CRC-64 computation on stream of, 107-109
      extracting from strings, 28
      randomly reading from binary file, 74
      sequentially reading from binary file, 66
      sequentially reading from binary files, 59
bytestrings, 45

C[ Top ]
C extensions
      building, 619-622
            with Pyrex, 623-624
      debugging, 639
C++ library, using in Python, 625-627
C programming language
      coding Python extensions, 357
      cPickle as built-in module for storing/retrieving data, 290
            (see also cPickle module)
C++ syntax for I/O, 83
caching
      attribute values, 750-752
      automatic, 29, 656
      with FIFO pruning, 660-662
callback functions, avoiding lambda in writing, 426
candygram module, 372-374
case-insensitive text strings, 52-57
Celsius temperature, converting to other scales, 235
center method (string objects), 11
CGI (Common Gateway Interface), 341, 527
      programs, 341
      scripts (see CGI scripts)
      testing, 527-530
      uploading files with, 532
CGI scripts, 527
      handling URLs in, 530-532
      using Microsoft Jet via ADO, 325
Chainmap class, 243
ChangeCheckerMixin class, 264
characters, 8
      accented, entering in Tkinter widgets, 430
characters method, 468
class
      instances, upgrading on reload, 774-778
      objects, 230
      statement, 230
_ _class_ _ attribute, 255
classes
      adding attributes to, 240
      chaining dictionary lookups, 242
      classic, as legacy feature, 234
      creating new instances of, 230
      defining through inheritance, 232
      finding all methods of, 757
      functionality supplying across range of, 233
      instance, changing on the fly, 255
      instantiating, 231
      restricting attribute setting, 240
      saving/restoring with cPickle, 297-300
      Singleton, 272
      subclassing, 232
      (see also metaclasses)
closures, 21
CLSID (globally unique identifier), 411
Cocoa toolkit, building GUI programmatically, 459-461
code
      development, classic classes not recommended for, 282
      maintaining by use of new-style classes, 235
      programming, 235
            databases and, 288
      reusing through inheritance, 232
code objects
      altering in a decorator, 778
      extracting from _ _init_ _ objects, 300
      inserting in dynamically generated modules, 591
      pickling, 302-305
codecs module, printing Unicode characters to standard output, 48
collecting named items, 178-180
collections.deque
      subclassing for ring buffer implementation, 261
      using for FIFO implementations, 659
COM
      connecting to running instance of Internet Explorer, 415
      driving ADO and Jet with, 325
      driving Microsoft Word with, 102
      parsing XML with MSHTML, 483
      reading Microsoft Outlook contacts, 416-418
      registering/unregistering DLLs, 412
comma (,), 15
commands
      running repeatedly, 131
      scheduling, 133
comments, tracing in debug mode, 339-342
Common Gateway Interface (see CGI)
Common Object Request Broker Architecture (see CORBA)
comparison key (for sorting), 203
composition, 597
compression
      of objects, 296
      persistence with, 297
computer games, relational database design inappropriate for, 289
computers, monitoring, 506
concurrent programming, 356
conditionals. disabling while debugging, 333
connecting to running instance of Internet Explorer, 415
_const class, 240
constants, defining, 238
const.py module, 239
containsAny method, 17
containsOnly method, 18
content type, checking via HTTP, 535
converting
      among image formats, 434-437
      among temperature scales, 235
      characters to numeric code, 8
      Python source into HTML markup, 598-601
      text strings, 45
            to lowercase/uppercase, 26
      time zones, 130
cookies
      handling while fetching web pages, 538-541
      Internet Explorer, finding, 543-545
_ _copy_ _ method, 254
copy module, 148
copy.copy function, 254
copying
      mailbox files, 405
      objects, 148-150
copy_reg module, extending pickle/cPickle modules, 302
CORBA (Common Object Request Broker Architecture), 558, 560
      implementing server and client, 574-576
CoreGraphics module, 100
counts method, 201
cPickle module, 290
      classes and instances, 297-300
      serializing data, 293-296
      using compression with, 296
      (see also pickling), 300
CRCs (cyclic redundancy checks), 107
CreateMutex function, 381
creating
      class instances, 230
      share on Windows, 414
cStringIO module, 61, 79
ctypes module, 411
currying, 594-597
cursor objects, 317
custom metaclasses, synchronization and, 361
cyclic redundancy checks (CRCs), 107

D[ Top ]
daemon processes, forking on Unlx-like systems, 388-390
daemon threads, 358
data
      Excel, accessing with Jython, 330
      hierarchical structuring of, 265
      saving/retrieving with support for selecting/searching, 310
      serializing
            marshal module, 291-293
            pickle and cPickle modules, 293-296
database cursors, printing contents of, 320-323
databases, 288, 307-331
      applications providing transaction support/concurrency control, 290
      persistence, compression and, 297
      programming issues, 288
      relational (see relational databases)
datagram sockets (UDP), 487-489
      monitoring network status, 511-513
      using for SNTP, 492
date/time, 110-135
      calculating
            number of holidays, 124-127
            number of weekdays, 122
            time periods in date range, 120
            yesterday/tomorrow, 116
      checking for daylight saving time, 129
      converting time zones, 130
      datetime module, 112
      finding date of previous weekday, 118
      getting time from server via SNTP protocol, 491
      parsing fuzzy dates, 127
      running commands repeatedly, 131
      summing song durations, 121
      time module, 110-112
      timedelta module
            timedelta type, 116-119, 121
datetime module, 112, 116, 120
      calculating number of weekdays, 123
date/timescheduling commands, 133
dateutil module, 120
      automatic holiday lookups, 124
      calculating number of weekdays, 123
daylight saving time, checking for, 129
DB API modules, single parameter passing style across various, 323-325
db_row (Python Database Row Module), 320
DDList class, 429
deadlocks, 376
      avoiding by nonblocking output and error streams, 386-388
debug mode, tracing expressions/comments, 339-342
debugging, 332-354
      C extensions, 639
      disabling conditions and loops, 333
      exception handling, 337-339
      garbage collection, 336, 337
      property function, 253
      starting debugger automatically after uncaught exception, 345-348
      threads in processes, 363
      tracebacks, 342-345
      unit tests
            checking values against, 352-354
            running automatically, 348
            running simply, 346
decimal module, 113-116, 135-141
decimal numeric data type, 113
decorate-sort-undecorate (DSU), 190
decorators, 740-787
      altering code objects in, 778
_ _deepcopy_ _ method, 256
def statement, defining methods with, 231
default values/bounds, using with tkSimpleDialog functions, 427
_ _delattr_ _ method, 245
delegation, 233
      flexibility of, 246
      in proxies, 247-250
      (see also automatic delegation)
description attribute, 316
      cursors, 321
descriptors, 740-787
design patterns, 269-278
      Adapter, 88
      Monostate, 276
      Null Object, 277-280
      object-oriented, 230
      Reactor, 570-573
      Singleton, 230, 271-277
      State, 269-271
      Strategy, 270
      Template Method, 226, 233
design tools, relational database design in appropriate for, 289
dict (built-in type), 167
      fromkeys classmethod, 176
dictionaries
      adding entries to, 165
      building, 166-169
      chaining lookups, 242
      dispatching methods/functions with, 175
      enriching type of, with rating functionality, 222-226
      extracting subsets from, 170
      finding unions/intersections of, 176
      getting values from, 163
      inverting, 171
      keys in (see dictionary keys)
      mapping column names to index values, 316
      sorting, 195
      using for search tasks, 190
      (see also mappings)
dictionary keys
      associating multiple values to, 173
      avoiding quoting in dictionary building, 166
directories
      computing relative path, 96
      finding files in, 91-96
      sharing on Windows, 414
      trees (see directory trees)
directory trees
      changing file extensions in, 90
      walking, 88
dispatching
      generators as co-routines, 691
      methods via dictionaries, 175
distributed programming, 558-583
      error handling in, 571
distutils package, 611
division, true versus truncating, 26
DLLs (dynamic link libraries), Windows
      calling functions from, 627-629
      registering/unregistering, 411
docstrings, 351
doctest module, 222, 333
DOM (Document Object Model), 464
drag-and-drop reordering, adding to a Tkinter listbox, 428
DSU (decorate-sort-undecorate), 190
      sorting lists of objects by their attributes, 198
      sorting lists of strings ignoring case, 196
      sorting strings with embedded numbers, 204
dtuple module, 319
duck typing, 10
dump and dumps functions
      marshal module, 291-293
      pickle/cPickle modules, 293-296
duplicates, removing from sequences, 647-653
Dynamic IP protocol (DNS), 519-522
dynamic link libraries (see DLLs)

E[ Top ]
EAFP (easier to ask forgiveness than permission), 10
email addresses, building whitelist of, from mailboxes, 406
email messages
      blocking duplicates, 408
      in Python 2.4, 501-503
      logging to disk, 522-524
      malformed, 503
            POP3 mailboxes, 503, 505
      removing attachments from, 499-501
email module, 409
email package, 405
      bundling files in MIME messages, 495
embedding Python, 616-642
empty string joiner (".join), 9, 33
encoding
      types of, 47
      Unicode for XML/HTML, 49
      XML, autodetecting, 469-471
enumerate function, 154
enumerations, simulating, 606-609
_ _eq_ _ method, adding to Borg class, 274
Erlang's approach to thread communication, 373
error handling, 332
      EAFP approach, 10
      in distributed programming, 571
      in Unicode encoding, 50-52
      in XML parsing, 477
      via exceptions, 337-339
event-driven programming, 356
      multithreading compared to, 359
Excel (see Microsoft Excel)
exception handling, 337-339
      starting debugger automatically after uncaught exception, 345-348
      within expressions, 185
exec statement, 187, 591
      power of, 593
executables, making from scripts
      in Windows with p2exe, 611
      Unix, 613-615
expand function, 35
expandtabs method, 33
Expat parser (XML), 463
expressions
      as distinct from statements, 666, 765
      handling exceptions in, 185
      tracing in debug mode, 339-342
extend method, 15
extending Python, 616-642
extract_stack function, 340

F[ Top ]
factory functions
      closures, 20, 361
      metaclasses, 771-774
      tuple subclasses, 249
fade-in windows, implementing with IronPython, 461
Fahrenheit temperature, converting to other scales, 235
farey fractions, converting numbers to rationals, 675-677
FeedParser module, 501, 503
fetch data from databases incrementally, 719
Fibonacci sequence, 697
FIFO (first-in, first-out)
      pruning, caching with, 660-662
FIFO (first-in, first-out) implementations, using collections.deque for, 659
file extensions, changing in directory trees, 90
file objects, 87
filenames, versioning, 105
files, 58-109
      archiving into compressed tar file, 80
      attributes, changing on Windows, 100
      backing up, 403
            versioning filenames, 105
      binary mode versus text mode, 59
      bundling in MIME messages, 495-497
      C++ approach to I/O, 83
      code portability, 60-62
      counting lines in, 69-72
      dynamically changing search path, 94
      extensions (see file extensions)
      finding
            in directories, 91-96
            on search path, 93
      HTTP downloading, resuming, 536
      input, rewinding, 84-87
      locking
            types of locks, 104
            with cross-platform API, 103
      mailbox, selectively copying, 405
      names (see filenames)
      objects (see file objects)
      OpenOffice.org, extracting text from, 101
      OPML, generating, 545-548
      PDF (see PDF files)
      processing words in, 72
      pseudo-files
      random-access
            input/output, 74
            updating, 75
      reading, 62-65
            by specific line, 68
      searching/replacing text in, 67
      uploading with CGI, 532
      walking directory trees, 88
      Word, extracting text from, 102
      writing to, 66
      zip, 77, 79
filtering
      list of FTP sites, 490
      text strings for set of characters, 22-25
filter_rdf function, 480
find method, subsequences in sequences, 221
finding
      all methods of classes, 757
      date of previous weekday, 118
      files in directories, 91-96
      Internet Explorer cookie, 543-545
      subsequences in sequences, 157
      unions/intersections of dictionaries, 176
first-class objects, 230
floating point, 113
floating-point
      arithmetic, 135
      arithmetic, simulating, 682-685
FOAF (Friend-Of-A-Friend), 545
folders (see directories)
foreign exchange rates, monitoring, 144
formatter.AbstractFormatter class, 57
Friend-Of-A-Friend (FOAF), 545
FTP sites, filtering list of, 490
functions
      built-in, trying special methods in specific order, 232
      composing, 597
      dispatching with dictionaries, 175
      executing in parallel on multiple argument sets, 369-371
      I/O bound, 371
      polymorphism of, 267
      portability, 62

G[ Top ]
Gadfly, 290
garbage collection
      cyclic, avoiding, 337
      debugging, 336, 337
      maintaining references to bound methods without inhibiting, 256
gc module, 336
generator expressions, 153
generators, 689-739
generic programming, 232
genetic sequencing information, archiving, relational database design for, 290
get method, 35
      dictionary values, 163
      extracting subsets from dictionaries, 170
      lists and, 153
      values from dictionaries, 163
_ _getattr_ _ method, 245, 248
_ _getitem_ _ method, 161, 202
getItems method, 561, 562
getQualifiedURL function, 531
_getS method, 253
_ _getstate_ _ method, 255
GetSubList method, 445
GetText method, 445
getvalue method, 338
GIF images, inline, embedding using Tkinter, 432
GIL (Global Interpreter Lock), 356
      Python C APIs and, 357
Gimp toolkit (GTK), 423
Global Interpreter Lock (see GIL)
globally unique identifier (CSLID), 411
GMP (Gnu Multiple Precision), 683
Graham's scan algorithm, 686
groupby function, 227
_groupkeyfunc function, 227
groupnames function, 227
GTK (Gimp toolkit), 423
GUI toolkits, 423
GUIs
      asynchronous I/O, combining with threads, 439-443
      concurrent programming and, 356
      Python Cocoa, building programmatically, 459-461
      (see also user interfaces)
gzip module
      compressing backup files, 404
      using compression with, 296

H[ Top ]
handling exceptions (see exception handling)
_ _hash_ _ method, adding to Borg class, 274
Haskell programming language, 153
haystack.count method, 6
heap property, 207
heap, retrieving data in order, 208
heapq module, 207, 209, 364
histogram, 200
HTML
      converting documents to text on Unix, 55
      encoding Unicode for, 49
      mail, sending, 492-495
      (see also XML)
htmlentitydefs module, 50
HTTP
      checking content type via, 535
      monitoring networks with, 511-513
HTTPS navigation, authenticating with proxy for, 541

I[ Top ]
IDLE (Integrated Development Environment), 443-445
      GUI shell for exploring Python OOP, 232
IDLE tree widget, using in Tkinter, 443-445
idlelib package, 443
image formats, converting among, 434-437
ImageJ, implementing plug-in in Jython, 455
immutability, 239
importing modules, 591-594
inheritance
      automatic delegation as alternative, 244-247
      code reuse and, 232
      copying objects and, 255
      drawbacks, 244
      flexibility of delegation and, 246
      multiple, 233
            supported by super class, 285-287
      polymorphism, requirement of, 232
_ _init_ _ method, 53, 300
      bypassing, 255
      calling superclasses that define, 282-285
      constructors for class instances, 231
      extracting code object of, 281
      initializers for class instances, 231
      overriding, 255
_ _init_ _ methods
      automatically initializing instance variables from, 280-282
initializing instance variables from _ _init_ _ methods, 280-282
input files, rewinding, 84-87
input function, 422
instance objects, 230
instances
      checking for state changes, 262-265
      saving/restoring with cPickle, 297-300
integers, formatting as binary strings, 671-675
Integrated Development Environment (see IDLE)
Internet Explorer, connecting to running instance of, 415
Internet Relay Chat (IRC), 522
intersection method, 178
intertools module, 17
intervals, checking values against in unit tests, 352-354
introspection, 589
      coding and, 285
I/O (input/output)
      C++ syntax, 83
      operations
            I/O-bound functions, 369-371
            locking threads, 357
      random-access files, 74
      sources, accessing while running GUIs, 439-443
IP addresses, calculating Apache hits per, 398
IRC (Internet Relay Chat), connecting to, 522-524
IronPython, implementing fade-in windows with, 461
IsExpandable method, 445
isinstance method, 9
islower method, 27
isorted function, 209
isSSL function, 531
istext function, 26
istitle method, 27
isupper method, 27
itemgetter function, 202, 252
iter function, 158
_ _iter_ _ method, 62
iterable mappings, 244
iterators, 689-739
iteritems method, 172
itertools module, 17
      dictionary building, 167
      inverting dictionaries, 171, 172
itertools.ifilter, 17
izip, 167, 171

J[ Top ]
JDBC (Java Database Connectivity), accessing from Jython servlet, 327-330
".join (empty string joiner), 9, 33
join method, 6, 14, 363
Jython
      extracting data from Excel, 330
      implementing ImageJ plug-in, 455
      servlets
            connecting to JDBC database from, 327-330
            running with, 542
      viewing image from URL with, 456

K[ Top ]
Kelvin temperature, converting to other scales, 235
KeyError exception, 243
keys method, 225
KMai, blocking duplicate email messages, 408
KMP (Knuth-Morris-Pratt algorithm, 221
KnuthMorrisPratt method, 221
**kwds syntax, 163

L[ Top ]
lambda, avoiding in writing callback functions, 426
LBYL (Look Before You Leap), object attribute checking, 266
ldap extension, 524
ldap module, 525
LDAP servers, accessing, 524
lexing, 585-586
linecache module, 68
line-termination characters, 59, 64
Linux
      measuring memory usage on, 334
      user interface toolkits, 423
list comprehensions
      accessing substrings and, 28
      building, 609-611
      dictionary building, 171
      quicksort algorithm and, 215
      removing/reordering columns in lists of rows, 160
      translating from Haskell to Python, 153
list function, 213
list objects, 15
listboxes, Tkinter
      adding drag-and-drop reordering to, 428
      supporting multiple values per row, 445-448
lists
      building, 7, 151, 155
      items in
            appending, 217-220
            processing in random order, 204
      of rows, removing/reordering columns, 160
      picking items at random from, 184
      returning elements of, 153
ljust method (string objects), 11
locale module, 139
localization
      processing non-ASCII characters, 43-45
      western European alphabets, 4
locals function, 281
lock function, 104
locks, 356
log
      Apache files, analyzing, 398
      information, storing, 259-262
logging, centralized, 332
logging module, 489
Look Before You Leap (LBYL), object attribute checking, 266
LookBeforeYouLeap class, 283
loops, disabling while debugging, 333
lower method, 27, 197
_ _lshift_ _, 83
lstrip method, 12
Luhn algorithm, 143

M[ Top ]
Mac OS, getting user input on, 456
Mac OS X
      line-termination characters, 64
      PDF files, counting pages in, 99
      system information, gathering, 418-421
mailbox files, selectively copying, 405
mailbox modules, 405
mailboxes
      building whitelist of email addresses from, 406
      POP3, malformed messages, 503, 505
makefile method, textual data source, 4
maketrans function, 19
      string filtering, 23
make_xlat function, 40
malware, 500
mappings, 242
      partial, changing into full, 243
marshal module, 290
      limitations, 303
      serializing data, 291-293
      use cases for, 310
Medusa, 560
      using with XML-RPC, 564
medusa package, 564
Meerkat service, 561
memoization, 29, 656
      implementing _ _deepcopy_ _ method, 256
memory
      debugging problems, 641
      file-based transformations, 4
      leaks, investigating, 336
      measuring usage on Linux, 334
      ring buffers and, 260
      saving, implementing tuples as named items, 252
mergesort algorithm, 194
message loops, 382
message pumps, 382
messages (see email messages)
met method, 284
metaclasses, 236, 740-787
      custom, synchronization and, 361
methods
      as attributes in Python, 245
      bound (see bound methods)
      calling other methods on same instance, 233
      copying between Tkinter widgets, 448
      defining as instance objects behavior, 231
      delegating work to same method in superclass, 233
      dispatching with dictionaries, 175
      hiding those supplied by delegate, 247
      of classes, finding all, 757
      of subclass, overriding superclass methods, 233
      special, of classes, 232
      string objects, 6
      synchronizing in objects, 359-361
      unbound, 42
Microsoft Access (see Access)
Microsoft Excel
      data, extracting with Jython, 330
      XML, parsing, 475
Microsoft Jet, 289
      using via ADO, 325
Microsoft ODBC standard, 289
Microsoft Outlook, reading contacts, 416-418
Microsoft SQL Server, 290
MIME messages
      bundling files in, 495-497
      multipart, unpacking, 497-499
MIME (Multipurpose Internet Mail Extensions), 495
mimetools module, 493
MimeWriter module, 493
mixin class
      checking instances for state changes, 262
      functionality supplying across range of classes, 233
      using cooperative supercalls, 285
modules
      benefits over OOP objects, 230
      building, tools for, 617
      class definitions, including assignment statement in, 235
      ensuring name is defined in, 187
      importing, 591-594
      Python search path and, 94
      SWIG-generated, 630
money tasks, 135-145
      adding machine, Python as, 140-143
      checking credit card checksums, 143
      foreign exchange rates, monitoring, 144
      formatting decimals as currency, 137-140
      performing decimal arithmetic, 135
moneyfmt function, 137
monitoring computers, 506
Monostate Design Pattern, 276
MsgWaitForMultipleObjects function, 381-384
MSHTML, 483
msvcrt module, 82, 98
MultiListbox._ _init_ _ method, 448
multiple inheritance, 233
multiple_replace function, 39
multiprocess computing, 355
Multipurpose Internet Mail Extensions (MIME), 495
multitasking, without threads, 378
multithreaded environment, using SWIG-generated modules in, 630
multithreaded programming, 355-390
      deadlocks, 376
      main benefit of, 375
      race conditions, 376
MySQL, 290
      database, accessing, 310
      storing BLOBs in, 312
MySQLdb module, 310
      storing BLOBs in MySQL, 312

N[ Top ]
named attributes, tuple items accessible as, 250-252
name_iterablemust, calling groupnames function on, 227
Network News Transfer Protocol (NNTP), 486
network ports, forwarding/redirecting, 513-515
network programming, 485-525
      detectng inactive computers, 506-511
      Dynamic IP protocol, 519-522
      messages, passing with socket datagrams, 487-489
networks, monitoring with HTTP, 511-513
_ _new_ _ method, 252
_ _new_ _ staticmethod method, 271
new-style classes, 234
nlargest, 209
NNTP (Network News Transfer Protocol), 486
nobuffer method, 86
NoNewAttrs class, 240
nsmallest, 209
Null class, 278
      see also Null Object Design Pattern
Null Object Design Pattern, 277-280
numbers, converting to rationals, 675-677

O[ Top ]
Object Request Brokers (ORBs), 560
object-oriented design pattern, 230
object-oriented programming (see OOP)
objects
      checking for attributes, 266-269
      code, pickling, 302-305
      compressing generic, 296
      copying, 148-150
            deep copies, 256
            shallow copies, 255
      describing creation of, 230
      determining whether iterable, 158
      docstrings in, 351
      file (see file objects)
      in Python, 230
      lists of, sorting by object's attribute, 198
      making fast copy of, 254
      mutating with shelve module, 305-307
      referene cycles, 337
      state of, 269-271
      synchyronizing methods in, 359-361
      testing for string-like characteristics, 9
      with bound methods of other objects, pickling, 300-302
ODBC (Open Database Connectivity), 289
old-style classes, 234
once method, overridden by Subclass, 233
OOP (object-oriented programming), 175, 229-287
      polymorphism as benefit of, 232
      Python implementation of, 229
open, 58
      reading from files, 63
Open Database Connectivity (see ODBC)
Openldap C API, 525
OpenOffice.org files, extracting text from, 101
operations
      state-altering, checking objects for necessary attributes, 266
      trying special methods in specific order, 232
operator module, 143, 252
OPML (Outline Processor Markup Language), 545
      files, 545-548
options, copying with geometry methods between Tkinter widgets, 448
Oracle, 290
ORBs (Object Request Brokers), 560
os module, 55, 58, 401
      walking directory trees, 89
os.path module, 404
Outline Processor Markup Language (OPML), 545
Outlook, reading contacts, 416-418
overriding methods, 232

P[ Top ]
p2exe, making Windows executables from scripts, 611
parameters, single passing style across DB API modules, 323-325
parentheses, balanced, checking strings for, 604-606
parser generators, 587
parser module, 128
parsing, 586
      text, 3
      XML with MSHTML, 483
passwords
      random, 393
      somewhat-random, 394-397
PB (Perspective Broker), 558
PDF files, counting pages on Mac OS X, 99
PEM (Privacy-enhanced Electronic Mail), 582
percentage error, 678
performance
      adding entries to dictionaries, 166
      algorithms and, 205
      big-O analysis and notation, 199
      comparing isorted function with sorted function, 209
      comparing select method with sort method, 214
      dictionary unions/intersections, 177
      enhancing, adding threads to Python programs, 356
      file-based transformations, 4
      invert_dict_fast versus invert_dict, 172
      multiple string pieces in sequences, 14
      multiprocess computing, 356
      search paths, changing, 94
      sorting and, 192
      sorting by object attributes, 200
persistence, 288-307
      compression with, 297
Perspective Broker (PB), 558
pickle module, 290, 559
      serializing data, 293-296
      use cases for, 310
      (see also pickling), 300
pickling
      code objects, 302-305
      objects with bound methods, 300-302
PIL (Python Imaging Library), 434
plain text, 4
      converting to Unicode, 45
      (see also text)
PLY parser generator, 587
Pmw extension library, 423
polymorphism
      as benefit of OOP, 232
      Python functions and, 267
      signature-based, 232
pop method
      extracting subsets from dictionaries, 170
      getting values from dictionaries, 164
POP servers, authenticating users, 397
POP3 mailbox, inspecting interactively, 503-506
popen module, processes, driving external, 384
popen2 module, capturing output and error streams, 386-388
poplib module, 503
portability of code, 60-62
portalocker.py module, 104
PostgreSQL, storing BLOBs in, 313
predicates, 18
      expanding list items, 157
prime numbers, computing, 669-671
print statement, 422
printf function, 183
printing, database cursor content, 320-323
priority queue, 208
PriorityQueue class, 365
Privacy-enhanced Electronic Mail (PEM), 582
processes, 356
      daemon, forking on Unix-like systems, 388-390
      debugging threads in, 363
      external, driving with popen, 384
      running on Unix-like systems, capturing output and error streams, 386-388
processing
      international text with Unicode, 43-45
      list items in random order, 204
      text, 1-57
            non-ASCII, 43-45
      words in files, 72
procmail, blocking duplicate email messages, 408
programming code, 288
programming languages, state and behavior in, 230
programs about programs, 584-615
progress indicators, providing on text consoles, 424
progressbar class, 425
properties, avoiding boilerplate accessors for, 252
property function, 252
proxies, special method delegation in, 247-250
proxy function, 249
proxy, tunneling SSL through, 516-519
proxying, 248
pseudo-files, getting/parsing contents of, 335
psycopg module, 313
pty module, 392
Py-DBAPI (Python DB Application Programming Interface), 290
PyGTK interface to GTK toolkit, 423
PyGUI API, 423
PyQt, combining GUIs and asynchronous I/O with threads, 443
Pyrex, building C extensions, 623-624
pysqlite module, 322
Python
      as adding machine, 140-143
      benefits of simplicity, 229
      coding extensions in C, 357
      distributions, ActivePython, 326
      extending/embedding, 616-642
      interface for accessing relational databases, 290
            alternatives to, 290
      multithreaded programming, 357
            adding threads to programs, 356
            (see also multithreaded programming)
      OOP features in, 229
      power tools, 740-787
      printf C function in, 183
      programming shortcuts, 146-189
      source code, converting into HTML markup, 598-601
      support for multiple paradigns, 230
      tree of objects, converting XML document into, 471-473
      (see also Python 2.3; Python 2.4)
Python 2.3
      accessing decimal module, 141
      interpolating variables in strings, 35
      string alignment, padding character in, 11
      (see also Python)
Python 2.4
      doctest module, using with unittest, 350
      DSU support, 197
      email messages in, 501-503
      email parser in, 500
      generator expressions, 171
      interpolating variables in strings, 35-38
      string alignment, padding character in, 11
      (see also Python)
Python Database Row Module (db_row), 320
Python DB Application Programming Interface, 290
Python Imaging Library (PIL), 434
Pythonwin toolkit, 423
PyWin32 package, 326, 392
PyXML package, 464

Q[ Top ]
Queue class, 357
      combining GUIs and asynchronous I/O with threads, 439
      coordinating pool of worker threads, 366
      specializing priority values of threads, 364-366
quicksort algorithm, 192, 213
      implementing in three lines of code, 215-217
Quixote, 527

R[ Top ]
race conditions, 376
random module, items with given probabilities, 184
Rankine temperature, converting to other scales, 235
raw_input function, 422
re module
      finding subsequences, 221
      replacing multiple patterns in strings, 39
      string processing, 6
Reactor Design Pattern, 570-573
read method, 60, 489
      objects pickled to file, returning, 297
      reading from files, 63-65
reading
      data from zip files, 77
      data/text in files, 62-65
      Microsoft Outlook contacts, 416-418
      text files, specific line in, 68
      unbuffered characters from standard input, 98
readLines method, 60, 63
ref class, 258
reference cycles, 337
referenceError exception, 258
registry, system administration, 392
regular expressions
      expanding/compressing tabs in strings, 34
      substring substitutions, 38
relational databases, 289
      enterprise software-engineering three-tier system, 289
      hybrid approaches to, 290
      implementations from major software vendors, 289
      implentations of, with ODBC interface, 290
      inappropriate for some applications, 289
      saving/retrieving data with support for selecting/searching, 310
relative paths, computing, 96
Remote Procedure Call (RPC), 558
repeat method, inherited by Subclass from Behave superclass, 233
replace method, 53, 67
_ _repr_ _ method, 252
resource module, 335
rfc822 module, 405
ring buffers, 259-262
rjust method (string objects), 11
rotating calipers algorithm, 686
RPC (Remote Procedure Call), 558
rrule.count method, 120
rstrip method, 12
run method, overriding, 358

S[ Top ]
samplesort algorithm, 192
sanitise function, 501
SAX API, checking XML well-formedness, 465
SAX API (XML parser), 464
SAX parser, merging continuous text events with, 480-483
scalars, 157
sched module, command scheduling, 133
Schwartzian Transform, 197
scripts
      in Windows, running one instance of, 380
      spawning editors from, 401
search paths
      dynamically changing, 94
      finding files in directories, 91-96
searching
      for items in sorted sequence, 211
      searching/replacing text in files, 67
      using dictionaries for, 190
Secure Shell (see SSH)
Secure Socket Layer (SSL), 516
Secure Socket Layer/Transport Layer Security (SSL/TLS), 518
security, multithreaded programming, 356
seek method, 60
      random-access files, 76
select method, 214
select module, 559
      capturing output and error streams from Unix shell command, 386-388
selecting, 190-228
self.something syntax, 231
sequences, 14
      accessing item-by-item, 635-638
      adding items to while preserving sortedness, 206
      finding subsequences in, 220
      flexible access to, 318-320
      items in
            getting first smallest, 208
            selecting nth smallest, 212
      lexicographical comparison of, 190
      looping over items in, 154
      nested, flattening, 157-159
      performing membership tests on, 217-220
      removing duplicates from, 647-653
      sorted, searching for items in, 211
      translating into C array, 631-634
serializing code objects with sincemarshal, 303
serializing data
      marshal module, 291-293
      pickle and cPickle modules, 293-296
serve_forever method, 566
servers, LDAP, 524
servlets, coding with Jython, 542
Set data type, 177
set method, 18
_ _setattr_ _ method, 240, 245
      attribute settings, 237
setdefault method
      adding entries to dictionaries, 165
setdefault method, adding entries to dictionaries, 165
sets module, 97, 177
      finding sets/unions of dictionaries, 177
_ _setstate_ _ method, 255
shebang (#!), 68
shelve module, mutating objects with, 305-307
shortcuts in Python, 146-189
signatures, methods with same, 232
Simple Mail Transfer Protocol (SMTP), 486
Simple Object Access Protocol (SOAP), 559
SimpleXMLRPCServer class, 567
SimpleXMLRPCServer module, 559, 562, 566
Simplified Network Time Protocol (SNTP), 491
sincemarshal module, 303
Singleton Design Pattern, 230, 271
      alternative to, 275
      avoiding with Borg class, 273-277
Singletons, 272
s.isdigit method, 6
slash (/), 58
_ _slots_ _ method
      restricting attribute setting, 241
SMTP (Simple Mail Transfer Protocol), 486
snapshot method, 264
SNTP (Simplified Network Time Protocol), 491
SOAP (Simple Object Access Protocol), 559
socket module, 486, 559
sort method, 190, 192, 214
      lists of strings, 196
sorted function, 197, 215
sorting, 190-228
      current state of, 194
      dictionaries, 195
      history of, in Python, 192
      keys/indices based on corresponding values, 200
      list of strings ignoring case, 196
      lists of objects by object's attribute, 198
      names and separating them by initials, 226
      strings with embedded numbers, 203
_sortkeyfunc function, 227
sound system, on Windows, checking, 410
SPARK parser generator, 587
special methods
      class definitions, 232
      delegating in proxies, 247-250
      operations/built-in functions trying in specific order, 232
split method, 33
      processing words in files, 73
      reading from files, 63
splitext function, 404
splitlines method, 32
      reading from files, 63
SQL
      as emerging database interface standard, 289
      databases, XML representations stored in, 290
      implentations of, 290
SQLite, 290
      storing BLOBs in, 315
sqlite.encode, inserting BLOBs in SQLite databases, 315
SSH (Secure Shell), 582
      performing remote logins using, 579-581
SSL clients, authenticating over HTTPS, 582
SSL (Secure Socket Layer), tunneling through proxy, 516-519
SSL/TLS (Secure Socket Layer/Transport Layer Security), 518
standard input, reading unbuffered characters, 98
standard output
      printing Unicode to, 48
      using printf to output to, 183
start method, 358
State Design Pattern, 269-271
stopwatch, implementing in Tkinter, 437
s.toupper method, 6
Strategy Design Pattern, 270
streams, capturing from Unix shell command, 386-388
strftime function, 111
string module, 7
      string filtering, 23
string-formatting operator (%), 7, 13, 37
StringIO module, 61, 79
strings
      aligning, 11
      checking for balanced parentheses, 604-606
      extracting bytes from, 28
      removing whitespace from, 12
      sorting while ignoring case, 196
      verifying valid numeric format, 590
      with embedding numbers, sorting, 203
      zip files in, 79
      (see also text strings)
strip method, 12
strptime function, 111
strset.translate, 19
struct module, 559
sub method, string substitutions, 38
Subclass class, 233
subclass method, 233
subclass methods, 233
subclassing, 232
      Singletons and, 272
substitute method, 38
substrings, accessing, 28-31
sum function, 121
summing numbers with accuracy, 680
super methods
      performing superclass delegation, 233
superclass methods, 233
superclasses
      calling _ _init_ _ method for, 282-285
      delegation of, 233
      using cooperative, 285-287
SuperMixin class, 287
_ _slots_ _ function, 252
superTuple function, 252
SWIG modules, using in multithreaded environment, 630
Swing, viewing image from URL with, 456
Sybase, 290
synchronizing methods in objects, 359-361
system administration, 391-421
system_profiler command (Mac OS X), 418

T[ Top ]
tabs in strings, expanding/compressing, 32
tar files, compressed, archiving files into, 80
tarfile module, 80
tasks, automatic, checking/modifying on Windows, 412
tell method, 60
      rewinding input files, 87
Telnet, performing remote logins using, 576-579
temperature scales, converting among, 235
tempfile module, 401
Template Method Design Pattern, 226, 233
      queuing, 366
termios module, 98
ternary operator, 666
testing, 332-354
      CGI, 527-530
      exception handling, 337-339
      objects for string-like characteristics, 9
      unit tests
            checking values against, 352-354
            running automatically, 348
            running simply, 346
TestThread class, 363
text, 1-57
      converting HTML documents to, on Unix, 55
      extracting
            from OpenOffice.org files, 101
            from Word files, 102
      parsing, 3
      processing (see text processing)
      reading from files, 62-65
      searching/replacing in files, 67
      sources of, 3
      strings (see text strings)
text consoles, providing progress indicators, 424
text editors, spawning from scripts, 401
text processing, 1-57
      basic operations, 3
      converting characters to Unicode, 8
      by characters, text strings, 7
      (see also text; text strings)
text strings, 4-7
      aligning, 11
      case-insensitive, 52-57
      changing indentation of, 31
      checking
            contents of, 25
            endings of, 41
            for set of characters, 16-19
      converting
            between Unicode and plain, 45
            to lowercase/uppercase, 26
      expanding/compressing tabs in, 32
      filtering for set of characters, 22-25
      interpolating variables in, 35
      performing substitutions on, 38-41
      processing by character, 7
      reversing by words or character, 15
      substrings (see substrings)
      testing for string-like characteristics, 9
      translate method, simplifying usage of, 20
      trimming space from ends of, 12
textHandler class, 468
theobject.something syntax, 231
There's More Than One Way To Do It (TMTOWIDI), 146
Thread class, 358
thread module, 357
thread pools, 366-369
threading module, 357
      synchronization constructs in, 358
threads, 356
      adding to Python programs to enhance performance, 356
      allocating per-thread storage, 374-377
      combining GUIs and asynchronous I/O with, 439-443
      communicating among via Queue class, 364-366
      communicating with, Erland's approach to, 373
      coordinating by message passing, 372-374
      daemon, 358
      GIL, adding to Python programs, 356
      locking, 356
      multiple, reducing data structures accessed by, 357
      multitasking without, 378
      synchronizing, 359-361
      terminating, 362-364
time module, 110-112
time (see date/time)
timedelta module, calculating dates, 116
timedelta module (datetime), 116-119, 121
timeit module, 72
      measuring performance with, 206
Tix extension library, 423
Tkinter applications
      implementing tabbed notebook for, 451-453
      using IDLE tree widget in, 443-445
Tkinter toolkit
      adding drag-and-drop reordering to listbox, 428
      as GUI toolkit, 423
      implementing stopwatch in, 437
Tkinter widgets
      copying geometry methods/options between, 448
      embedding inline GIFs using, 432
      entering accented characters in, 430
      supporting multiple values per row in listbox, 445-448
tkSimpleDialog functions, using default values/bounds with, 427
TMTOWTDI (There's More Than One Way To Do It), 146
tokens, 585
      merging/splitting, 602-603
toy programs, 288
traceback module, 340
traceback.print_exc function, 338
tracebacks
      getting information from while debugging, 342-345
translate method, 19, 20-26
      simplifying usage of, 20
      string filtering, 23
try/except statement, using inside expressions, 185
TTY functions, 392
tty module, 98
TtyFormatter class, 57
tuples, implementing with named items, 250-252
Twisted, 356
two-dimensional points, computing convex hull and diameter, 685-688
type checking, 10
TypeError exception, raised by inspect.getargspec, 284

U[ Top ]
UDP (user datagram protocol), 487
unbound methods, 42
underscore (_), 563
Unicode, 4
      converting
            characters to, 8
            to plain text, 45
      encoding
            error handling in, 50-52
            for XML/HTML, 49
      printing to standard output, 48
      international text processing 43-45
uniform function, 184
unit testing, 333
unit tests
      checking values against intervals, 352-354
      running automatically, 348
      running simply, 346
      using doctest with unittest in Python 2.4, 350
unittest module, using with doctest in Python 2.4, 350
Unix
      converting HTML documents to text on Unix, 55
      line-termination characters, 64
      making executables from scripts, 613-615
      (see also Unix-like systems)
Unix-like systems
      forking daemon processes on, 388-390
      wrapper, 391
unpacking assignment, 698-702
updating random-access files, 75
upgrading class instances on reload, 774-778
upleDescriptor class, 319
upper method, 27
urllib module, 486
urllib2 module, 486
urlopen function, 489
URLs
      getting document from, on Web, 489
      handling in CGI scripts, 530-532
      viewing image from, with Swing and Jython, 456
user accounts, assigning random passwords, 393
user datagram protocol (UDP), 487
user input, getting on Mac OS, 456
user interfaces, 422-462

V[ Top ]
variables
      in strings, interpolating, 35
      module-level (see constants)

W[ Top ]
WCK (Widget Construction Kit), 423
weak references, 256
      to bound methods, 258
weakref module, 256, 258, 337
Web, getting document from URL on, 489
web pages, handling cookies while fetching, 538-541
Web programming, 526-557
web servers, 527
WebWare, 527
whitelists, 406
whitespace, removing from strings, 12
Widget Construction Kit (WCK), 423
Win32 API, multithreading, 381
Win32 applications
      message processing with MsgWaitForMultipleObjects, 381-384
win32api module, 100
win32com package, 416
Windows
      applications message loops, 382
      changing file attributes, 100
      creating share on, 414
      line-termination characters, 64
      login, checking/modifying automatic tasks run at, 412
      making executables with p2exe from scripts, 611
      registering/unregistering DLLs on, 411
      sound system on, checking, 410
      standard output, sending binary data to, 82
      system administration, 392
      using MSHTML to parse XML, 483
Windows DLLs, calling functions from, 627-629
Windows registry, system administration, 392
_winreg module, 392, 413
winsound module, 410
wrapper, 391
write method, 3
      writing to files, 59
writelines method, writing to files, 66
writestr method, reading data from zip files, 78
writing
      callback functions, avoiding lambda in, 426
      to files, 66
wxPython toolkit, 423
      designing notebook widget with panels, 453
wxWidgets C++ library, 423

X[ Top ]
xdrlib module, 559
XML
      accessing structural data in human-readable form, 290
      encoding Unicode for, 49
      using MSHTML to parse, 483
XML documents
      converting into tree of Python objects, 471-473
      counting tags in, 467
      extracting text from, 468
      validating, 477
XML processing, 463-484
      autodetecting XML encoding, 469-471
      checking XML well formedness, 465
      eror handling in, 477
      filtering elements/attributes of namespace, 478-480
      parsing Microsoft Excel XML, 475
      removing whitespace-only text nodes from DOM node subtree, 474
XML tags, counting number of "element"s in XML document, 467
XML validation, 466
XMLFilterBase class, 481
XMLGenerator class, 480
XML-RPC, 464, 558
      enabling remote termination, 566
      method calls to, 561
      serving requests to, 562
      using with Medusa, 564
xmlrpclib module, 559
xml.sax.saxutils module, 481
xproperty function, 253

Z[ Top ]
zip, 167
zip files
      handling inside strings, 79
      reading data from, 77
zipfile module, 77
Z-Object Database (ZODB), 290
ZODB (Z-Object Database), 290
Zope, 527

	

Zurück zu Python Cookbook


Themen

Buchreihen

Special Interest

International Sites

O'Reilly China O'Reilly France O'Reilly USA O'Reilly Japan O'Reilly Taiwan