Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v8plus / html / python / tut / node12.html
CommitLineData
920dae64
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="tut.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="tut.html" title='Python Tutorial' />
8<link rel='contents' href='node2.html' title="Contents" />
9<link rel='index' href='node19.html' title='Index' />
10<link rel='last' href='about.html' title='About this document...' />
11<link rel='help' href='about.html' title='About this document...' />
12<link rel="next" href="node13.html" />
13<link rel="prev" href="node11.html" />
14<link rel="parent" href="tut.html" />
15<link rel="next" href="node13.html" />
16<meta name='aesop' content='information' />
17<title>10. Brief Tour of the Standard Library </title>
18</head>
19<body>
20<DIV CLASS="navigation">
21<div id='top-navigation-panel' xml:id='top-navigation-panel'>
22<table align="center" width="100%" cellpadding="0" cellspacing="2">
23<tr>
24<td class='online-navigation'><a rel="prev" title="9. Classes"
25 href="node11.html"><img src='../icons/previous.png'
26 border='0' height='32' alt='Previous Page' width='32' /></A></td>
27<td class='online-navigation'><a rel="parent" title="Python Tutorial"
28 href="tut.html"><img src='../icons/up.png'
29 border='0' height='32' alt='Up One Level' width='32' /></A></td>
30<td class='online-navigation'><a rel="next" title="11. Brief Tour of"
31 href="node13.html"><img src='../icons/next.png'
32 border='0' height='32' alt='Next Page' width='32' /></A></td>
33<td align="center" width="100%">Python Tutorial</td>
34<td class='online-navigation'><a rel="contents" title="Table of Contents"
35 href="node2.html"><img src='../icons/contents.png'
36 border='0' height='32' alt='Contents' width='32' /></A></td>
37<td class='online-navigation'><img src='../icons/blank.png'
38 border='0' height='32' alt='' width='32' /></td>
39<td class='online-navigation'><a rel="index" title="Index"
40 href="node19.html"><img src='../icons/index.png'
41 border='0' height='32' alt='Index' width='32' /></A></td>
42</tr></table>
43<div class='online-navigation'>
44<b class="navlabel">Previous:</b>
45<a class="sectref" rel="prev" href="node11.html">9. Classes</A>
46<b class="navlabel">Up:</b>
47<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
48<b class="navlabel">Next:</b>
49<a class="sectref" rel="next" href="node13.html">11. Brief Tour of</A>
50</div>
51<hr /></div>
52</DIV>
53<!--End of Navigation Panel-->
54<div class='online-navigation'>
55<!--Table of Child-Links-->
56<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
57
58<UL CLASS="ChildLinks">
59<LI><A href="node12.html#SECTION0012100000000000000000">10.1 Operating System Interface</a>
60<LI><A href="node12.html#SECTION0012200000000000000000">10.2 File Wildcards</a>
61<LI><A href="node12.html#SECTION0012300000000000000000">10.3 Command Line Arguments</a>
62<LI><A href="node12.html#SECTION0012400000000000000000">10.4 Error Output Redirection and Program Termination</a>
63<LI><A href="node12.html#SECTION0012500000000000000000">10.5 String Pattern Matching</a>
64<LI><A href="node12.html#SECTION0012600000000000000000">10.6 Mathematics</a>
65<LI><A href="node12.html#SECTION0012700000000000000000">10.7 Internet Access</a>
66<LI><A href="node12.html#SECTION0012800000000000000000">10.8 Dates and Times</a>
67<LI><A href="node12.html#SECTION0012900000000000000000">10.9 Data Compression</a>
68<LI><A href="node12.html#SECTION00121000000000000000000">10.10 Performance Measurement</a>
69<LI><A href="node12.html#SECTION00121100000000000000000">10.11 Quality Control</a>
70<LI><A href="node12.html#SECTION00121200000000000000000">10.12 Batteries Included</a>
71</ul>
72<!--End of Table of Child-Links-->
73</div>
74<HR>
75
76<H1><A NAME="SECTION0012000000000000000000"></A><A NAME="briefTour"></A>
77<BR>
7810. Brief Tour of the Standard Library
79</H1>
80
81<P>
82
83<H1><A NAME="SECTION0012100000000000000000"></A><A NAME="os-interface"></A>
84<BR>
8510.1 Operating System Interface
86</H1>
87
88<P>
89The <a class="ulink" href="../lib/module-os.html"
90 ><tt class="module">os</tt></a>
91module provides dozens of functions for interacting with the
92operating system:
93
94<P>
95<div class="verbatim"><pre>
96&gt;&gt;&gt; import os
97&gt;&gt;&gt; os.system('time 0:02')
980
99&gt;&gt;&gt; os.getcwd() # Return the current working directory
100'C:\\Python24'
101&gt;&gt;&gt; os.chdir('/server/accesslogs')
102</pre></div>
103
104<P>
105Be sure to use the "<tt class="samp">import os</tt>" style instead of
106"<tt class="samp">from os import *</tt>". This will keep <tt class="function">os.open()</tt> from
107shadowing the builtin <tt class="function">open()</tt> function which operates much
108differently.
109
110<P>
111<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
112as interactive aids for working with large modules like <tt class="module">os</tt>:
113
114<P>
115<div class="verbatim"><pre>
116&gt;&gt;&gt; import os
117&gt;&gt;&gt; dir(os)
118&lt;returns a list of all module functions&gt;
119&gt;&gt;&gt; help(os)
120&lt;returns an extensive manual page created from the module's docstrings&gt;
121</pre></div>
122
123<P>
124For daily file and directory management tasks, the
125<a class="ulink" href="../lib/module-shutil.html"
126 ><tt class="module">shutil</tt></a>
127module provides a higher level interface that is easier to use:
128
129<P>
130<div class="verbatim"><pre>
131&gt;&gt;&gt; import shutil
132&gt;&gt;&gt; shutil.copyfile('data.db', 'archive.db')
133&gt;&gt;&gt; shutil.move('/build/executables', 'installdir')
134</pre></div>
135
136<P>
137
138<H1><A NAME="SECTION0012200000000000000000"></A><A NAME="file-wildcards"></A>
139<BR>
14010.2 File Wildcards
141</H1>
142
143<P>
144The <a class="ulink" href="../lib/module-glob.html"
145 ><tt class="module">glob</tt></a>
146module provides a function for making file lists from directory
147wildcard searches:
148
149<P>
150<div class="verbatim"><pre>
151&gt;&gt;&gt; import glob
152&gt;&gt;&gt; glob.glob('*.py')
153['primes.py', 'random.py', 'quote.py']
154</pre></div>
155
156<P>
157
158<H1><A NAME="SECTION0012300000000000000000"></A><A NAME="command-line-arguments"></A>
159<BR>
16010.3 Command Line Arguments
161</H1>
162
163<P>
164Common utility scripts often need to process command line arguments.
165These arguments are stored in the
166<a class="ulink" href="../lib/module-sys.html"
167 ><tt class="module">sys</tt></a> module's <var>argv</var>
168attribute as a list. For instance the following output results from
169running "<tt class="samp">python demo.py one two three</tt>" at the command line:
170
171<P>
172<div class="verbatim"><pre>
173&gt;&gt;&gt; import sys
174&gt;&gt;&gt; print sys.argv
175['demo.py', 'one', 'two', 'three']
176</pre></div>
177
178<P>
179The <a class="ulink" href="../lib/module-getopt.html"
180 ><tt class="module">getopt</tt></a>
181module processes <var>sys.argv</var> using the conventions of the <span class="Unix">Unix</span>
182<tt class="function">getopt()</tt> function. More powerful and flexible command line
183processing is provided by the
184<a class="ulink" href="../lib/module-optparse.html"
185 ><tt class="module">optparse</tt></a> module.
186
187<P>
188
189<H1><A NAME="SECTION0012400000000000000000"></A><A NAME="stderr"></A>
190<BR>
19110.4 Error Output Redirection and Program Termination
192</H1>
193
194<P>
195The <a class="ulink" href="../lib/module-sys.html"
196 ><tt class="module">sys</tt></a>
197module also has attributes for <var>stdin</var>, <var>stdout</var>, and
198<var>stderr</var>. The latter is useful for emitting warnings and error
199messages to make them visible even when <var>stdout</var> has been redirected:
200
201<P>
202<div class="verbatim"><pre>
203&gt;&gt;&gt; sys.stderr.write('Warning, log file not found starting a new one\n')
204Warning, log file not found starting a new one
205</pre></div>
206
207<P>
208The most direct way to terminate a script is to use "<tt class="samp">sys.exit()</tt>".
209
210<P>
211
212<H1><A NAME="SECTION0012500000000000000000"></A><A NAME="string-pattern-matching"></A>
213<BR>
21410.5 String Pattern Matching
215</H1>
216
217<P>
218The <a class="ulink" href="../lib/module-re.html"
219 ><tt class="module">re</tt></a>
220module provides regular expression tools for advanced string processing.
221For complex matching and manipulation, regular expressions offer succinct,
222optimized solutions:
223
224<P>
225<div class="verbatim"><pre>
226&gt;&gt;&gt; import re
227&gt;&gt;&gt; re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
228['foot', 'fell', 'fastest']
229&gt;&gt;&gt; re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
230'cat in the hat'
231</pre></div>
232
233<P>
234When only simple capabilities are needed, string methods are preferred
235because they are easier to read and debug:
236
237<P>
238<div class="verbatim"><pre>
239&gt;&gt;&gt; 'tea for too'.replace('too', 'two')
240'tea for two'
241</pre></div>
242
243<P>
244
245<H1><A NAME="SECTION0012600000000000000000"></A><A NAME="mathematics"></A>
246<BR>
24710.6 Mathematics
248</H1>
249
250<P>
251The <a class="ulink" href="../lib/module-math.html"
252 ><tt class="module">math</tt></a> module gives
253access to the underlying C library functions for floating point math:
254
255<P>
256<div class="verbatim"><pre>
257&gt;&gt;&gt; import math
258&gt;&gt;&gt; math.cos(math.pi / 4.0)
2590.70710678118654757
260&gt;&gt;&gt; math.log(1024, 2)
26110.0
262</pre></div>
263
264<P>
265The <a class="ulink" href="../lib/module-random.html"
266 ><tt class="module">random</tt></a>
267module provides tools for making random selections:
268
269<P>
270<div class="verbatim"><pre>
271&gt;&gt;&gt; import random
272&gt;&gt;&gt; random.choice(['apple', 'pear', 'banana'])
273'apple'
274&gt;&gt;&gt; random.sample(xrange(100), 10) # sampling without replacement
275[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
276&gt;&gt;&gt; random.random() # random float
2770.17970987693706186
278&gt;&gt;&gt; random.randrange(6) # random integer chosen from range(6)
2794
280</pre></div>
281
282<P>
283
284<H1><A NAME="SECTION0012700000000000000000"></A><A NAME="internet-access"></A>
285<BR>
28610.7 Internet Access
287</H1>
288
289<P>
290There are a number of modules for accessing the internet and processing
291internet protocols. Two of the simplest are
292<a class="ulink" href="../lib/module-urllib2.html"
293 ><tt class="module">urllib2</tt></a>
294for retrieving data from urls and
295<a class="ulink" href="../lib/module-smtplib.html"
296 ><tt class="module">smtplib</tt></a>
297for sending mail:
298
299<P>
300<div class="verbatim"><pre>
301&gt;&gt;&gt; import urllib2
302&gt;&gt;&gt; for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
303... if 'EST' in line: # look for Eastern Standard Time
304... print line
305
306&lt;BR&gt;Nov. 25, 09:43:32 PM EST
307
308&gt;&gt;&gt; import smtplib
309&gt;&gt;&gt; server = smtplib.SMTP('localhost')
310&gt;&gt;&gt; server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
311"""To: jcaesar@example.org
312From: soothsayer@example.org
313
314Beware the Ides of March.
315""")
316&gt;&gt;&gt; server.quit()
317</pre></div>
318
319<P>
320
321<H1><A NAME="SECTION0012800000000000000000"></A><A NAME="dates-and-times"></A>
322<BR>
32310.8 Dates and Times
324</H1>
325
326<P>
327The <a class="ulink" href="../lib/module-datetime.html"
328 ><tt class="module">datetime</tt></a> module
329supplies classes for manipulating dates and times in both simple
330and complex ways. While date and time arithmetic is supported, the
331focus of the implementation is on efficient member extraction for
332output formatting and manipulation. The module also supports objects
333that are time zone aware.
334
335<P>
336<div class="verbatim"><pre>
337# dates are easily constructed and formatted
338&gt;&gt;&gt; from datetime import date
339&gt;&gt;&gt; now = date.today()
340&gt;&gt;&gt; now
341datetime.date(2003, 12, 2)
342&gt;&gt;&gt; now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
343'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
344
345# dates support calendar arithmetic
346&gt;&gt;&gt; birthday = date(1964, 7, 31)
347&gt;&gt;&gt; age = now - birthday
348&gt;&gt;&gt; age.days
34914368
350</pre></div>
351
352<P>
353
354<H1><A NAME="SECTION0012900000000000000000"></A><A NAME="data-compression"></A>
355<BR>
35610.9 Data Compression
357</H1>
358
359<P>
360Common data archiving and compression formats are directly supported
361by modules including:
362<a class="ulink" href="../lib/module-zlib.html"
363 ><tt class="module">zlib</tt></a>,
364<a class="ulink" href="../lib/module-gzip.html"
365 ><tt class="module">gzip</tt></a>,
366<a class="ulink" href="../lib/module-bz2.html"
367 ><tt class="module">bz2</tt></a>,
368<a class="ulink" href="../lib/module-zipfile.html"
369 ><tt class="module">zipfile</tt></a>, and
370<a class="ulink" href="../lib/module-tarfile.html"
371 ><tt class="module">tarfile</tt></a>.
372
373<P>
374<div class="verbatim"><pre>
375&gt;&gt;&gt; import zlib
376&gt;&gt;&gt; s = 'witch which has which witches wrist watch'
377&gt;&gt;&gt; len(s)
37841
379&gt;&gt;&gt; t = zlib.compress(s)
380&gt;&gt;&gt; len(t)
38137
382&gt;&gt;&gt; zlib.decompress(t)
383'witch which has which witches wrist watch'
384&gt;&gt;&gt; zlib.crc32(s)
385226805979
386</pre></div>
387
388<P>
389
390<H1><A NAME="SECTION00121000000000000000000"></A><A NAME="performance-measurement"></A>
391<BR>
39210.10 Performance Measurement
393</H1>
394
395<P>
396Some Python users develop a deep interest in knowing the relative
397performance of different approaches to the same problem.
398Python provides a measurement tool that answers those questions
399immediately.
400
401<P>
402For example, it may be tempting to use the tuple packing and unpacking
403feature instead of the traditional approach to swapping arguments.
404The <a class="ulink" href="../lib/module-timeit.html"
405 ><tt class="module">timeit</tt></a> module
406quickly demonstrates a modest performance advantage:
407
408<P>
409<div class="verbatim"><pre>
410&gt;&gt;&gt; from timeit import Timer
411&gt;&gt;&gt; Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
4120.57535828626024577
413&gt;&gt;&gt; Timer('a,b = b,a', 'a=1; b=2').timeit()
4140.54962537085770791
415</pre></div>
416
417<P>
418In contrast to <tt class="module">timeit</tt>'s fine level of granularity, the
419<a class="ulink" href="../lib/module-profile.html"
420 ><tt class="module">profile</tt></a> and <tt class="module">pstats</tt>
421modules provide tools for identifying time critical sections in larger blocks
422of code.
423
424<P>
425
426<H1><A NAME="SECTION00121100000000000000000"></A><A NAME="quality-control"></A>
427<BR>
42810.11 Quality Control
429</H1>
430
431<P>
432One approach for developing high quality software is to write tests for
433each function as it is developed and to run those tests frequently during
434the development process.
435
436<P>
437The <a class="ulink" href="../lib/module-doctest.html"
438 ><tt class="module">doctest</tt></a> module provides
439a tool for scanning a module and validating tests embedded in a program's
440docstrings. Test construction is as simple as cutting-and-pasting a
441typical call along with its results into the docstring. This improves
442the documentation by providing the user with an example and it allows the
443doctest module to make sure the code remains true to the documentation:
444
445<P>
446<div class="verbatim"><pre>
447def average(values):
448 """Computes the arithmetic mean of a list of numbers.
449
450 &gt;&gt;&gt; print average([20, 30, 70])
451 40.0
452 """
453 return sum(values, 0.0) / len(values)
454
455import doctest
456doctest.testmod() # automatically validate the embedded tests
457</pre></div>
458
459<P>
460The <a class="ulink" href="../lib/module-unittest.html"
461 ><tt class="module">unittest</tt></a> module is not
462as effortless as the <tt class="module">doctest</tt> module, but it allows a more
463comprehensive set of tests to be maintained in a separate file:
464
465<P>
466<div class="verbatim"><pre>
467import unittest
468
469class TestStatisticalFunctions(unittest.TestCase):
470
471 def test_average(self):
472 self.assertEqual(average([20, 30, 70]), 40.0)
473 self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
474 self.assertRaises(ZeroDivisionError, average, [])
475 self.assertRaises(TypeError, average, 20, 30, 70)
476
477unittest.main() # Calling from the command line invokes all tests
478</pre></div>
479
480<P>
481
482<H1><A NAME="SECTION00121200000000000000000"></A><A NAME="batteries-included"></A>
483<BR>
48410.12 Batteries Included
485</H1>
486
487<P>
488Python has a ``batteries included'' philosophy. This is best seen
489through the sophisticated and robust capabilities of its larger
490packages. For example:
491
492<P>
493
494<UL>
495<LI>The <a class="ulink" href="../lib/module-xmlrpclib.html"
496 ><tt class="module">xmlrpclib</tt></a> and
497 <a class="ulink" href="../lib/module-SimpleXMLRPCServer.html"
498 ><tt class="module">SimpleXMLRPCServer</tt></a>
499 modules make implementing remote procedure calls into an almost trivial task.
500 Despite the names, no direct knowledge or handling of XML is needed.
501</LI>
502<LI>The <a class="ulink" href="../lib/module-email.html"
503 ><tt class="module">email</tt></a> package is a library
504 for managing email messages, including MIME and other RFC 2822-based message
505 documents. Unlike <tt class="module">smtplib</tt> and <tt class="module">poplib</tt> which actually send
506 and receive messages, the email package has a complete toolset for building
507 or decoding complex message structures (including attachments) and for
508 implementing internet encoding and header protocols.
509</LI>
510<LI>The <a class="ulink" href="../lib/module-xml.dom.html"
511 ><tt class="module">xml.dom</tt></a> and
512 <a class="ulink" href="../lib/module-xml.sax.html"
513 ><tt class="module">xml.sax</tt></a> packages provide robust
514 support for parsing this popular data interchange format. Likewise, the
515 <a class="ulink" href="../lib/module-csv.html"
516 ><tt class="module">csv</tt></a> module supports direct reads and
517 writes in a common database format. Together, these modules and packages
518 greatly simplify data interchange between python applications and other
519 tools.
520</LI>
521<LI>Internationalization is supported by a number of modules including
522 <a class="ulink" href="../lib/module-gettext.html"
523 ><tt class="module">gettext</tt></a>,
524 <a class="ulink" href="../lib/module-locale.html"
525 ><tt class="module">locale</tt></a>, and the
526 <a class="ulink" href="../lib/module-codecs.html"
527 ><tt class="module">codecs</tt></a> package.
528</LI>
529</UL>
530
531<P>
532
533<DIV CLASS="navigation">
534<div class='online-navigation'>
535<p></p><hr />
536<table align="center" width="100%" cellpadding="0" cellspacing="2">
537<tr>
538<td class='online-navigation'><a rel="prev" title="9. Classes"
539 href="node11.html"><img src='../icons/previous.png'
540 border='0' height='32' alt='Previous Page' width='32' /></A></td>
541<td class='online-navigation'><a rel="parent" title="Python Tutorial"
542 href="tut.html"><img src='../icons/up.png'
543 border='0' height='32' alt='Up One Level' width='32' /></A></td>
544<td class='online-navigation'><a rel="next" title="11. Brief Tour of"
545 href="node13.html"><img src='../icons/next.png'
546 border='0' height='32' alt='Next Page' width='32' /></A></td>
547<td align="center" width="100%">Python Tutorial</td>
548<td class='online-navigation'><a rel="contents" title="Table of Contents"
549 href="node2.html"><img src='../icons/contents.png'
550 border='0' height='32' alt='Contents' width='32' /></A></td>
551<td class='online-navigation'><img src='../icons/blank.png'
552 border='0' height='32' alt='' width='32' /></td>
553<td class='online-navigation'><a rel="index" title="Index"
554 href="node19.html"><img src='../icons/index.png'
555 border='0' height='32' alt='Index' width='32' /></A></td>
556</tr></table>
557<div class='online-navigation'>
558<b class="navlabel">Previous:</b>
559<a class="sectref" rel="prev" href="node11.html">9. Classes</A>
560<b class="navlabel">Up:</b>
561<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
562<b class="navlabel">Next:</b>
563<a class="sectref" rel="next" href="node13.html">11. Brief Tour of</A>
564</div>
565</div>
566<hr />
567<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
568</DIV>
569<!--End of Navigation Panel-->
570<ADDRESS>
571See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
572</ADDRESS>
573</BODY>
574</HTML>