Theos module provides dozens of functions for interacting with theoperating system:
>>>importos>>>os.system('time 0:02')0>>>os.getcwd()# Return the current working directory'C:\\Python26'>>>os.chdir('/server/accesslogs')
Be sure to use theimportos style instead offromosimport*. Thiswill keepos.open() from shadowing the builtinopen() function whichoperates much differently.
The builtindir() andhelp() functions are useful as interactiveaids for working with large modules likeos:
>>>importos>>>dir(os)<returns a list of all module functions>>>>help(os)<returns an extensive manual page created from the module's docstrings>
For daily file and directory management tasks, theshutil module providesa higher level interface that is easier to use:
>>>importshutil>>>shutil.copyfile('data.db','archive.db')>>>shutil.move('/build/executables','installdir')
Theglob module provides a function for making file lists from directorywildcard searches:
>>>importglob>>>glob.glob('*.py')['primes.py', 'random.py', 'quote.py']
Common utility scripts often need to process command line arguments. Thesearguments are stored in thesys module’sargv attribute as a list. Forinstance the following output results from runningpythondemo.pyonetwothree at the command line:
>>>importsys>>>printsys.argv['demo.py', 'one', 'two', 'three']
Thegetopt module processessys.argv using the conventions of the Unixgetopt() function. More powerful and flexible command line processing isprovided by theoptparse module.
Thesys module also has attributes forstdin,stdout, andstderr.The latter is useful for emitting warnings and error messages to make themvisible even whenstdout has been redirected:
>>>sys.stderr.write('Warning, log file not found starting a new one\n')Warning, log file not found starting a new one
The most direct way to terminate a script is to usesys.exit().
There module provides regular expression tools for advanced stringprocessing. For complex matching and manipulation, regular expressions offersuccinct, optimized solutions:
>>>importre>>>re.findall(r'\bf[a-z]*','which foot or hand fell fastest')['foot', 'fell', 'fastest']>>>re.sub(r'(\b[a-z]+) \1',r'\1','cat in the the hat')'cat in the hat'
When only simple capabilities are needed, string methods are preferred becausethey are easier to read and debug:
>>>'tea for too'.replace('too','two')'tea for two'
Themath module gives access to the underlying C library functions forfloating point math:
>>>importmath>>>math.cos(math.pi/4.0)0.70710678118654757>>>math.log(1024,2)10.0
Therandom module provides tools for making random selections:
>>>importrandom>>>random.choice(['apple','pear','banana'])'apple'>>>random.sample(xrange(100),10)# sampling without replacement[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]>>>random.random()# random float0.17970987693706186>>>random.randrange(6)# random integer chosen from range(6)4
There are a number of modules for accessing the internet and processing internetprotocols. Two of the simplest areurllib2 for retrieving data from urlsandsmtplib for sending mail:
>>>importurllib2>>>forlineinurllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):...if'EST'inlineor'EDT'inline:# look for Eastern Time...printline<BR>Nov. 25, 09:43:32 PM EST>>>importsmtplib>>>server=smtplib.SMTP('localhost')>>>server.sendmail('soothsayer@example.org','jcaesar@example.org',..."""To: jcaesar@example.org...From: soothsayer@example.org......BewaretheIdesofMarch....""")>>>server.quit()
(Note that the second example needs a mailserver running on localhost.)
Thedatetime module supplies classes for manipulating dates and times inboth simple and complex ways. While date and time arithmetic is supported, thefocus of the implementation is on efficient member extraction for outputformatting and manipulation. The module also supports objects that are timezoneaware.
# dates are easily constructed and formatted>>> from datetime import date>>> now = date.today()>>> nowdatetime.date(2003, 12, 2)>>> 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>>> birthday = date(1964, 7, 31)>>> age = now - birthday>>> age.days14368Common data archiving and compression formats are directly supported by modulesincluding:zlib,gzip,bz2,zipfile andtarfile.
>>>importzlib>>>s='witch which has which witches wrist watch'>>>len(s)41>>>t=zlib.compress(s)>>>len(t)37>>>zlib.decompress(t)'witch which has which witches wrist watch'>>>zlib.crc32(s)226805979
Some Python users develop a deep interest in knowing the relative performance ofdifferent approaches to the same problem. Python provides a measurement toolthat answers those questions immediately.
For example, it may be tempting to use the tuple packing and unpacking featureinstead of the traditional approach to swapping arguments. Thetimeitmodule quickly demonstrates a modest performance advantage:
>>>fromtimeitimportTimer>>>Timer('t=a; a=b; b=t','a=1; b=2').timeit()0.57535828626024577>>>Timer('a,b = b,a','a=1; b=2').timeit()0.54962537085770791
In contrast totimeit‘s fine level of granularity, theprofile andpstats modules provide tools for identifying time critical sections inlarger blocks of code.
One approach for developing high quality software is to write tests for eachfunction as it is developed and to run those tests frequently during thedevelopment process.
Thedoctest module provides a tool for scanning a module and validatingtests embedded in a program’s docstrings. Test construction is as simple ascutting-and-pasting a typical call along with its results into the docstring.This improves the documentation by providing the user with an example and itallows the doctest module to make sure the code remains true to thedocumentation:
defaverage(values):"""Computes the arithmetic mean of a list of numbers. >>> print average([20, 30, 70]) 40.0 """returnsum(values,0.0)/len(values)importdoctestdoctest.testmod()# automatically validate the embedded tests
Theunittest module is not as effortless as thedoctest module,but it allows a more comprehensive set of tests to be maintained in a separatefile:
importunittestclassTestStatisticalFunctions(unittest.TestCase):deftest_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
Python has a “batteries included” philosophy. This is best seen through thesophisticated and robust capabilities of its larger packages. For example:
Brief Tour of the Standard Library – Part II