10 Python standard library concise tutorial Table of Contents
- 1. Operating System Interface
- 2. File wildcards
- 3. Command Line Parameters
- 4. Error output redirection and program termination
- 5 String Matching
- 6. Mathematics
- 7. Internet access
- 8. Date and Time
- 9. Data Compression
- 10 Performance Measurement
- 11 Quality Control
1. Operating System Interface
OSThe module provides a series of modules for interacting with the system:
>>> os.getcwd() # Return the current working directory'/home/minix/Documents/Note/Programming/python/lib1'>>> os.chdir('~/python') # Change current working directoryTraceback (most recent call last): File "<stdin>", line 1, in <module>OSError: [Errno 2] No such file or directory: '~/python'>>> os.chdir('/home/minix/python') # Change current working directory>>> os.system('mkdir tos')0>>> os.system('ls')classes errorAexception learnPython pythonInterpretercontrolFlow informalIntroduction lib1 tosdataStructure io modules0
Note:
- Use import OS instead of from OS import *. Otherwise, OS. open () will overwrite the built-in open () function.
- The path must be fully written ~
ShutilThe module provides easy-to-use interfaces to facilitate daily file management.
>>> os.system('touch data.db')0>>> os.system('ls')data.db0>>> import shutil>>> shutil.copy('data.db', 'archive.db')>>> os.system('ls')archive.db data.db0
2. File wildcards
GlobThe module provides the following methods to obtain a list of file names using wildcards:
>>> os.system ('ls')archive.db data.db foo.cpp0>>> import glob>>> glob.glob('*.db')['archive.db', 'data.db']
3. Command Line Parameters
Parameters are usually provided to a script. These parameters can be obtained through the argv attribute of the SYS module.
#demo.pyimport sysprint sys.argv
In this way, the command line will get:
$ python demo.py one two three['demo.py', 'one', 'two', 'three']
GeroptThe module uses the getopt () function of UNIX to process SYS. argv. More powerful and flexible command line processing methods can be found in the argparse module.
4. Error output redirection and program termination
SysThe module also provides three attributes: stdin, stdout, and stderr. stderr can display errors and warnings when stdout is redirected.
>>> import sys>>> sys.stderr.write('Warning, long file not found\n')Warning, long file not found
The most direct way to end a script is to use SYS. Exit ()
5 String Matching
ReThe module provides regular expression tools for advanced string processing. For some complex matching operations, Regular Expressions generally provide the optimal solution:
>>> re.sub(r'(\b[a-z]+) \l', r'\l', 'cat in the the hat hat')'cat in the the hat hat'
The string method is the best when you only need some simple functions, because they are easy to read and debug.
>>> 'tea for too'.replace('too', 'two')'tea for two'
6. Mathematics
MathThe module provides the ability to access floating point processing functions in the underlying C function library:
>>> import math>>> math.cos(math.pi / 4.0)0.7071067811865476>>> math.log(1024, 2)10.0
RandomThe module provides a tool for random selection.
>>> import random>>> random.choice(['apple', 'pear', 'banana'])'banana'>>> random.choice(['apple', 'pear', 'banana'])'apple'>>> random.choice(['apple', 'pear', 'banana'])'apple'>>> random.sample(xrange(100), 10)[37, 22, 82, 76, 51, 58, 33, 92, 56, 48]>>> random.sample(xrange(100), 10)[13, 44, 15, 70, 69, 42, 17, 0, 14, 81]>>> random.random()0.4976690748939975>>> random.random()0.10626734770387691>>> random.randrange(10)6>>> random.randrange(10)9
7. Internet access
Python has a series of modules used to access the Internet and process the Internet protocol. The simplest of them is urllib2 and smtplib. The former is used to receive data from URLs, and the latter can send emails.
8. Date and Time
DatatimeThe module provides a series of classes for processing dates and times, from simple to complex.
>>> from datetime import date>>> now = date.today()>>> nowdatetime.date(2013, 3, 7)>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")'03-07-13. 07 Mar 2013 is a Thursday on the 07 day of March.'>>> birthday = date(1964, 7, 31)>>> age = now - birthday>>> age.days17751
9. Data Compression
Common data packaging and compression formats are directly supported by python in the following modules: zlib, Gzip, bz2, zipfile, and tarfile.
>>> import zlib>>> str = "we repeat repeat and repeat many time">>> len(str)37>>> t = zlib.compress(str)>>> len(t)32>>> zlib.decompress(t)'we repeat repeat and repeat many time'
10 Performance Measurement
Some Python users need to compare the performance of different methods to solve the same problem. Python provides corresponding measurement tools to quickly draw conclusions.
>>> from timeit import Timer>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()0.05308699607849121>>> Timer('a,b = b,a', 'a=1; b=2').timeit()0.042800188064575195
Compared with timeit, the profile and pstat modules provide a series of tools to identify the time of key areas in a large segment of code.
11 Quality Control
One way to develop high-quality software is to write test programs for each function during development and run them multiple times.DoctestThe module provides a tool to scan a module and verify the test embedded in the docstring program. the embedded test code structure is very simple, just like copying and pasting the output results to the test code.
def average(values): """ Computes the arithmetic mean of a list of numbers. >>> print average([20,30,70]) 40.0 """ return sum(values, 0,0) / len(values+1)import doctestdoctest.testmod()
UnittestModules are not similarDoctestThe module looks like a breeze, but it can be written in a separate file for more complex testing.
import unittestclass 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
Link: http://docs.python.org/2/tutorial/stdlib.html