10. 标准库概览

10.1. 操作系统接口

os模块提供了几十个函数与操作系统交互:

>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python26'
>>> 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')
>>> shutil.move('/build/executables', 'installdir')

10.2. 文件通配符

glob模块提供了一个函数用于在目录中以通配符搜索文件,并生成匹配的文件列表:

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

10.3.命令行参数

常见实用程序脚本通常需要处理命令行参数。这些参数存储在sys模块的argv属性为一个列表。例如下面的输出结果从命令行运行python demo.py 一个两个三个

>>> import sys
>>> print sys.argv
['demo.py', 'one', 'two', 'three']

Getopt模块处理sys.argv使用 Unix getopt()函数的约定。argparse模块提供更强大、 更灵活的命令行处理。

10.4.错误输出重定向和程序终止

Sys模块还具有标准输入标准输出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.数学

数学模块给浮点运算的基础 C 库函数的访问:

>>> import math
>>> math.cos(math.pi / 4.0)
0.70710678118654757
>>> math.log(1024, 2)
10.0

随机模块提供了进行随机选择的工具:

>>> import random
>>> 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 float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

10.7.互联网访问

那里有很多的模块,用于访问互联网和加工的互联网协议。最简单的两个模块是从URL获取数据的urllib2 和发送邮件的smtplib

>>> import urllib2
>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     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.日期和时间

日期时间模块提供了用于处理日期和时间在简单和复杂的方法的类。日期和时间算术运算支持的但实施的重点是有效成员提取的输出格式设置和操作。该模块还支持时区意识到的对象。

>>> # 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 zip 文件tarfile

>>> import zlib
>>> 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

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

大声精细的粒度、配置文件pstats模块级别用于标识时间关键节更大块的代码中提供的工具。

10.11.质量控制

一种开发高质量软件的方法是为每一个函数开发测试代码,并且在开发过程中经常运行这些测试代码。

doctest模块提供一个工具,这个工具可以扫描一个模块并验证确认内嵌到程序中的文档字符串测试代码。测试构造与剪切一个典型的调用并同它的结果粘贴到文档字符串中一样简单。这提高了文档的用户提供一个示例,它允许 doctest 模块,以确保代码始终遵守文档:

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)
import doctest
doctest.testmod()   # automatically validate the embedded tests

单元测试的模块不是那样容易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 有"电池列"的哲学。这从其较大的文件包的先进和强大功能得到了最好的体现。例如:

  • XmlrpclibSimpleXMLRPCServer模块使到几乎是琐碎的任务执行的远程过程调用。模块名称,尽管没有直接知识或处理 XML 的需要。
  • 电子邮件软件包是一个用于管理电子邮件,包括 MIME 和其他基于 RFC 2822 的邮件文件的库。不同于smtplibpoplib ,实际发送和接收邮件,电子邮件软件包有一个完整的工具集,建设或解码复杂消息结构 (包括附件),并执行编码和标头的互联网协议。
  • Xml.domxml.sax的包为解析此常用数据交换格式提供有力的支持。同样, csv模块支持直接读取并写入中常见的数据库格式。在一起,这些模块和包大大简化 Python 应用程序和其他工具之间的数据交换。
  • 国际化支持模块包括gettext区域设置编解码器包数。