“Python/docs/3.9/tutorial/stdlib”的版本间差异
(autoload) |
小 (Page commit) |
||
第1行: | 第1行: | ||
+ | {{DISPLAYTITLE:10. 标准库简介 — Python 文档}} | ||
<div id="brief-tour-of-the-standard-library" class="section"> | <div id="brief-tour-of-the-standard-library" class="section"> | ||
<span id="tut-brieftour"></span> | <span id="tut-brieftour"></span> | ||
− | = | + | = 10. 标准库简介 = |
<div id="operating-system-interface" class="section"> | <div id="operating-system-interface" class="section"> | ||
<span id="tut-os-interface"></span> | <span id="tut-os-interface"></span> | ||
− | == | + | == 10.1. 操作系统界面 == |
− | + | [[../../library/os#module-os|os]] 模块提供了几十个与操作系统交互的函数: | |
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第16行: | 第16行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import os |
− | + | >>> os.getcwd() # Return the current working directory | |
'C:\\Python39' | 'C:\\Python39' | ||
− | + | >>> os.chdir('/server/accesslogs') # Change current working directory | |
− | + | >>> os.system('mkdir today') # Run the command mkdir in the system shell | |
− | 0</ | + | 0</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 请务必使用 <code>import os</code> 样式而不是 <code>from os import *</code>。 这将防止 [[../../library/os#os|os.open()]] 隐藏内置的 [[../../library/functions#open|open()]] 函数,该函数的运行方式大不相同。 | |
− | |||
− | |||
− | + | 内置的 [[../../library/functions#dir|dir()]] 和 [[../../library/functions#help|help()]] 函数可用作处理大型模块(如 [[../../library/os#module-os|os]])的交互式辅助工具: | |
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第37行: | 第34行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import os |
− | + | >>> dir(os) | |
− | + | <returns a list of all module functions> | |
− | + | >>> help(os) | |
− | + | <returns an extensive manual page created from the module's docstrings></syntaxhighlight> | |
</div> | </div> | ||
</div> | </div> | ||
− | + | 对于日常文件和目录管理任务,[[../../library/shutil#module-shutil|shutil]] 模块提供了更易于使用的更高级别的接口: | |
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第53行: | 第49行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import shutil |
− | + | >>> shutil.copyfile('data.db', 'archive.db') | |
'archive.db' | 'archive.db' | ||
− | + | >>> shutil.move('/build/executables', 'installdir') | |
− | 'installdir'</ | + | 'installdir'</syntaxhighlight> |
</div> | </div> | ||
第67行: | 第63行: | ||
<span id="tut-file-wildcards"></span> | <span id="tut-file-wildcards"></span> | ||
− | == | + | == 10.2. 文件通配符 == |
− | + | [[../../library/glob#module-glob|glob]] 模块提供了从目录通配符搜索中生成文件列表的功能: | |
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第76行: | 第71行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import glob |
− | + | >>> glob.glob('*.py') | |
− | ['primes.py', 'random.py', 'quote.py']</ | + | ['primes.py', 'random.py', 'quote.py']</syntaxhighlight> |
</div> | </div> | ||
第88行: | 第83行: | ||
<span id="tut-command-line-arguments"></span> | <span id="tut-command-line-arguments"></span> | ||
− | == | + | == 10.3. 命令行参数 == |
− | + | 通用实用程序脚本通常需要处理命令行参数。 这些参数作为列表存储在 [[../../library/sys#module-sys|sys]] 模块的 ''argv'' 属性中。 例如,在命令行运行 <code>python demo.py one two three</code> 会产生以下输出: | |
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第98行: | 第91行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import sys |
− | + | >>> print(sys.argv) | |
− | ['demo.py', 'one', 'two', 'three']</ | + | ['demo.py', 'one', 'two', 'three']</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | [[../../library/argparse#module-argparse|argparse]] 模块提供了一种更复杂的机制来处理命令行参数。 以下脚本提取一个或多个文件名以及可选的要显示的行数: | |
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第113行: | 第104行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">import argparse |
parser = argparse.ArgumentParser(prog = 'top', | parser = argparse.ArgumentParser(prog = 'top', | ||
第120行: | 第111行: | ||
parser.add_argument('-l', '--lines', type=int, default=10) | parser.add_argument('-l', '--lines', type=int, default=10) | ||
args = parser.parse_args() | args = parser.parse_args() | ||
− | print(args)</ | + | print(args)</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 在命令行中使用 <code>python top.py --lines=5 alpha.txt beta.txt</code> 运行时,脚本将 <code>args.lines</code> 设置为 <code>5</code>,将 <code>args.filenames</code> 设置为 <code>['alpha.txt', 'beta.txt']</code>。 | |
− | |||
第133行: | 第123行: | ||
<span id="tut-stderr"></span> | <span id="tut-stderr"></span> | ||
− | == | + | == 10.4. 错误输出重定向和程序终止 == |
− | + | [[../../library/sys#module-sys|sys]] 模块还具有 ''stdin''、''stdout'' 和 ''stderr'' 的属性。 后者对于发出警告和错误消息很有用,即使 ''stdout'' 已被重定向,也可以使它们可见: | |
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第143行: | 第131行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> sys.stderr.write('Warning, log file not found starting a new one\n') |
− | Warning, log file not found starting a new one</ | + | Warning, log file not found starting a new one</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 终止脚本的最直接方法是使用 <code>sys.exit()</code>。 | |
第156行: | 第144行: | ||
<span id="tut-string-pattern-matching"></span> | <span id="tut-string-pattern-matching"></span> | ||
− | == | + | == 10.5. 字符串模式匹配 == |
− | + | [[../../library/re#module-re|re]] 模块为高级字符串处理提供了正则表达式工具。 对于复杂的匹配和操作,正则表达式提供了简洁、优化的解决方案: | |
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第166行: | 第152行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import re |
− | + | >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') | |
['foot', 'fell', 'fastest'] | ['foot', 'fell', 'fastest'] | ||
− | + | >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') | |
− | 'cat in the hat'</ | + | 'cat in the hat'</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 当只需要简单的功能时,首选字符串方法,因为它们更易于阅读和调试: | |
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第182行: | 第167行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> 'tea for too'.replace('too', 'two') |
− | 'tea for two'</ | + | 'tea for two'</syntaxhighlight> |
</div> | </div> | ||
第193行: | 第178行: | ||
<span id="tut-mathematics"></span> | <span id="tut-mathematics"></span> | ||
− | == | + | == 10.6. 数学 == |
− | + | [[../../library/math#module-math|math]] 模块可以访问浮点数学的底层 C 库函数: | |
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第202行: | 第186行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import math |
− | + | >>> math.cos(math.pi / 4) | |
0.70710678118654757 | 0.70710678118654757 | ||
− | + | >>> math.log(1024, 2) | |
− | 10.0</ | + | 10.0</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | [[../../library/random#module-random|random]] 模块提供了进行随机选择的工具: | |
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第217行: | 第201行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import random |
− | + | >>> random.choice(['apple', 'pear', 'banana']) | |
'apple' | 'apple' | ||
− | + | >>> random.sample(range(100), 10) # sampling without replacement | |
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33] | [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] | ||
− | + | >>> random.random() # random float | |
0.17970987693706186 | 0.17970987693706186 | ||
− | + | >>> random.randrange(6) # random integer chosen from range(6) | |
− | 4</ | + | 4</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | [[../../library/statistics#module-statistics|statistics]] 模块计算数值数据的基本统计属性(均值、中位数、方差等): | |
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第237行: | 第220行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import statistics |
− | + | >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] | |
− | + | >>> statistics.mean(data) | |
1.6071428571428572 | 1.6071428571428572 | ||
− | + | >>> statistics.median(data) | |
1.25 | 1.25 | ||
− | + | >>> statistics.variance(data) | |
− | 1.3720238095238095</ | + | 1.3720238095238095</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | SciPy 项目 < https://scipy.org > 有许多其他的数值计算模块。 | |
− | |||
第257行: | 第239行: | ||
<span id="tut-internet-access"></span> | <span id="tut-internet-access"></span> | ||
− | == | + | == 10.7. 互联网 == |
− | + | 有许多用于访问互联网和处理互联网协议的模块。 两个最简单的是 [[../../library/urllib.request#module-urllib|urllib.request]] 用于从 URL 检索数据和 [[../../library/smtplib#module-smtplib|smtplib]] 用于发送邮件: | |
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第267行: | 第247行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> from urllib.request import urlopen |
− | + | >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response: | |
... for line in response: | ... for line in response: | ||
... line = line.decode('utf-8') # Decoding the binary data to text. | ... line = line.decode('utf-8') # Decoding the binary data to text. | ||
第274行: | 第254行: | ||
... print(line) | ... 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 | ... From: soothsayer@example.org | ||
... | ... | ||
... Beware the Ides of March. | ... Beware the Ides of March. | ||
− | ... | + | ... """) |
− | + | >>> server.quit()</syntaxhighlight> | |
</div> | </div> | ||
</div> | </div> | ||
− | + | (请注意,第二个示例需要在本地主机上运行的邮件服务器。) | |
第296行: | 第276行: | ||
<span id="tut-dates-and-times"></span> | <span id="tut-dates-and-times"></span> | ||
− | == | + | == 10.8. 日期和时间 == |
− | + | [[../../library/datetime#module-datetime|datetime]] 模块提供了以简单和复杂方式操作日期和时间的类。 虽然支持日期和时间算术,但实现的重点是高效的成员提取以进行输出格式化和操作。 该模块还支持时区感知的对象。 | |
− | |||
− | |||
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第308行: | 第284行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> # dates are easily constructed and formatted |
− | + | >>> from datetime import date | |
− | + | >>> now = date.today() | |
− | + | >>> now | |
datetime.date(2003, 12, 2) | 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.' | '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</ | + | 14368</syntaxhighlight> |
</div> | </div> | ||
第330行: | 第306行: | ||
<span id="tut-data-compression"></span> | <span id="tut-data-compression"></span> | ||
− | == | + | == 10.9. 数据压缩 == |
− | + | 常用的数据归档和压缩格式由模块直接支持,包括:[[../../library/zlib#module-zlib|zlib]]、[[../../library/gzip#module-gzip|gzip]]、[[../../library/bz2#module-bz2|bz2]]、[[../../library/lzma#module-lzma|lzma]]、zipfile[ X161X] 和 [[../../library/tarfile#module-tarfile|tarfile]]。 | |
− | |||
− | [[../../library/tarfile#module-tarfile| | ||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第340行: | 第314行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> import zlib |
− | + | >>> s = b'witch which has which witches wrist watch' | |
− | + | >>> len(s) | |
41 | 41 | ||
− | + | >>> t = zlib.compress(s) | |
− | + | >>> len(t) | |
37 | 37 | ||
− | + | >>> zlib.decompress(t) | |
b'witch which has which witches wrist watch' | b'witch which has which witches wrist watch' | ||
− | + | >>> zlib.crc32(s) | |
− | 226805979</ | + | 226805979</syntaxhighlight> |
</div> | </div> | ||
第360行: | 第334行: | ||
<span id="tut-performance-measurement"></span> | <span id="tut-performance-measurement"></span> | ||
− | == | + | == 10.10. 绩效衡量 == |
− | + | 一些 Python 用户对了解解决同一问题的不同方法的相对性能产生了浓厚的兴趣。 Python 提供了一种测量工具,可以立即回答这些问题。 | |
− | |||
− | |||
− | + | 例如,使用元组打包和解包功能而不是传统的方法来交换参数可能很诱人。 [[../../library/timeit#module-timeit|timeit]] 模块迅速展示了适度的性能优势: | |
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第374行: | 第344行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">>>> from timeit import Timer |
− | + | >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() | |
0.57535828626024577 | 0.57535828626024577 | ||
− | + | >>> Timer('a,b = b,a', 'a=1; b=2').timeit() | |
− | 0.54962537085770791</ | + | 0.54962537085770791</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | 与 [[../../library/timeit#module-timeit|timeit]] 的精细粒度级别相比,[[../../library/profile#module-profile|profile]] 和 [[../../library/profile#module-pstats|pstats]] 模块提供了用于识别较大代码块中的时间关键部分的工具。 | |
− | [[../../library/profile#module-pstats| | ||
− | |||
第392行: | 第360行: | ||
<span id="tut-quality-control"></span> | <span id="tut-quality-control"></span> | ||
− | == | + | == 10.11. 质量控制 == |
− | + | 开发高质量软件的一种方法是在开发过程中为每个功能编写测试,并在开发过程中频繁运行这些测试。 | |
− | |||
− | |||
− | + | [[../../library/doctest#module-doctest|doctest]] 模块提供了一个用于扫描模块和验证嵌入在程序文档字符串中的测试的工具。 测试构建就像将典型调用及其结果剪切并粘贴到文档字符串中一样简单。 这通过为用户提供示例来改进文档,并允许 doctest 模块确保代码与文档保持一致: | |
− | |||
− | |||
− | |||
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第409行: | 第370行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">def average(values): |
− | + | """Computes the arithmetic mean of a list of numbers. | |
− | + | >>> print(average([20, 30, 70])) | |
40.0 | 40.0 | ||
− | + | """ | |
return sum(values) / len(values) | return sum(values) / len(values) | ||
import doctest | import doctest | ||
− | doctest.testmod() # automatically validate the embedded tests</ | + | doctest.testmod() # automatically validate the embedded tests</syntaxhighlight> |
</div> | </div> | ||
</div> | </div> | ||
− | + | [[../../library/unittest#module-unittest|unittest]] 模块不像 [[../../library/doctest#module-doctest|doctest]] 模块那么轻松,但它允许在单独的文件中维护一组更全面的测试: | |
− | |||
− | |||
<div class="highlight-python3 notranslate"> | <div class="highlight-python3 notranslate"> | ||
第431行: | 第390行: | ||
<div class="highlight"> | <div class="highlight"> | ||
− | < | + | <syntaxhighlight lang="python3">import unittest |
class TestStatisticalFunctions(unittest.TestCase): | class TestStatisticalFunctions(unittest.TestCase): | ||
第443行: | 第402行: | ||
average(20, 30, 70) | average(20, 30, 70) | ||
− | unittest.main() # Calling from the command line invokes all tests</ | + | unittest.main() # Calling from the command line invokes all tests</syntaxhighlight> |
</div> | </div> | ||
第453行: | 第412行: | ||
<span id="tut-batteries-included"></span> | <span id="tut-batteries-included"></span> | ||
− | == | + | == 10.12. 包括电池 == |
− | Python | + | Python 有一个“包含电池”的理念。 通过其较大封装的复杂和强大功能可以最好地看出这一点。 例如: |
− | |||
− | * | + | * [[../../library/xmlrpc.client#module-xmlrpc|xmlrpc.client]] 和 [[../../library/xmlrpc.server#module-xmlrpc|xmlrpc.server]] 模块使实现远程过程调用成为一项几乎微不足道的任务。 尽管有模块名称,但不需要直接了解或处理 XML。 |
− | * | + | * [[../../library/email#module-email|email]] 包是一个用于管理电子邮件消息的库,包括 MIME 和其他基于 <span id="index-1" class="target"></span>[https://tools.ietf.org/html/rfc2822.html RFC 2822] 的消息文档。 与实际发送和接收消息的 [[../../library/smtplib#module-smtplib|smtplib]] 和 [[../../library/poplib#module-poplib|poplib]] 不同,电子邮件包具有用于构建或解码复杂消息结构(包括附件)以及用于实现 Internet 编码和标头协议的完整工具集。 |
− | * | + | * [[../../library/json#module-json|json]] 包为解析这种流行的数据交换格式提供了强大的支持。 [[../../library/csv#module-csv|csv]]模块支持直接读写逗号分隔值格式的文件,数据库和电子表格常用。 [[../../library/xml.etree.elementtree#module-xml.etree|xml.etree.ElementTree]]、[[../../library/xml.dom#module-xml|xml.dom]] 和 [[../../library/xml.sax#module-xml|xml.sax]] 包支持 XML 处理。 这些模块和包一起极大地简化了 Python 应用程序和其他工具之间的数据交换。 |
− | * | + | * [[../../library/sqlite3#module-sqlite3|sqlite3]] 模块是 SQLite 数据库库的包装器,提供了一个可以使用稍微非标准的 SQL 语法更新和访问的持久数据库。 |
− | * | + | * 许多模块支持国际化,包括 [[../../library/gettext#module-gettext|gettext]]、[[../../library/locale#module-locale|locale]] 和 [[../../library/codecs#module-codecs|codecs]] 包。 |
第468行: | 第426行: | ||
</div> | </div> | ||
+ | <div class="clearer"> | ||
− | [[Category:Python 3.9 | + | |
+ | |||
+ | </div> | ||
+ | |||
+ | [[Category:Python 3.9 文档]] |
2021年10月31日 (日) 04:54的最新版本
10. 标准库简介
10.1. 操作系统界面
os 模块提供了几十个与操作系统交互的函数:
请务必使用 import os
样式而不是 from os import *
。 这将防止 os.open() 隐藏内置的 open() 函数,该函数的运行方式大不相同。
内置的 dir() 和 help() 函数可用作处理大型模块(如 os)的交互式辅助工具:
对于日常文件和目录管理任务,shutil 模块提供了更易于使用的更高级别的接口:
10.3. 命令行参数
通用实用程序脚本通常需要处理命令行参数。 这些参数作为列表存储在 sys 模块的 argv 属性中。 例如,在命令行运行 python demo.py one two three
会产生以下输出:
argparse 模块提供了一种更复杂的机制来处理命令行参数。 以下脚本提取一个或多个文件名以及可选的要显示的行数:
在命令行中使用 python top.py --lines=5 alpha.txt beta.txt
运行时,脚本将 args.lines
设置为 5
,将 args.filenames
设置为 ['alpha.txt', 'beta.txt']
。
10.4. 错误输出重定向和程序终止
sys 模块还具有 stdin、stdout 和 stderr 的属性。 后者对于发出警告和错误消息很有用,即使 stdout 已被重定向,也可以使它们可见:
终止脚本的最直接方法是使用 sys.exit()
。
10.5. 字符串模式匹配
re 模块为高级字符串处理提供了正则表达式工具。 对于复杂的匹配和操作,正则表达式提供了简洁、优化的解决方案:
当只需要简单的功能时,首选字符串方法,因为它们更易于阅读和调试:
10.6. 数学
math 模块可以访问浮点数学的底层 C 库函数:
random 模块提供了进行随机选择的工具:
statistics 模块计算数值数据的基本统计属性(均值、中位数、方差等):
SciPy 项目 < https://scipy.org > 有许多其他的数值计算模块。
10.7. 互联网
有许多用于访问互联网和处理互联网协议的模块。 两个最简单的是 urllib.request 用于从 URL 检索数据和 smtplib 用于发送邮件:
(请注意,第二个示例需要在本地主机上运行的邮件服务器。)
10.10. 绩效衡量
一些 Python 用户对了解解决同一问题的不同方法的相对性能产生了浓厚的兴趣。 Python 提供了一种测量工具,可以立即回答这些问题。
例如,使用元组打包和解包功能而不是传统的方法来交换参数可能很诱人。 timeit 模块迅速展示了适度的性能优势:
与 timeit 的精细粒度级别相比,profile 和 pstats 模块提供了用于识别较大代码块中的时间关键部分的工具。
10.11. 质量控制
开发高质量软件的一种方法是在开发过程中为每个功能编写测试,并在开发过程中频繁运行这些测试。
doctest 模块提供了一个用于扫描模块和验证嵌入在程序文档字符串中的测试的工具。 测试构建就像将典型调用及其结果剪切并粘贴到文档字符串中一样简单。 这通过为用户提供示例来改进文档,并允许 doctest 模块确保代码与文档保持一致:
unittest 模块不像 doctest 模块那么轻松,但它允许在单独的文件中维护一组更全面的测试:
10.12. 包括电池
Python 有一个“包含电池”的理念。 通过其较大封装的复杂和强大功能可以最好地看出这一点。 例如:
- xmlrpc.client 和 xmlrpc.server 模块使实现远程过程调用成为一项几乎微不足道的任务。 尽管有模块名称,但不需要直接了解或处理 XML。
- email 包是一个用于管理电子邮件消息的库,包括 MIME 和其他基于 RFC 2822 的消息文档。 与实际发送和接收消息的 smtplib 和 poplib 不同,电子邮件包具有用于构建或解码复杂消息结构(包括附件)以及用于实现 Internet 编码和标头协议的完整工具集。
- json 包为解析这种流行的数据交换格式提供了强大的支持。 csv模块支持直接读写逗号分隔值格式的文件,数据库和电子表格常用。 xml.etree.ElementTree、xml.dom 和 xml.sax 包支持 XML 处理。 这些模块和包一起极大地简化了 Python 应用程序和其他工具之间的数据交换。
- sqlite3 模块是 SQLite 数据库库的包装器,提供了一个可以使用稍微非标准的 SQL 语法更新和访问的持久数据库。
- 许多模块支持国际化,包括 gettext、locale 和 codecs 包。