On this page
10. 标准库简介
10.1. 作业系统介面
os模块提供了数十种用于与 os 进行交互的Function:
>>> import os
>>> os.getcwd() # Return the current working directory
'C:\\Python38'
>>> 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()函数的Function,后者的操作方式大不相同。
内置的dir()和help()Function可作为交互式辅助工具,用于处理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>
对于日常文件和目录 Management 任务,shutil模块提供了更易于使用的更高级别的界面:
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'
10.2. 文件通配符
glob模块提供了pass目录通配符搜索来创建文件列表的Function:
>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']
10.3. 命令行参数
通用 Util 脚本通常需要处理命令行参数。这些参数作为列表存储在sys模块的* argv *属性中。例如,以下输出是在命令行上运行python demo.py one two three
的结果:
>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']
argparse模块提供了一种更复杂的机制来处理命令行参数。以下脚本提取一个或多个文件名以及要显示的可选行数:
import argparse
parser = argparse.ArgumentParser(prog = 'top',
description = 'Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)
当在命令行上使用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.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'
如果只需要简单的Function,则首选字符串方法,因为它们更易于阅读和调试:
>>> 'tea for too'.replace('too', 'two')
'tea for two'
10.6. Mathematics
math模块可访问用于浮点 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
SciPy 项目< https://scipy.org >拥有许多其他用于数值计算的模块。
10.7. 互联网
有许多用于访问 Internet 和处理 Internet 协议的模块。最简单的两个是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()
(请注意,第二个示例需要在 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,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 提供了一种度量工具,可以立即回答这些问题。
例如,使用 Tuples 打包和拆包Function代替传统的交换参数方法可能很诱人。 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. 质量控制
开发高质量软件的一种方法是在开发每个Function时编写测试,并在开发过程中频繁运行这些测试。
doctest模块提供了一种工具,用于扫描模块并验证嵌入在程序文档字符串中的测试。测试构造就像将一个典型的调用及其结果粘贴到文档字符串中一样简单。这pass为用户提供示例来改善文档,并允许 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. 包含 Batteries
Python 具有“包括 Batteries”的 IDEA。最好的解决方案是pass其大型程序包的复杂而强大的Function来实现的。例如:
xmlrpc.client和xmlrpc.server模块使实现远程过程调用成为一项几乎不重要的任务。尽管有模块名称,但不需要直接了解或处理 XML。
email软件包是用于 Management 电子邮件的库,包括 MIME 和其他基于 RFC 2822的邮件文档。与实际发送和接收消息的smtplib和poplib不同,电子邮件包具有用于构建或解码复杂的消息结构(包括附件)以及实现 Internet 编码和 Headers 协议的完整工具集。
json软件包为解析此流行的数据交换格式提供了强大的支持。 csv模块支持直接读取和写入逗号分隔值格式的文件,通常由数据库和电子表格支持。 xml.etree.ElementTree,xml.dom和xml.sax软件包支持 XML 处理。这些模块和软件包在一起可以极大地简化 Python 应用程序和其他工具之间的数据交换。
sqlite3模块是 SQLite 数据库库的包装,提供了一个持久数据库,可以使用稍微不标准的 SQL 语法进行更新和访问。