Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / amd64 / html / python / tut / node12.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="tut.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python Documentation Index' />
<link rel="first" href="tut.html" title='Python Tutorial' />
<link rel='contents' href='node2.html' title="Contents" />
<link rel='index' href='node19.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="node13.html" />
<link rel="prev" href="node11.html" />
<link rel="parent" href="tut.html" />
<link rel="next" href="node13.html" />
<meta name='aesop' content='information' />
<title>10. Brief Tour of the Standard Library </title>
</head>
<body>
<DIV CLASS="navigation">
<div id='top-navigation-panel' xml:id='top-navigation-panel'>
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="9. Classes"
href="node11.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="11. Brief Tour of"
href="node13.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node11.html">9. Classes</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node13.html">11. Brief Tour of</A>
</div>
<hr /></div>
</DIV>
<!--End of Navigation Panel-->
<div class='online-navigation'>
<!--Table of Child-Links-->
<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
<UL CLASS="ChildLinks">
<LI><A href="node12.html#SECTION0012100000000000000000">10.1 Operating System Interface</a>
<LI><A href="node12.html#SECTION0012200000000000000000">10.2 File Wildcards</a>
<LI><A href="node12.html#SECTION0012300000000000000000">10.3 Command Line Arguments</a>
<LI><A href="node12.html#SECTION0012400000000000000000">10.4 Error Output Redirection and Program Termination</a>
<LI><A href="node12.html#SECTION0012500000000000000000">10.5 String Pattern Matching</a>
<LI><A href="node12.html#SECTION0012600000000000000000">10.6 Mathematics</a>
<LI><A href="node12.html#SECTION0012700000000000000000">10.7 Internet Access</a>
<LI><A href="node12.html#SECTION0012800000000000000000">10.8 Dates and Times</a>
<LI><A href="node12.html#SECTION0012900000000000000000">10.9 Data Compression</a>
<LI><A href="node12.html#SECTION00121000000000000000000">10.10 Performance Measurement</a>
<LI><A href="node12.html#SECTION00121100000000000000000">10.11 Quality Control</a>
<LI><A href="node12.html#SECTION00121200000000000000000">10.12 Batteries Included</a>
</ul>
<!--End of Table of Child-Links-->
</div>
<HR>
<H1><A NAME="SECTION0012000000000000000000"></A><A NAME="briefTour"></A>
<BR>
10. Brief Tour of the Standard Library
</H1>
<P>
<H1><A NAME="SECTION0012100000000000000000"></A><A NAME="os-interface"></A>
<BR>
10.1 Operating System Interface
</H1>
<P>
The <a class="ulink" href="../lib/module-os.html"
><tt class="module">os</tt></a>
module provides dozens of functions for interacting with the
operating system:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import os
&gt;&gt;&gt; os.system('time 0:02')
0
&gt;&gt;&gt; os.getcwd() # Return the current working directory
'C:\\Python24'
&gt;&gt;&gt; os.chdir('/server/accesslogs')
</pre></div>
<P>
Be sure to use the "<tt class="samp">import os</tt>" style instead of
"<tt class="samp">from os import *</tt>". This will keep <tt class="function">os.open()</tt> from
shadowing the builtin <tt class="function">open()</tt> function which operates much
differently.
<P>
<a id='l2h-34' xml:id='l2h-34'></a>The builtin <tt class="function">dir()</tt> and <tt class="function">help()</tt> functions are useful
as interactive aids for working with large modules like <tt class="module">os</tt>:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import os
&gt;&gt;&gt; dir(os)
&lt;returns a list of all module functions&gt;
&gt;&gt;&gt; help(os)
&lt;returns an extensive manual page created from the module's docstrings&gt;
</pre></div>
<P>
For daily file and directory management tasks, the
<a class="ulink" href="../lib/module-shutil.html"
><tt class="module">shutil</tt></a>
module provides a higher level interface that is easier to use:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import shutil
&gt;&gt;&gt; shutil.copyfile('data.db', 'archive.db')
&gt;&gt;&gt; shutil.move('/build/executables', 'installdir')
</pre></div>
<P>
<H1><A NAME="SECTION0012200000000000000000"></A><A NAME="file-wildcards"></A>
<BR>
10.2 File Wildcards
</H1>
<P>
The <a class="ulink" href="../lib/module-glob.html"
><tt class="module">glob</tt></a>
module provides a function for making file lists from directory
wildcard searches:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import glob
&gt;&gt;&gt; glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
</pre></div>
<P>
<H1><A NAME="SECTION0012300000000000000000"></A><A NAME="command-line-arguments"></A>
<BR>
10.3 Command Line Arguments
</H1>
<P>
Common utility scripts often need to process command line arguments.
These arguments are stored in the
<a class="ulink" href="../lib/module-sys.html"
><tt class="module">sys</tt></a> module's <var>argv</var>
attribute as a list. For instance the following output results from
running "<tt class="samp">python demo.py one two three</tt>" at the command line:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import sys
&gt;&gt;&gt; print sys.argv
['demo.py', 'one', 'two', 'three']
</pre></div>
<P>
The <a class="ulink" href="../lib/module-getopt.html"
><tt class="module">getopt</tt></a>
module processes <var>sys.argv</var> using the conventions of the <span class="Unix">Unix</span>
<tt class="function">getopt()</tt> function. More powerful and flexible command line
processing is provided by the
<a class="ulink" href="../lib/module-optparse.html"
><tt class="module">optparse</tt></a> module.
<P>
<H1><A NAME="SECTION0012400000000000000000"></A><A NAME="stderr"></A>
<BR>
10.4 Error Output Redirection and Program Termination
</H1>
<P>
The <a class="ulink" href="../lib/module-sys.html"
><tt class="module">sys</tt></a>
module also has attributes for <var>stdin</var>, <var>stdout</var>, and
<var>stderr</var>. The latter is useful for emitting warnings and error
messages to make them visible even when <var>stdout</var> has been redirected:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one
</pre></div>
<P>
The most direct way to terminate a script is to use "<tt class="samp">sys.exit()</tt>".
<P>
<H1><A NAME="SECTION0012500000000000000000"></A><A NAME="string-pattern-matching"></A>
<BR>
10.5 String Pattern Matching
</H1>
<P>
The <a class="ulink" href="../lib/module-re.html"
><tt class="module">re</tt></a>
module provides regular expression tools for advanced string processing.
For complex matching and manipulation, regular expressions offer succinct,
optimized solutions:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import re
&gt;&gt;&gt; re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
&gt;&gt;&gt; re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
</pre></div>
<P>
When only simple capabilities are needed, string methods are preferred
because they are easier to read and debug:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; 'tea for too'.replace('too', 'two')
'tea for two'
</pre></div>
<P>
<H1><A NAME="SECTION0012600000000000000000"></A><A NAME="mathematics"></A>
<BR>
10.6 Mathematics
</H1>
<P>
The <a class="ulink" href="../lib/module-math.html"
><tt class="module">math</tt></a> module gives
access to the underlying C library functions for floating point math:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import math
&gt;&gt;&gt; math.cos(math.pi / 4.0)
0.70710678118654757
&gt;&gt;&gt; math.log(1024, 2)
10.0
</pre></div>
<P>
The <a class="ulink" href="../lib/module-random.html"
><tt class="module">random</tt></a>
module provides tools for making random selections:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import random
&gt;&gt;&gt; random.choice(['apple', 'pear', 'banana'])
'apple'
&gt;&gt;&gt; random.sample(xrange(100), 10) # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
&gt;&gt;&gt; random.random() # random float
0.17970987693706186
&gt;&gt;&gt; random.randrange(6) # random integer chosen from range(6)
4
</pre></div>
<P>
<H1><A NAME="SECTION0012700000000000000000"></A><A NAME="internet-access"></A>
<BR>
10.7 Internet Access
</H1>
<P>
There are a number of modules for accessing the internet and processing
internet protocols. Two of the simplest are
<a class="ulink" href="../lib/module-urllib2.html"
><tt class="module">urllib2</tt></a>
for retrieving data from urls and
<a class="ulink" href="../lib/module-smtplib.html"
><tt class="module">smtplib</tt></a>
for sending mail:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import urllib2
&gt;&gt;&gt; for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
... if 'EST' in line: # look for Eastern Standard Time
... print line
&lt;BR&gt;Nov. 25, 09:43:32 PM EST
&gt;&gt;&gt; import smtplib
&gt;&gt;&gt; server = smtplib.SMTP('localhost')
&gt;&gt;&gt; server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org
Beware the Ides of March.
""")
&gt;&gt;&gt; server.quit()
</pre></div>
<P>
<H1><A NAME="SECTION0012800000000000000000"></A><A NAME="dates-and-times"></A>
<BR>
10.8 Dates and Times
</H1>
<P>
The <a class="ulink" href="../lib/module-datetime.html"
><tt class="module">datetime</tt></a> module
supplies classes for manipulating dates and times in both simple
and complex ways. While date and time arithmetic is supported, the
focus of the implementation is on efficient member extraction for
output formatting and manipulation. The module also supports objects
that are time zone aware.
<P>
<div class="verbatim"><pre>
# dates are easily constructed and formatted
&gt;&gt;&gt; from datetime import date
&gt;&gt;&gt; now = date.today()
&gt;&gt;&gt; now
datetime.date(2003, 12, 2)
&gt;&gt;&gt; now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
# dates support calendar arithmetic
&gt;&gt;&gt; birthday = date(1964, 7, 31)
&gt;&gt;&gt; age = now - birthday
&gt;&gt;&gt; age.days
14368
</pre></div>
<P>
<H1><A NAME="SECTION0012900000000000000000"></A><A NAME="data-compression"></A>
<BR>
10.9 Data Compression
</H1>
<P>
Common data archiving and compression formats are directly supported
by modules including:
<a class="ulink" href="../lib/module-zlib.html"
><tt class="module">zlib</tt></a>,
<a class="ulink" href="../lib/module-gzip.html"
><tt class="module">gzip</tt></a>,
<a class="ulink" href="../lib/module-bz2.html"
><tt class="module">bz2</tt></a>,
<a class="ulink" href="../lib/module-zipfile.html"
><tt class="module">zipfile</tt></a>, and
<a class="ulink" href="../lib/module-tarfile.html"
><tt class="module">tarfile</tt></a>.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; import zlib
&gt;&gt;&gt; s = 'witch which has which witches wrist watch'
&gt;&gt;&gt; len(s)
41
&gt;&gt;&gt; t = zlib.compress(s)
&gt;&gt;&gt; len(t)
37
&gt;&gt;&gt; zlib.decompress(t)
'witch which has which witches wrist watch'
&gt;&gt;&gt; zlib.crc32(s)
226805979
</pre></div>
<P>
<H1><A NAME="SECTION00121000000000000000000"></A><A NAME="performance-measurement"></A>
<BR>
10.10 Performance Measurement
</H1>
<P>
Some Python users develop a deep interest in knowing the relative
performance of different approaches to the same problem.
Python provides a measurement tool that answers those questions
immediately.
<P>
For example, it may be tempting to use the tuple packing and unpacking
feature instead of the traditional approach to swapping arguments.
The <a class="ulink" href="../lib/module-timeit.html"
><tt class="module">timeit</tt></a> module
quickly demonstrates a modest performance advantage:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; from timeit import Timer
&gt;&gt;&gt; Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
&gt;&gt;&gt; Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
</pre></div>
<P>
In contrast to <tt class="module">timeit</tt>'s fine level of granularity, the
<a class="ulink" href="../lib/module-profile.html"
><tt class="module">profile</tt></a> and <tt class="module">pstats</tt>
modules provide tools for identifying time critical sections in larger blocks
of code.
<P>
<H1><A NAME="SECTION00121100000000000000000"></A><A NAME="quality-control"></A>
<BR>
10.11 Quality Control
</H1>
<P>
One approach for developing high quality software is to write tests for
each function as it is developed and to run those tests frequently during
the development process.
<P>
The <a class="ulink" href="../lib/module-doctest.html"
><tt class="module">doctest</tt></a> module provides
a tool for scanning a module and validating tests embedded in a program's
docstrings. Test construction is as simple as cutting-and-pasting a
typical call along with its results into the docstring. This improves
the documentation by providing the user with an example and it allows the
doctest module to make sure the code remains true to the documentation:
<P>
<div class="verbatim"><pre>
def average(values):
"""Computes the arithmetic mean of a list of numbers.
&gt;&gt;&gt; print average([20, 30, 70])
40.0
"""
return sum(values, 0.0) / len(values)
import doctest
doctest.testmod() # automatically validate the embedded tests
</pre></div>
<P>
The <a class="ulink" href="../lib/module-unittest.html"
><tt class="module">unittest</tt></a> module is not
as effortless as the <tt class="module">doctest</tt> module, but it allows a more
comprehensive set of tests to be maintained in a separate file:
<P>
<div class="verbatim"><pre>
import unittest
class TestStatisticalFunctions(unittest.TestCase):
def test_average(self):
self.assertEqual(average([20, 30, 70]), 40.0)
self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
self.assertRaises(ZeroDivisionError, average, [])
self.assertRaises(TypeError, average, 20, 30, 70)
unittest.main() # Calling from the command line invokes all tests
</pre></div>
<P>
<H1><A NAME="SECTION00121200000000000000000"></A><A NAME="batteries-included"></A>
<BR>
10.12 Batteries Included
</H1>
<P>
Python has a ``batteries included'' philosophy. This is best seen
through the sophisticated and robust capabilities of its larger
packages. For example:
<P>
<UL>
<LI>The <a class="ulink" href="../lib/module-xmlrpclib.html"
><tt class="module">xmlrpclib</tt></a> and
<a class="ulink" href="../lib/module-SimpleXMLRPCServer.html"
><tt class="module">SimpleXMLRPCServer</tt></a>
modules make implementing remote procedure calls into an almost trivial task.
Despite the names, no direct knowledge or handling of XML is needed.
</LI>
<LI>The <a class="ulink" href="../lib/module-email.html"
><tt class="module">email</tt></a> package is a library
for managing email messages, including MIME and other RFC 2822-based message
documents. Unlike <tt class="module">smtplib</tt> and <tt class="module">poplib</tt> which actually send
and receive messages, the email package has a complete toolset for building
or decoding complex message structures (including attachments) and for
implementing internet encoding and header protocols.
</LI>
<LI>The <a class="ulink" href="../lib/module-xml.dom.html"
><tt class="module">xml.dom</tt></a> and
<a class="ulink" href="../lib/module-xml.sax.html"
><tt class="module">xml.sax</tt></a> packages provide robust
support for parsing this popular data interchange format. Likewise, the
<a class="ulink" href="../lib/module-csv.html"
><tt class="module">csv</tt></a> module supports direct reads and
writes in a common database format. Together, these modules and packages
greatly simplify data interchange between python applications and other
tools.
</LI>
<LI>Internationalization is supported by a number of modules including
<a class="ulink" href="../lib/module-gettext.html"
><tt class="module">gettext</tt></a>,
<a class="ulink" href="../lib/module-locale.html"
><tt class="module">locale</tt></a>, and the
<a class="ulink" href="../lib/module-codecs.html"
><tt class="module">codecs</tt></a> package.
</LI>
</UL>
<P>
<DIV CLASS="navigation">
<div class='online-navigation'>
<p></p><hr />
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="9. Classes"
href="node11.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="11. Brief Tour of"
href="node13.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node11.html">9. Classes</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node13.html">11. Brief Tour of</A>
</div>
</div>
<hr />
<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
</DIV>
<!--End of Navigation Panel-->
<ADDRESS>
See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
</ADDRESS>
</BODY>
</HTML>