[译]The Python Tutorial#10. Brief Tour of the Standard Library

来源:互联网 发布:windows tv box 编辑:程序博客网 时间:2024/06/05 12:12

[译]The Python Tutorial#Brief Tour of the Standard Library

10.1 Operating System Interface

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 shell0

确保使用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

一般的工具脚本通常需要处理命令行参数。命令行参数作为列表存储在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 Error Output Redirection and Program Termination

sys模块拥有变量stdinstdout以及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 String Pattern Matching

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 Mathematics

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 float0.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

SciPy 项目

10.7 Internet Access

Python提供了许多用于网络资源访问以及互联网协议处理的模块。最简单的两个是用于从URL获取数据的urllib.request,以及发送邮件的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 Dates and Times

datetime模块提供了以简单或者复杂方式计算时间以及日期的类。支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出。该模块同时支持时区处理。

>>> # dates are easily constructed and formatted>>> from datetime import date>>> now = date.today()>>> nowdatetime.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.days14368

10.9 Data Compression

以下模块直接支持通用数据的打包和压缩格式: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模块能够快速证实序列解包更快:

>>> 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以及pstas模块提供了适用于大型代码块的性能测量工具。

10.11 Quality Control

开发高质量软件的一种方式是在每一个函数编写时,为其编写测试用例,并且在开发过程中经常运行这些测试用例。

doctest模块提供了一个工具,该工具扫描模块并验证内嵌入程序文档字符串中的测试。测试的结构非常简单,就像复制粘贴一个附带返回值的典型函数调用一样。为使用者提供调用示例,从而增强了文档,同时允许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 doctestdoctest.testmod()   # automatically validate the embedded tests

unittest不像doctest模块那样简单,但是它允许在单独的文件中维护复杂的测试集合:

import unittestclass 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有“自带电池”的哲学。这一点可以从Python自带庞大包提供的大量功能看出来。例如:

  • xmlrpc.server和xmlrpc.client模块让远程调用变得非常简单,尽管名字中有xml,但是在使用时无需xml的知识,也不需要处理xml。
  • email包是管理邮件信息的库,包括MIME其他以及基于RFC-32的信息文档。与实际发送和接受邮件的smtplibpoplib不同,emial包拥有一个完整的工具集合,该工具集包含构造以及解码复杂消息结构(包括附件)以及实现网络编码和头协议等功能。
  • json包提供了解析json这种流行的数据交换格式的支持。csv支持直接读写通用数据格式文件,包括数据库和表格文件。xml.etree.ElementTree, xml.dom 以及 xml.sax包支持XML的处理。这些模块极大简化了Python应用和其他工具之间的数据交换。
  • sqlite3模块是对SQLite数据库的包装库,该模块提供了一个持久数据库,可以通过稍微不标准的sql语法访问和更新数据库。
  • 国际化由一系列模块支持,包括: gettext, locale, 以及codecs包。
阅读全文
0 0