10. Python 标准库概览¶

10.1. �作系统接�¶

os 模��供了很多与�作系统交互的函数:

>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python27'
>>> 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')
>>> 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 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'

�需简�的�作时,字符串方法最好用,因为它们易读,�容易调试:

>>> 'tea for too'.replace('too', 'two')
'tea for two'

10.6. 数学¶

math 模�为浮点�算�供了对底层 C 函数库的访问:

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

random �供了生��机数的工具:

>>> 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. 互�网访问¶

有几个模�用于访问互�网以�处�网络通信�议。其中最简�的两个是用于处�从 urls 接收的数�的 urllib2 以�用于��电�邮件的 smtplib:

>>> import urllib2
>>> for line in urllib2.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,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 �供了一个度�工具,为这些问题�供了直接答案。

例如,使用元组�装和拆��交�元素看起��比使用传统的方法�诱人的多。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 模��供了一个工具,扫�模�并根�程�中内嵌的文档字符串执行测试。测试构造如�简�的将它的输出结果剪切并粘贴到文档字符串中。通过用户�供的例�,它�展了文档,�许 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

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)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

unittest.main() # Calling from the command line invokes all tests

10.12. “瑞士军刀�¶

Python 展现了“瑞士军刀�的哲学。这�以通过它更大的包的高级和�壮的功能�得到最好的展现。例如:

  • xmlrpclib å’Œ SimpleXMLRPCServer 模å�—让远程过程调用å�˜å¾—轻而易举。

    尽管模�有这样的�字,用户无需拥有XML的知识或处� XML。

  • email 包是一个管ç�†é‚®ä»¶ä¿¡æ�¯çš„库,包括MIME和其它基于 RFC2822 的信æ�¯æ–‡æ¡£ã€‚

    ��于实际��和接收信�的 smtplib 和 poplib 模�,email 包包�一个构造或解���消�结构(包括附件)�实现互�网编�和头�议的完整工具集。

  • xml.dom å’Œ xml.sax 包为æµ�行的信æ�¯äº¤æ�¢æ ¼å¼�æ��供了强大的支æŒ�。

    �样,csv 模�支�在通用数�库格�中直接读写。综�起�,这些模�和包大大简化了 Python 应用程�和其它工具之间的数�交�。

  • 国际化由 gettext, locale å’Œ codecs 包支æŒ�。