10.1 操作系统接口
os模块提供了很多和操作系统交互的函数:
>>> import os
>>> os.getcwd() # Return the current working directory
'C:\\Python36'
>>> 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()导致不同的操作。
内置函数dir()和help()在和大的模块例如os工作将是一种更有用的交互手段:
>>> 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 文件通配符
glob模块提供了一个函数,从目录通配符中搜索文件列表的功能
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py']
10.3 命令行参数
常见的使用脚本通常需要处理命令行参数。这些参数被存储在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属性。后者对发出警告和错误消息非常有用,即使是他们被重定向,也可以使他们可见
>>> 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'
当只需要简单的功能时,字符串方法是首选因为他们更容易阅读和调试:
>>> '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
statistics模块计算数字数据的基本的统计学属性(平均值,中值,方差等):
>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095
10.7 互联网访问
有许多模块用于访问internet和处理internet协议。其中最简单的2个是urllib.request用于从url提取数据和smtplib用于发送邮件:
>>> from urllib.request import urlopen
>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
... for line in response:
... 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()
注意第二个例子需要在本地有一个邮件服务。
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 性能评估
一些Python使用者对了解同一问题的不同方法的相关性能有很深的兴趣。Python提供了一套测量功能来立即回答这些问题。
例如,尝试使用元组来打包和拆分特性而不是传统的交换参数的方法。timeit模块展示了一个适度的性能优势:
>>> 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 质量控制
开发好质量的软件的一个方式是为每一个函数写测试,并且在开发过程中频繁的运行这些测试。
doctest模块提供了一个功能,可以扫描一个模块并验证嵌入在一个程序的docstrings李的测试。测试的构成简单的好像粘贴复制一个典型的调用和它的结果一起到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 内置电池
Python有一个内置电池管理。通过其更大的包的复杂和强健的功能,可以看到这一点。例如:- xmlrpc.client和xmlrpc.server模块将远程过程调用变为一个几乎微不足道的任务。不管模块的名称,不需要掌握处理XML的直接的知识
- email包是一个用于管理邮件消息的库,包括MIME和其他基于RFC 2822的消息文档。不像实际发送和接收消息的smtplib和poplib,这个email包有一个完整的工具集,用于建立或者解码复杂的消息结构(包括附件)并且实现internet编码和头协议。
- json包提供强力的支持,为了解析这个流行的数据交换格式。csv模块支持直接读写逗号分隔值格式的文件,这些文件通常是数据库或者电子表格。XML处理是由xml.etree.ElementTree,xml.dom和xml.sax包支持。这些模块和包在一起极大的简化了Python应用程序和其他工具之间的数据交换
- sqllite3模块是SQLite数据库的包装,提供了一个持久的数据,能用略不标准的sql语法被更新和访问
- 国际化被很多模块支持,包括gettext,locale和codecs包。