rest25/tutorial/stdlib.rst => rest262/tutorial/stdlib.rst
5**********************************
6
7
8.. _tut-os-interface:
9
10Operating System Interface
11==========================
12
n13-The :mod:`os` (XXX reference: ../lib/module-os.html) module provides dozens of
n13+The :mod:`os` module provides dozens of functions for interacting with the
14-functions for interacting with the operating system::
14+operating system::
15
16   >>> import os
17   >>> os.system('time 0:02')
18   0
19   >>> os.getcwd()      # Return the current working directory
n20-   'C:\\Python24'
n20+   'C:\\Python26'
21   >>> os.chdir('/server/accesslogs')
22
23Be sure to use the ``import os`` style instead of ``from os import *``.  This
24will keep :func:`os.open` from shadowing the builtin :func:`open` function which
25operates much differently.
26
27.. index:: builtin: help
28
30aids for working with large modules like :mod:`os`::
31
32   >>> import os
33   >>> dir(os)
34   <returns a list of all module functions>
35   >>> help(os)
36   <returns an extensive manual page created from the module's docstrings>
37
n38-For daily file and directory management tasks, the  :mod:`shutil` (XXX
n38+For daily file and directory management tasks, the :mod:`shutil` module provides
39-reference: ../lib/module-shutil.html) module provides a higher level interface
39+a higher level interface that is easier to use::
40-that is easier to use::
41
42   >>> import shutil
43   >>> shutil.copyfile('data.db', 'archive.db')
44   >>> shutil.move('/build/executables', 'installdir')
45
46
47.. _tut-file-wildcards:
48
49File Wildcards
50==============
51
n52-The :mod:`glob` (XXX reference: ../lib/module-glob.html) module provides a
n51+The :mod:`glob` module provides a function for making file lists from directory
53-function for making file lists from directory wildcard searches::
52+wildcard searches::
54
55   >>> import glob
56   >>> glob.glob('*.py')
57   ['primes.py', 'random.py', 'quote.py']
58
59
60.. _tut-command-line-arguments:
61
62Command Line Arguments
63======================
64
65Common utility scripts often need to process command line arguments. These
n66-arguments are stored in the :mod:`sys` (XXX reference: ../lib/module-sys.html)
n65+arguments are stored in the :mod:`sys` module's *argv* attribute as a list.  For
67-module's *argv* attribute as a list.  For instance the following output results
66+instance the following output results from running ``python demo.py one two
68-from running ``python demo.py one two three`` at the command line::
67+three`` at the command line::
69
70   >>> import sys
71   >>> print sys.argv
72   ['demo.py', 'one', 'two', 'three']
73
n74-The :mod:`getopt` (XXX reference: ../lib/module-getopt.html) module processes
n73+The :mod:`getopt` module processes *sys.argv* using the conventions of the Unix
75-*sys.argv* using the conventions of the Unix :func:`getopt` function.  More
74+:func:`getopt` function.  More powerful and flexible command line processing is
76-powerful and flexible command line processing is provided by the :mod:`optparse`
75+provided by the :mod:`optparse` module.
77-(XXX reference: ../lib/module-optparse.html) module.
78
79
80.. _tut-stderr:
81
82Error Output Redirection and Program Termination
83================================================
84
n85-The :mod:`sys` (XXX reference: ../lib/module-sys.html) module also has
n83+The :mod:`sys` module also has attributes for *stdin*, *stdout*, and *stderr*.
86-attributes for *stdin*, *stdout*, and *stderr*.  The latter is useful for
84+The latter is useful for emitting warnings and error messages to make them
87-emitting warnings and error messages to make them visible even when *stdout* has
85+visible even when *stdout* has been redirected::
88-been redirected::
89
90   >>> sys.stderr.write('Warning, log file not found starting a new one\n')
91   Warning, log file not found starting a new one
92
93The most direct way to terminate a script is to use ``sys.exit()``.
94
95
96.. _tut-string-pattern-matching:
97
98String Pattern Matching
99=======================
100
n101-The :mod:`re` (XXX reference: ../lib/module-re.html) module provides regular
n98+The :mod:`re` module provides regular expression tools for advanced string
102-expression tools for advanced string processing. For complex matching and
99+processing. For complex matching and manipulation, regular expressions offer
103-manipulation, regular expressions offer succinct, optimized solutions::
100+succinct, optimized solutions::
104
105   >>> import re
106   >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
107   ['foot', 'fell', 'fastest']
108   >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
109   'cat in the hat'
110
111When only simple capabilities are needed, string methods are preferred because
115   'tea for two'
116
117
118.. _tut-mathematics:
119
120Mathematics
121===========
122
n123-The :mod:`math` (XXX reference: ../lib/module-math.html) module gives access to
n120+The :mod:`math` module gives access to the underlying C library functions for
124-the underlying C library functions for floating point math::
121+floating point math::
125
126   >>> import math
127   >>> math.cos(math.pi / 4.0)
128   0.70710678118654757
129   >>> math.log(1024, 2)
130   10.0
131
n132-The :mod:`random` (XXX reference: ../lib/module-random.html) module provides
n129+The :mod:`random` module provides tools for making random selections::
133-tools for making random selections::
134
135   >>> import random
136   >>> random.choice(['apple', 'pear', 'banana'])
137   'apple'
138   >>> random.sample(xrange(100), 10)   # sampling without replacement
139   [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
140   >>> random.random()    # random float
141   0.17970987693706186
142   >>> random.randrange(6)    # random integer chosen from range(6)
n143-   4   
n139+   4
144
145
146.. _tut-internet-access:
147
148Internet Access
149===============
150
151There are a number of modules for accessing the internet and processing internet
n152-protocols. Two of the simplest are :mod:`urllib2` (XXX reference: ../lib/module-
n148+protocols. Two of the simplest are :mod:`urllib2` for retrieving data from urls
153-urllib2.html) for retrieving data from urls and :mod:`smtplib` (XXX reference:
149+and :mod:`smtplib` for sending mail::
154-../lib/module-smtplib.html)  for sending mail::
155
156   >>> import urllib2
157   >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
158   ...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time
159   ...         print line
160
161   <BR>Nov. 25, 09:43:32 PM EST
162
163   >>> import smtplib
164   >>> server = smtplib.SMTP('localhost')
165   >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
n166-   """To: jcaesar@example.org
n161+   ... """To: jcaesar@example.org
167-   From: soothsayer@example.org
162+   ... From: soothsayer@example.org
168- 
163+   ...
169-   Beware the Ides of March.
164+   ... Beware the Ides of March.
170-   """)
165+   ... """)
171   >>> server.quit()
n167+ 
168+(Note that the second example needs a mailserver running on localhost.)
172
173
174.. _tut-dates-and-times:
175
176Dates and Times
177===============
178
n179-The :mod:`datetime` (XXX reference: ../lib/module-datetime.html) module supplies
n176+The :mod:`datetime` module supplies classes for manipulating dates and times in
180-classes for manipulating dates and times in both simple and complex ways. While
177+both simple and complex ways. While date and time arithmetic is supported, the
181-date and time arithmetic is supported, the focus of the implementation is on
178+focus of the implementation is on efficient member extraction for output
182-efficient member extraction for output formatting and manipulation.  The module
179+formatting and manipulation.  The module also supports objects that are timezone
183-also supports objects that are timezone aware. ::
180+aware. ::
184
185   # dates are easily constructed and formatted
186   >>> from datetime import date
187   >>> now = date.today()
188   >>> now
189   datetime.date(2003, 12, 2)
190   >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
191   '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
198
199
200.. _tut-data-compression:
201
202Data Compression
203================
204
205Common data archiving and compression formats are directly supported by modules
n206-including: :mod:`zlib` (XXX reference: ../lib/module-zlib.html), :mod:`gzip`
n203+including: :mod:`zlib`, :mod:`gzip`, :mod:`bz2`, :mod:`zipfile` and
207-(XXX reference: ../lib/module-gzip.html), :mod:`bz2` (XXX reference: ../lib
204+:mod:`tarfile`. ::
208-/module-bz2.html), :mod:`zipfile` (XXX reference: ../lib/module-zipfile.html),
209-and :mod:`tarfile` (XXX reference: ../lib/module-tarfile.html). ::
210
211   >>> import zlib
212   >>> s = 'witch which has which witches wrist watch'
213   >>> len(s)
214   41
215   >>> t = zlib.compress(s)
216   >>> len(t)
217   37
227=======================
228
229Some Python users develop a deep interest in knowing the relative performance of
230different approaches to the same problem. Python provides a measurement tool
231that answers those questions immediately.
232
233For example, it may be tempting to use the tuple packing and unpacking feature
234instead of the traditional approach to swapping arguments. The :mod:`timeit`
n235-(XXX reference: ../lib/module-timeit.html) module quickly demonstrates a modest
n230+module quickly demonstrates a modest performance advantage::
236-performance advantage::
237
238   >>> from timeit import Timer
239   >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
240   0.57535828626024577
241   >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
242   0.54962537085770791
243
n244-In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile`
n238+In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile` and
245-(XXX reference: ../lib/module-profile.html) and :mod:`pstats` modules provide
239+:mod:`pstats` modules provide tools for identifying time critical sections in
246-tools for identifying time critical sections in larger blocks of code.
240+larger blocks of code.
247
248
249.. _tut-quality-control:
250
251Quality Control
252===============
253
254One approach for developing high quality software is to write tests for each
255function as it is developed and to run those tests frequently during the
256development process.
257
n258-The :mod:`doctest` (XXX reference: ../lib/module-doctest.html) module provides a
n252+The :mod:`doctest` module provides a tool for scanning a module and validating
259-tool for scanning a module and validating tests embedded in a program's
253+tests embedded in a program's docstrings.  Test construction is as simple as
260-docstrings.  Test construction is as simple as cutting-and-pasting a typical
254+cutting-and-pasting a typical call along with its results into the docstring.
261-call along with its results into the docstring.  This improves the documentation
255+This improves the documentation by providing the user with an example and it
262-by providing the user with an example and it allows the doctest module to make
256+allows the doctest module to make sure the code remains true to the
263-sure the code remains true to the documentation::
257+documentation::
264
265   def average(values):
266       """Computes the arithmetic mean of a list of numbers.
267
268       >>> print average([20, 30, 70])
269       40.0
270       """
271       return sum(values, 0.0) / len(values)
272
273   import doctest
274   doctest.testmod()   # automatically validate the embedded tests
275
n276-The :mod:`unittest` (XXX reference: ../lib/module-unittest.html) module is not
n270+The :mod:`unittest` module is not as effortless as the :mod:`doctest` module,
277-as effortless as the :mod:`doctest` module, but it allows a more comprehensive
271+but it allows a more comprehensive set of tests to be maintained in a separate
278-set of tests to be maintained in a separate file::
272+file::
279
280   import unittest
281
282   class TestStatisticalFunctions(unittest.TestCase):
283
284       def test_average(self):
285           self.assertEqual(average([20, 30, 70]), 40.0)
286           self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
293.. _tut-batteries-included:
294
295Batteries Included
296==================
297
298Python has a "batteries included" philosophy.  This is best seen through the
299sophisticated and robust capabilities of its larger packages. For example:
300
n301-* The :mod:`xmlrpclib` (XXX reference: ../lib/module-xmlrpclib.html) and
n295+* The :mod:`xmlrpclib` and :mod:`SimpleXMLRPCServer` modules make implementing
302-  :mod:`SimpleXMLRPCServer` (XXX reference: ../lib/module-SimpleXMLRPCServer.html)
296+  remote procedure calls into an almost trivial task.  Despite the modules
303-  modules make implementing remote procedure calls into an almost trivial task.
304-  Despite the modules names, no direct knowledge or handling of XML is needed.
297+  names, no direct knowledge or handling of XML is needed.
305
n306-* The :mod:`email` (XXX reference: ../lib/module-email.html) package is a
n299+* The :mod:`email` package is a library for managing email messages, including
307-  library for managing email messages, including MIME and other RFC 2822-based
300+  MIME and other RFC 2822-based message documents. Unlike :mod:`smtplib` and
308-  message documents. Unlike :mod:`smtplib` and :mod:`poplib` which actually send
301+  :mod:`poplib` which actually send and receive messages, the email package has
309-  and receive messages, the email package has a complete toolset for building or
302+  a complete toolset for building or decoding complex message structures
310-  decoding complex message structures (including attachments) and for implementing
303+  (including attachments) and for implementing internet encoding and header
311-  internet encoding and header protocols.
304+  protocols.
312
n313-* The :mod:`xml.dom` (XXX reference: ../lib/module-xml.dom.html) and
n306+* The :mod:`xml.dom` and :mod:`xml.sax` packages provide robust support for
314-  :mod:`xml.sax` (XXX reference: ../lib/module-xml.sax.html) packages provide
315-  robust support for parsing this popular data interchange format. Likewise, the
307+  parsing this popular data interchange format. Likewise, the :mod:`csv` module
316-  :mod:`csv` (XXX reference: ../lib/module-csv.html) module supports direct reads
308+  supports direct reads and writes in a common database format. Together, these
317-  and writes in a common database format. Together, these modules and packages
309+  modules and packages greatly simplify data interchange between python
318-  greatly simplify data interchange between python applications and other tools.
310+  applications and other tools.
319
320* Internationalization is supported by a number of modules including
t321-  :mod:`gettext` (XXX reference: ../lib/module-gettext.html), :mod:`locale` (XXX
t313+  :mod:`gettext`, :mod:`locale`, and the :mod:`codecs` package.
322-  reference: ../lib/module-locale.html), and the :mod:`codecs` (XXX reference:
323-  ../lib/module-codecs.html) package.
324
325
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op