Python3 Standard Library Overview
Operating System Interface
os module provides a number of functions related to the operating system linked.
>>> import os >>> os.getcwd() # 返回当前的工作目录 'C:\\Python34' >>> os.chdir('/server/accesslogs') # 修改当前的工作目录 >>> os.system('mkdir today') # 执行系统命令 mkdir 0
We recommend the use of "import os" style instead of "from os import *". This ensures that with the operating system vary in different os.open () does not override the built-in function open ().
When you use os such a large module built-in dir () and help () functions are useful:
>>> import os >>> 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,: mod: shutil module provides a high-level interface that is easier to use:
>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') >>> shutil.move('/build/executables', 'installdir')
glob module provides a function for making file lists from directory wildcard searches:
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py']
Command line parameters
Common utility scripts often invoke the command line parameters. These command-line arguments as a list stored in the argv variable sys module. You can get the following output example, after the implementation of "python demo.py one two three" at the command line:
>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three']
Error Output Redirection and Program Termination
sys, and also stdin, stdout and stderr properties, even when stdout has been redirected, the latter can also be used to display warnings and error messages.
>>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one
Most scripts are directed to terminate the use of "sys.exit ()".
Regular string match
re for advanced string processing module provides regular expression tools. For complex matching and manipulation, regular expressions offer succinct, optimized solutions:
>>> import re >>> 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'
If you only need a simple function, you should first consider the string method, since they are easier to read and debug:
>>> 'tea for too'.replace('too', 'two') 'tea for two'
floating point math module provides access to the underlying C library:
>>> import math >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0
random provides tools for generating random numbers.
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4
There are several modules for accessing the internet and processing internet protocols. Two of the simplest is to process the received data from urls and smtplib urllib.request for sending e-mail:
>>> from urllib.request import urlopen >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... line = line.decode('utf-8') # Decoding the binary data to text. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print(line) <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('email@example.com', 'firstname.lastname@example.org', ... """To: email@example.com ... From: firstname.lastname@example.org ... ... Beware the Ides of March. ... """) >>> server.quit()
Note that the second example requires a local mail server have running.
Date and Time
datetime module for the date and times in both simple and complex ways.
Support date and time arithmetic, while focusing on the realization of more efficient processing and formatting output.
The module also supports time-zone processor:
>>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.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.days 14368
The following modules directly support common data archiving and compression formats: zlib, gzip, bz2, zipfile, and tarfile.
>>> import zlib >>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979
Performance of different methods for some users to understand the same problem among very interested. Python provides a measurement tool that provides direct answers to these questions.
For example, use the tuple packing and unpacking exchange element looks better than using traditional methods to more attractive, timeit modern approach proved faster.
>>> from timeit import Timer >>> 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
With respect timeit fine-grained,: mod: profile and pstats module provides a measure of time for larger blocks of code tool.
One way is to develop high-quality software development and testing of each function code, and in the development process often tested
doctest module provides a tool for scanning a module and program embedded in the document string test is performed in accordance with.
Test construction is as simple as its output cut and pasted into the document string.
By way of example provided by the user, it reinforces the document, allowing doctest module to make sure the code remains true to the documentation:
def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest doctest.testmod() # 自动验证嵌入测试
Unlike doctest module unittest module so easy to use, but it can provide a more comprehensive set of tests in a separate file:
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