10 标准库简介
10.1 操作系统接口(Operating System Interface)
os
模块提供了许多和操作系统交互的函数:
>>> import os >>> os.getcwd() # Return the current working directory 'C:\\Python34' >>> os.chdir('/server/accesslogs') # Change current working directory >>> os.system('mkdir today') # Run the command mkdir in the system shell 0
请确保使用import os
风格的模块导入,而不是from os import *
。这是为了保证os.open()和内建的open()函数互不影响,它们操作有很大差别。
在使用像os这样的大型模块时,内建的dir()和help()函数是很有用的交互式助手:
>>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive manual page created from the module's docstrings>
处理日常的文件、目录管理任务时,shutil
模块提供了易用的高层接口:
>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') 'archive.db' >>> shutil.move('/build/executables', 'installdir') 'installdir'
10.2 文件通配符(File Wildcards)
glob
模块提供了一个根据文件通配符查找文件列表的函数:
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py']
10.3 命令行参数(Command Line Arguments)
通用的工具脚本通常都需要处理命令行的参数。这些参数作为list存储在sys模块中的argv属性中。例如,下面输出在命令行中运行python demo.py one two three
后的结果:
>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three']
getopt模块使用方便的Unix函数getopt()处理sys.argv。argparse模块提供了更加强大、灵活的命令行处理。
10.4 错误输出重定向和程序终止
sys模块还有stdin,stdout和stderr等属性。后者在发送警告、错误消息时时很有用的,即使stdout已经重定向了它们(错误消息)也可以被看到:
>>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one
终止脚本最直接的方式是使用sys.exit()
。
10.5 字符串模式匹配
re
模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和操作,正则表达式提供了简洁、有效的方案:
>>> 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'
只需要简单功能的时侯,使用string的方法更合适,因为它们可读性更高,debug也方便:
>>> 'tea for too'.replace('too', 'two') 'tea for two'
10.6 数学
在处理浮点运算时,math
模块提供了对底层C函数库的访问:
>>> import math >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0
random
模块提供了随机选择的功能:
>>> 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
SciPy项目http://scipy.org中还有很多数学计算方面的其他模块。
10.7 互联网访问
有很多模块可以访问互联网,处理网络协议。最简单的两个是urllib.request
用来从URL中接受数据,和smtplib
用来发送邮件:
>>> 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('soothsayer@example.org', 'jcaesar@example.org', ... """To: jcaesar@example.org ... From: soothsayer@example.org ... ... Beware the Ides of March. ... """) >>> server.quit()
(注意,第二个例子需要在localhost上运行邮件服务器。)
10.8 日期和时间
datetime
模块提供了简单和复杂的处理日期和时间两种的方法。虽然日期和时间是支持运算的,但实现的重点是在格式化输出和操作时能够高效的提取成员。该模块还支持时区处理:
>>> # 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
10.9 数据压缩
常用的数据归档和压缩格式都是由以下模块直接支持的:zlib, gzip, bz2, lzma, zipfile和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
10.10 性能度量(Performance Measurement)
一些Python用户,对解决相同问题的不同方式的性能差别很感兴趣。Python提供了一个度量工具,可以立即解决这个问题。
例如,可能尝试用元组的打包和解包特性来代替传统的参数交换。timeit模块可以快速展示出适度的性能优势(原文:The timeit module quickly demonstrates a modest performance advantage):
>>> 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
相对于timeit的细粒度,profile和pstats模块提供了在更大的代码块中识别关键部分的工具。
10.11 质量控制(Quality Control)
开发高质量软件的一个方法是,在每个函数开发完成后为它编写测试,并且在开发过程中经常运行这些测试。
doctest
模块提供了一个工具,它可以扫描一个模块,验证嵌入在程序docstring中的测试。测试结构和将一个典型的调用和它的结果复制粘贴到docstring一样简单。这种方式提高了文档的作用,它为用户提供一个使用的例子,还可以让doctest模块确定当前代码和这份文档是一致的:
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() # automatically validate the embedded tests
unittest
模块就不像doctest
模块这么简单了,但是它允许在一个单独的文件中进行更全面的测试:
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) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main() # Calling from the command line invokes all tests
10.12 自备电池(Batteries Included)
Python有一个“自备电池”的哲学。这通过它的大型包的复杂性和鲁棒性就可以看出来。例如:
xmlrpc.client
和xmlrpc.server
模块使执行远程过程调用成一个几乎微不足道的任务。尽管名字是这样,但没有直接处理XML或需要这方面的知识。email
包是一个管理邮件消息的库,包括MIME和其它基于RFC 2822的消息文档。它不像smtplib和poplib会实际进行收发消息的操作,email包有一个完整的构建或者解码复杂消息结构的工具包(包括附件),用于实现网络编码和头协议。xml.dom
和xml.sax
包为解析这种流行的数据交换格式提供了强大的支持。同样,csv模块支持直接读写通用数据库格式。总的来说,这些模块和包大大简化了Python应用程序和其它工具之间的数据交换。- 国际化被大量的模块所支持,其中包括
gettext
、locale
和codecs
。