@@ -4385,6 +4385,324 @@ \section{Generators\label{generators}}
43854385more effort than writing a regular function.
43864386
43874387
4388+
4389+ \chapter {Brief Tour of the Standard Library \label {briefTour } }
4390+
4391+
4392+ \section {Operating System Interface\label {os-interface } }
4393+
4394+ The \ulink {\module {os}}{../lib/module-os.html}
4395+ module provides dozens of functions for interacting with the
4396+ operating system:
4397+
4398+ \begin {verbatim }
4399+ >>> import os
4400+ >>> os.system('copy /data/mydata.fil /backup/mydata.fil')
4401+ 0
4402+ >>> os.getcwd() # Return the current working directory
4403+ 'C:\\Python24'
4404+ >>> os.chdir('/server/accesslogs')
4405+ \end {verbatim }
4406+
4407+ Be sure to use the \samp {import os} style instead of
4408+ \samp {from os import *}. This will keep \function {os.open()} from
4409+ shadowing the builtin \function {open()} function which operates much
4410+ differently.
4411+
4412+ The builtin \function {dir()} and \function {help()} functions are useful
4413+ as interactive aids for working with large modules like \module {os}:
4414+
4415+ \begin {verbatim }
4416+ >>> import os
4417+ >>> dir(os)
4418+ <returns a listi of all module functions>
4419+ >>> help(os)
4420+ <returns an extensive manual page created from the module's docstrings>
4421+ \end {verbatim }
4422+
4423+ For daily file and directory management tasks, the
4424+ \ulink {\module {shutil}}{../lib/module-shutil.html}
4425+ module provides a higher level interface that is easier to use:
4426+
4427+ \begin {verbatim }
4428+ >>> import shutil
4429+ >>> shutil.copyfile('data.db', 'archive.db')
4430+ >>> shutil.move('/build/excecutables', 'installdir')
4431+ \end {verbatim }
4432+
4433+
4434+ \section {File Wildcards\label {file-wildcards } }
4435+
4436+ The \ulink {\module {glob}}{../lib/module-glob.html}
4437+ module provides a function for making file lists from directory
4438+ wildcard searches:
4439+
4440+ \begin {verbatim }
4441+ >>> import glob
4442+ >>> glob.glob('*.py')
4443+ ['primes.py', 'random.py', 'quote.py']
4444+ \end {verbatim }
4445+
4446+
4447+ \section {Command Line Arguments\label {command-line-arguments } }
4448+
4449+ Common utility scripts often invoke processing command line arguments.
4450+ These arguments are stored in the
4451+ \ulink {\module {sys}}{../lib/module-sys.html}\ module's \var {argv}
4452+ attribute as a list. For instance the following output results from
4453+ running \samp {python demo.py one two three} at the command line:
4454+
4455+ \begin {verbatim }
4456+ >>> import sys
4457+ >>> print sys.argv[]
4458+ ['demo.py', 'one', 'two', 'three']
4459+ \end {verbatim }
4460+
4461+ The \ulink {\module {getopt}}{../lib/module-getopt.html}
4462+ module processes \var {sys.argv} using the conventions of the \UNIX {}
4463+ \function {getopt()} function. More powerful and flexible command line
4464+ processing is provided by the
4465+ \ulink {\module {optparse}}{../lib/module-optparse.html} module.
4466+
4467+
4468+ \section {Error Output Redirection and Program Termination\label {stderr } }
4469+
4470+ The \ulink {\module {sys}}{../lib/module-sys.html}
4471+ module also has attributes for \var {stdin}, \var {stdout}, and
4472+ \var {stderr}. The latter is useful for emitting warnings and error
4473+ messages to make them visible even when \var {stdout} has been redirected:
4474+
4475+ \begin {verbatim }
4476+ >>> sys.stderr.write('Warning, log file not found starting a new one')
4477+ Warning, log file not found starting a new one
4478+ \end {verbatim }
4479+
4480+ The most direct way to terminate a script is to use \samp {sys.exit()}.
4481+
4482+
4483+ \section {String Pattern Matching\label {string-pattern-matching } }
4484+
4485+ The \ulink {\module {re}}{../lib/module-re.html}
4486+ module provides regular expression tools for advanced string processing.
4487+ When only simple capabilities are needed, string methods are preferred
4488+ because they are easier to read and debug. However, for more
4489+ sophisticated applications, regular expressions can provide succinct,
4490+ optimized solutions:
4491+
4492+ \begin {verbatim }
4493+ >>> import re
4494+ >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
4495+ ['foot', 'fell', 'fastest']
4496+ >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
4497+ 'cat in the hat'
4498+ \end {verbatim }
4499+
4500+
4501+ \section {Mathematics\label {mathematics } }
4502+
4503+ The \ulink {\module {math}}{../lib/module-math.html} math module gives
4504+ access to the underlying C library functions for floating point math:
4505+
4506+ \begin {verbatim }
4507+ >>> import math
4508+ >>> math.cos(math.pi / 4.0)
4509+ 0.70710678118654757
4510+ >>> math.log(1024, 2)
4511+ 10.0
4512+ \end {verbatim }
4513+
4514+ The \ulink {\module {random}}{../lib/module-random.html}
4515+ module provides tools for making random selections:
4516+
4517+ \begin {verbatim }
4518+ >>> import random
4519+ >>> random.choice(['apple', 'pear', 'banana'])
4520+ 'apple'
4521+ >>> random.sample(xrange(100), 10) # sampling without replacement
4522+ [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
4523+ >>> random.random() # random float
4524+ 0.17970987693706186
4525+ >>> random.randrange(6) # random integer chosen from range(6)
4526+ 4
4527+ \end {verbatim }
4528+
4529+
4530+ \section {Internet Access\label {internet-access } }
4531+
4532+ There are a number of modules for accessing the internet and processing
4533+ internet protocols. Two of the simplest are
4534+ \ulink {\module {urllib2}}{../lib/module-urllib2.html}
4535+ for retrieving data from urls and
4536+ \ulink {\module {smtplib}}{../lib/module-smtplib.html}
4537+ for sending mail:
4538+
4539+ \begin {verbatim }
4540+ >>> import urllib2
4541+ >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
4542+ ... if 'EST' in line: # look for Eastern Standard Time
4543+ ... print line
4544+
4545+ <BR>Nov. 25, 09:43:32 PM EST
4546+
4547+ >>> import smtplib
4548+ >>> server = smtplib.SMTP('localhost')
4549+ 4550+ 4551+ 4552+
4553+ Beware the Ides of March.
4554+ """)
4555+ >>> server.quit()
4556+ \end {verbatim }
4557+
4558+
4559+ \section {Dates and Times\label {dates-and-times } }
4560+
4561+ The \ulink {\module {datetime}}{../lib/module-datetime.html} module
4562+ supplies classes for manipulating dates and times in both simple
4563+ and complex ways. While date and time arithmetic is supported, the
4564+ focus of the implementation is on efficient member extraction for
4565+ output formatting and manipulation. The module also supports objects
4566+ that are time zone aware.
4567+
4568+ \begin {verbatim }
4569+ # dates are easily constructed and formatted
4570+ >>> from datetime import date
4571+ >>> now = date.today()
4572+ >>> now
4573+ datetime.date(2003, 12, 2)
4574+ >>> now.strftime("%m-%d-%y or %d%b %Y is a %A on the %d day of %B")
4575+ '12-02-03 or 02Dec 2003 is a Tuesday on the 02 day of December'
4576+
4577+ # dates support calendar arithmetic
4578+ >>> birthday = date(1964, 7, 31)
4579+ >>> age = now - birthday
4580+ >>> age.days
4581+ 14368
4582+ \end {verbatim }
4583+
4584+
4585+ \section {Data Compression\label {data-compression } }
4586+
4587+ Common data archiving and compression formats are directly supported
4588+ by modules including: \module {zlib}, \module {gzip}, \module {bz2},
4589+ \module {zipfile}, and \module {tar}.
4590+
4591+ \begin {verbatim }
4592+ >>> import zlib
4593+ >>> s = 'witch which has which witches wrist watch'
4594+ >>> len(s)
4595+ 41
4596+ >>> t = zlib.compress(s)
4597+ >>> len(t)
4598+ 37
4599+ >>> zlib.decompress(t)
4600+ 'witch which has which witches wrist watch'
4601+ >>> zlib.crc32(t)
4602+ -1438085031
4603+ \end {verbatim }
4604+
4605+
4606+ \section {Performance Measurement\label {performance-measurement } }
4607+
4608+ Some Python users develop a deep interest in knowing the relative
4609+ performance between different approaches to the same problem.
4610+ Python provides a measurement tool that answers those questions
4611+ immediately.
4612+
4613+ For example, it may be tempting to use the tuple packing and unpacking
4614+ feature instead of the traditional approach to swapping arguments.
4615+ The \ulink {\module {timeit}}{../lib/module-timeit.html} module
4616+ quickly demonstrates that the traditional approach is faster:
4617+
4618+ \begin {verbatim }
4619+ >>> from timeit import Timer
4620+ >>> dir(Timer)
4621+ >>> Timer('t=a; a=b; b=t', 'a=1; b=1').timeit()
4622+ 0.60864915603680925
4623+ >>> Timer('a,b = b,a', 'a=1; b=1').timeit()
4624+ 0.8625194857439773
4625+ \end {verbatim }
4626+
4627+ In contrast to \module {timeit}'s fine level of granularity, the
4628+ \ulink {\module {profile}}{../lib/module-profile.html} and
4629+ \ulink {\module {pstats}}{../lib/module-pstats.html} modules
4630+ provide tools for identifying time critical sections in larger
4631+ blocks of code.
4632+
4633+
4634+ \section {Quality Control\label {quality-control } }
4635+
4636+ One approach for developing high quality software is to write tests for
4637+ each function as it is developed and to run those tests frequently during
4638+ the development process.
4639+
4640+ The \ulink {\module {doctest}}{../lib/module-doctest.html} module provides
4641+ a tool for scanning a module and validating tests embedded in a program's
4642+ docstrings. Test construction is as simple as cutting-and-pasting a
4643+ typical call along with its results into the docstring. This improves
4644+ the documentation by providing the user with an example and it allows the
4645+ doctest module to make sure the code remains true to the documentation:
4646+
4647+ \begin {verbatim }
4648+ def average(values):
4649+ """Computes the arithmetic mean of a list of numbers.
4650+
4651+ >>> print average([20, 30, 70])
4652+ 40.0
4653+ """
4654+ return sum(values, 0.0) / len(values)
4655+
4656+ import doctest
4657+ doctest.testmod() # automatically validate the embedded tests
4658+ \end {verbatim }
4659+
4660+ The \ulink {\module {unittest}}{../lib/module-unittest.html} module is not
4661+ as effortless as the \module {doctest} module, but it allows a more
4662+ comprehensive set of tests to be maintained in a separate file:
4663+
4664+ \begin {verbatim }
4665+ import unittest
4666+
4667+ class TestStatisticalFunctions(unittest.TestCase):
4668+
4669+ def test_average(self):
4670+ self.assertEqual(average([20, 30, 70]), 40.0)
4671+ self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
4672+ self.assertRaises(ZeroDivisionError, average, [])
4673+ self.assertRaises(TypeError, average, 20, 30, 70)
4674+
4675+ unittest.main() # Calling from the command line invokes all tests
4676+ \end {verbatim }
4677+
4678+ \section {Batteries Included\label {batteries-included } }
4679+
4680+ Python has a `` batteries included'' philosophy. The is best seen
4681+ through the sophisticated and robust capabilites of its larger
4682+ packages. For example:
4683+
4684+ * The \module {xmlrpclib} and \module {SimpleXMLRPCServer} modules make
4685+ implementing remote procedure calls into an almost trivial task.
4686+ Despite the names, no direct knowledge or handling of XML is needed.
4687+
4688+ * The \module {email} package is a library for managing email messages,
4689+ including MIME and other RFC 2822-based message documents. Unlike
4690+ \module {smtplib} and \module {poplib} which actually send and receive
4691+ messages, the email package has a complete toolset for building or
4692+ decoding complex message structures (including attachments)
4693+ and for implementing internet encoding and header protocols.
4694+
4695+ * The \module {xml.dom} and \module {xml.sax} packages provide robust
4696+ support for parsing this popular data interchange format. Likewise,
4697+ the \module {csv} module supports direct reads and writes in a common
4698+ database format. Together, these modules and packages greatly simplify
4699+ data interchange between python applications and other tools.
4700+
4701+ * Internationalization is supported by a number of modules including
4702+ \module {gettext}, \module {locale}, and the \module {codecs} package.
4703+
4704+
4705+
43884706\chapter {What Now? \label {whatNow } }
43894707
43904708Reading this tutorial has probably reinforced your interest in using
0 commit comments