Python3 标准库概览
通过一组可独立运行的本地实验,选择合适的文件、文本、网络、压缩和测试工具。
学完这一章,你能够
- 通过一组可独立运行的本地实验,选择合适的文件、文本、网络、压缩和测试工具。
文件、目录与模块查询
用 os.getcwd() 看进程的工作目录,用 os.listdir(path) 看该目录的直接条目。工作目录可能和脚本所在目录不同。读取环境变量时用 os.environ,本章只设置并恢复自己的示例变量。
保留模块前缀能分清 os.open 与内置 open。前者返回整数文件描述符,后者通常返回文件对象。dir(os) 提供可查看的属性名,其中也有常量等成员。help(os) 可以生成帮助文本,具体内容随平台和 Python 版本而变。
shutil.copyfile 复制内容,shutil.move 可移动或改名。本站只对自建目录操作,核对复制后的字节和移动后的位置。用 glob.glob("*.py", root_dir=目录) 查找与通配模式相符的路径。需要稳定顺序时主动排序。
区分命令行的输入、输出与退出
sys.argv 是 Python 列表。直接执行脚本时,第 0 项通常是脚本路径,之后是实际传入的参数。sys.version 和 sys.executable 分别帮助确认解释器版本和路径。
标准输入、标准输出、标准错误是三条独立的流。可以把普通结果重定向后继续读取 stderr。sys.exit(7) 发起 SystemExit,在脚本主线程未捕获时进程以状态 7 退出。实例用一个自建子进程同时记录三条流和返回码。
按任务选择文本与数值工具
只想替换字面片段时,可先用 str.replace。需要按边界查找、回引用捕获组或按模式分隔时,再用 re.findall、re.sub、re.split。实例用原始字符串写模式,避免把反斜杠先交给字符串转义处理。
math 提供三角函数、对数、指数和常量。三角函数按弧度传参,浮点结果可按容差比较。random 可用 choice 取一个元素、sample 不放回抽样、random 取 [0, 1) 浮点数、randrange 或 randint 取整数。这里用独立种子生成器复现实验,随机输出不适合作为密码。
json.dumps 把可编码的数据转换成 JSON 文本,json.loads 再解析。文件传输时另外选定文本编码。JSON 适合字典、列表和基础值,元组经往返会得到列表,不能假定任意 Python 对象都可无损还原。
用本机服务观察协议
urllib.parse 可构造查询和表单字段,urllib.request 可读取响应、保存下载并发送 POST。响应体先得到字节,再按约定字符集解码。需要跨请求保存 Cookie 时,可为自己的 opener 配置 HTTPCookieProcessor 和 CookieJar。
smtplib 是 SMTP 客户端,需要可连接的服务器。本站实验只连接 127.0.0.1 的一次性 HTTP 和 SMTP 接收器,观察请求参数、响应、Cookie 和 SMTP 信封。本地接收并不代表邮件已经投递到真实收件箱。历史远程报时页仍作为原例背景,实例使用本站自建响应。
日期、耗时和压缩各用合适的接口
datetime.now() 和 date.today() 默认使用本地时间。已知时区时可以构造带时区的 datetime,再用 astimezone 转换。date 相减得到 timedelta,读取 days 可看两日期相差的整天数。strftime 的数字字段适合固定格式,月份和星期的文字受 locale 影响。
time.time() 读墙上时钟,time.perf_counter() 适合测量经过时间。用 timeit.repeat 对同一个循环条件重复测量,并单独验证两种写法的结果等价。单台机器的结果不保证其它版本更快。profile 和 pstats 可按函数统计调用次数与耗时。
zlib、gzip 和 bz2 可压缩字节,zipfile 和 tarfile 可管理多个命名成员。解压后要比对原字节,也可以核对 CRC32。CRC32 用来发现常见传输错误,不能验证数据来源。短输入加上压缩头可能更大。本站 ZIP 和 TAR 实验只读自己写入的成员。
同时写文档例子和独立测试
doctest 运行 docstring 中的交互例子并比较输出,适合展示调用方式。unittest 用独立测试覆盖正常输入、边界和异常。这里分别观察均值、舍入结果、空输入的除零和实参个数错误。
工具选择与检查点
| 需求 | 常用模块 | 检查点 |
| 目录、路径和文件 | os、shutil、glob | 确认作用路径、复制字节、移动后的状态与排序 |
| 进程参数与流 | sys、subprocess | 检查 argv 类型、三条标准流与退出状态 |
| 文本与数据 | re、json | 回引用转义、编码及往返后的类型 |
| 浮点与抽样 | math、random | 用容差比较浮点值,区分放回与不放回 |
| 日期和测量 | time、datetime、timeit、profile、pstats | 区分墙钟、时区、时长、重复计时和函数统计 |
| HTTP 和 SMTP | urllib、http.cookiejar、smtplib | 明确目标地址、协议、请求数据及接收状态 |
| 压缩与归档 | zlib、gzip、bz2、zipfile、tarfile | 核对原始字节、归档成员与 CRC |
| 自动测试 | doctest、unittest | 分别查看文档输出和测试断言 |
本章自编源码与运行范围
展开查看收起
"""蓝色天空网 mbsky.com | A bounded tour of the Python standard library."""
import builtins
import bz2
from contextlib import contextmanager, redirect_stdout
from datetime import date, datetime, timedelta, timezone
import doctest
import glob
import gzip
from http.cookiejar import CookieJar
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import io
import json
import math
import os
from pathlib import Path
import profile
import pstats
import random
import re
import shutil
import smtplib
from socketserver import StreamRequestHandler, TCPServer
import subprocess
import sys
import tarfile
from tempfile import TemporaryDirectory, gettempdir
from threading import Thread
import time
from timeit import Timer
import unittest
from urllib.parse import parse_qs, urlencode, urlsplit
from urllib.request import HTTPCookieProcessor, ProxyHandler, Request, build_opener
import zipfile
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
def file_and_process_checks(checks, workspace):
checks.eq("os cwd refers to process location", Path(os.getcwd()).is_dir(), True)
fixtures = workspace / "fixtures"
fixtures.mkdir()
for name in ("scan.py", "track.py", "notes.txt"):
(fixtures / name).write_text("fixture", encoding="utf8")
checks.eq("os directory entries", sorted(os.listdir(fixtures)), ["notes.txt", "scan.py", "track.py"])
checks.eq("glob relative paths", sorted(glob.glob("*.py", root_dir=fixtures)), ["scan.py", "track.py"])
checks.eq("glob empty match", glob.glob("*.csv", root_dir=fixtures), [])
marker = "MBSKY_STDLIB_SCOPE"
previous = os.environ.get(marker)
os.environ[marker] = "owned"
try:
checks.eq("environment value", os.environ[marker], "owned")
finally:
if previous is None:
os.environ.pop(marker)
else:
os.environ[marker] = previous
checks.eq("environment restored", os.environ.get(marker), previous)
src = fixtures / "dispatch.bin"
raw = b"dispatch report\n"
src.write_bytes(raw)
copy = fixtures / "copy.bin"
shutil.copyfile(src, copy)
checks.eq("shutil copy exact bytes", copy.read_bytes(), raw)
out = (workspace / "moved.bin").resolve()
assert copy.resolve().is_relative_to(workspace) and out.is_relative_to(workspace)
shutil.move(str(copy), str(out))
checks.eq("shutil move changes path", (copy.exists(), out.read_bytes()), (False, raw))
descriptor = os.open(out, os.O_RDONLY | getattr(os, "O_BINARY", 0))
try:
checks.eq("os open returns descriptor", type(descriptor).__name__, "int")
finally:
os.close(descriptor)
with builtins.open(out, "rb") as stream:
checks.eq("builtin open gives readable file object", stream.read(), raw)
help_text = io.StringIO()
with redirect_stdout(help_text):
help(os)
checks.eq("help lists module documentation", "Help on module os" in help_text.getvalue(), True)
checks.eq("dir includes callable and constant", {"open", "O_RDONLY"} <= set(dir(os)), True)
script = workspace / "read_args.py"
script.write_text(
"import json, sys\n"
"print(json.dumps({'argv': sys.argv, 'input': sys.stdin.readline().rstrip('\\n'), "
"'version': sys.version.split()[0], 'executable': sys.executable}))\n"
"sys.stderr.write('separate warning\\n')\n"
"sys.exit(7)\n", encoding="utf8")
proc = subprocess.run([sys.executable, "-I", "-B", "-X", "utf8", str(script), "east", "two words"],
input="owned line\n", text=True, encoding="utf8", capture_output=True,
cwd=workspace, timeout=15)
recorded = json.loads(proc.stdout)
checks.eq("argv is list with script and literal args", recorded["argv"], [str(script), "east", "two words"])
checks.eq("stdin consumed separately", recorded["input"], "owned line")
checks.eq("stderr is separate from redirected stdout", proc.stderr, "separate warning\n")
checks.eq("sys exit process code", proc.returncode, 7)
checks.eq("sys interpreter metadata", (recorded["version"], str(Path(recorded["executable"]).resolve())),
(sys.version.split()[0], str(Path(sys.executable).resolve())))
def text_number_checks(checks):
checks.eq("regex word matching", re.findall(r"\bb[a-z]*", "yard bay bridge dock"), ["bay", "bridge"])
checks.eq("regex backreference replacement", re.sub(r"\b(\w+) \1\b", r"\1", "red red signal"), "red signal")
checks.eq("regex split", re.split(r"[,;]\s*", "east, west; yard"), ["east", "west", "yard"])
checks.eq("literal replace", "gate 2: closed".replace("closed", "open"), "gate 2: open")
checks.eq("cos radians tolerance", math.isclose(math.cos(math.pi / 3), 0.5), True)
checks.eq("log base two", math.log(512, 2), 9.0)
checks.eq("exponential inverse", math.isclose(math.exp(math.log(7)), 7.0), True)
generator = random.Random(843)
pick = generator.choice(["east", "west", "yard"])
sample = generator.sample(range(50), 5)
fraction = generator.random()
code = generator.randrange(6)
bounded = generator.randint(3, 5)
checks.eq("choice uses given population", pick in {"east", "west", "yard"}, True)
checks.eq("sample without replacement", len(sample) == len(set(sample)) == 5 and all(0 <= n < 50 for n in sample), True)
checks.eq("random float half-open bounds", 0 <= fraction < 1, True)
checks.eq("randrange half-open bounds", 0 <= code < 6, True)
checks.eq("randint inclusive bounds", 3 <= bounded <= 5, True)
same = random.Random(843)
checks.eq("seeded sequence reproduced on current runtime",
(same.choice(["east", "west", "yard"]), same.sample(range(50), 5),
same.random(), same.randrange(6), same.randint(3, 5)),
(pick, sample, fraction, code, bounded))
data = {"gate": "东", "hours": [4, 7], "open": True}
encoded = json.dumps(data, ensure_ascii=False)
checks.eq("JSON Chinese and structure round trip", ("东" in encoded, json.loads(encoded)), (True, data))
checks.eq("JSON tuple round trip changes type", json.loads(json.dumps((4, 7))), [4, 7])
@contextmanager
def running(server):
with server:
worker = Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
yield server.server_address[1]
finally:
server.shutdown()
worker.join()
class LocalHTTP(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def respond(self, data, *, cookie=False):
payload = json.dumps(data, ensure_ascii=False).encode("utf8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
if cookie:
self.send_header("Set-Cookie", "lab=ready; Path=/")
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
parts = urlsplit(self.path)
self.respond({"query": parse_qs(parts.query), "cookie": self.headers.get("Cookie")},
cookie=parts.path == "/start")
def do_POST(self):
size = int(self.headers["Content-Length"])
self.respond({"verb": self.command, "form": parse_qs(self.rfile.read(size).decode("ascii"))})
class LocalSMTP(StreamRequestHandler):
def handle(self):
self.connection.settimeout(5)
self.wfile.write(b"220 loopback.lab ESMTP ready\r\n")
envelope = {}
while line := self.rfile.readline(4096):
verb, _, value = line.strip().partition(b" ")
verb = verb.upper()
if verb in (b"EHLO", b"HELO"):
self.wfile.write(b"250 loopback.lab\r\n")
elif verb in (b"MAIL", b"RCPT"):
envelope[verb.decode("ascii")] = value.decode("ascii")
self.wfile.write(b"250 accepted\r\n")
elif verb == b"DATA":
self.wfile.write(b"354 end with period\r\n")
lines = []
while True:
content = self.rfile.readline(4096)
if not content:
return
if content == b".\r\n":
break
lines.append(content[1:] if content.startswith(b"..") else content)
envelope["data"] = b"".join(lines)
self.server.received.append(envelope)
self.wfile.write(b"250 stored only in memory\r\n")
elif verb == b"QUIT":
self.wfile.write(b"221 closing\r\n")
return
else:
self.wfile.write(b"502 unsupported fixture command\r\n")
def network_checks(checks, workspace):
cookie_jar = CookieJar()
opener = build_opener(ProxyHandler({}), HTTPCookieProcessor(cookie_jar))
with running(ThreadingHTTPServer(("127.0.0.1", 0), LocalHTTP)) as port:
base = f"http://127.0.0.1:{port}"
with opener.open(base + "/start?" + urlencode({"gate": "东"}), timeout=5) as response:
raw = response.read()
data = json.loads(raw.decode(response.headers.get_content_charset()))
checks.eq("HTTP decoded GET query", (response.status, data["query"]), (200, {"gate": ["东"]}))
download = workspace / "response.json"
download.write_bytes(raw)
checks.eq("HTTP download file matches response bytes", download.read_bytes(), raw)
with opener.open(base + "/next", timeout=5) as response:
checks.eq("Cookie forwarded to next request", json.load(response)["cookie"], "lab=ready")
body = urlencode({"gate": "东", "action": "scan"}).encode("ascii")
with opener.open(Request(base + "/submit", data=body, method="POST"), timeout=5) as response:
checks.eq("HTTP server received POST form", json.load(response),
{"verb": "POST", "form": {"gate": ["东"], "action": ["scan"]}})
server = TCPServer(("127.0.0.1", 0), LocalSMTP)
server.received = []
message = "Subject: owned example\r\n\r\nLoopback only"
with running(server) as port:
with smtplib.SMTP("127.0.0.1", port, timeout=5) as client:
rejected = client.sendmail("sender@example.invalid", ["receiver@example.invalid"], message)
checks.eq("SMTP loopback accepted recipient", rejected, {})
record, = server.received
checks.eq("SMTP envelope and exact message lines",
(record["MAIL"], record["RCPT"], record["data"].decode("ascii").splitlines()),
("FROM:<sender@example.invalid>", "TO:<receiver@example.invalid>", message.splitlines()))
def archive_and_measurement_checks(checks, workspace):
local_clock = datetime.now()
current_day = date.today()
checks.eq("date today lies inside observed interval",
local_clock.date() <= current_day <= datetime.now().date(), True)
offset = timezone(timedelta(hours=8))
fixed = datetime(2024, 2, 29, 9, 15, tzinfo=offset)
checks.eq("formatted explicit date and time", fixed.strftime("%Y-%m-%d %H:%M"), "2024-02-29 09:15")
checks.eq("timezone conversion to UTC", fixed.astimezone(timezone.utc).isoformat(), "2024-02-29T01:15:00+00:00")
checks.eq("leap-date difference in days", (date(2024, 3, 2) - date(2024, 2, 28)).days, 3)
checks.eq("time wall-clock UTC rendering", time.strftime("%Y-%m-%d", time.gmtime(0)), "1970-01-01")
start = time.perf_counter()
checks.eq("monotonic elapsed measurement nonnegative", time.perf_counter() - start >= 0, True)
raw = b"dispatch report\n" * 20
for module in (zlib, gzip, bz2):
compressed = module.compress(raw)
checks.eq(module.__name__ + " round trip", module.decompress(compressed), raw)
short = b"x"
checks.eq("zlib overhead can grow short input", len(zlib.compress(short)) > len(short), True)
checks.eq("crc32 known check value", zlib.crc32(b"123456789"), 0xcbf43926)
zip_path = workspace / "sample.zip"
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
archive.writestr("notes.txt", raw)
with zipfile.ZipFile(zip_path) as archive:
checks.eq("ZIP archive members CRC and payload", (archive.namelist(), archive.testzip(), archive.read("notes.txt")),
(["notes.txt"], None, raw))
tar_path = workspace / "sample.tar.gz"
with tarfile.open(tar_path, "w:gz") as archive:
member = tarfile.TarInfo("notes.txt")
member.size = len(raw)
archive.addfile(member, io.BytesIO(raw))
with tarfile.open(tar_path, "r:gz") as archive:
with archive.extractfile("notes.txt") as stream:
checks.eq("TAR archive member bytes without extraction", (archive.getnames(), stream.read()), (["notes.txt"], raw))
def temporary_swap():
first, second = 4, 7
hold = first
first = second
second = hold
return first, second
def unpack_swap():
first, second = 4, 7
first, second = second, first
return first, second
checks.eq("swap implementations equivalent", (temporary_swap(), unpack_swap()), ((7, 4), (7, 4)))
timings = {function.__name__: Timer(function).repeat(repeat=3, number=2000)
for function in (temporary_swap, unpack_swap)}
checks.eq("timeit records three finite repetitions for both", all(
len(samples) == 3 and all(math.isfinite(value) and value >= 0 for value in samples)
for samples in timings.values()), True)
def leaf():
return 2
def task():
return leaf() + leaf() + leaf()
profiler = profile.Profile()
checks.eq("profile observes actual function return", profiler.runcall(task), 6)
statistics = pstats.Stats(profiler, stream=io.StringIO())
counts = [row[1] for key, row in statistics.stats.items() if key[2] == "leaf"]
checks.eq("pstats records three leaf calls", counts, [3])
return timings
def average(values):
"""Calculate the arithmetic mean for a nonempty sequence.
>>> average([8, 12, 28])
16.0
"""
return sum(values) / len(values)
class AverageTests(unittest.TestCase):
def test_example(self):
self.assertEqual(average([8, 12, 28]), 16.0)
self.assertEqual(round(average([1, 4, 8]), 1), 4.3)
def test_empty(self):
self.assertRaises(ZeroDivisionError, average, [])
def test_argument_count(self):
self.assertRaises(TypeError, average, 8, 12, 28)
def test_checks(checks):
report = doctest.testmod(sys.modules[__name__])
checks.eq("doctest matches documented output", (report.failed, report.attempted), (0, 1))
wrong = doctest.DocTestParser().get_doctest(">>> average([8, 12, 28])\n15.0\n", {"average": average},
"negative example", "owned", 0)
result = doctest.DocTestRunner().run(wrong, out=io.StringIO().write)
checks.eq("doctest notices wrong output", (result.failed, result.attempted), (1, 1))
suite = unittest.defaultTestLoader.loadTestsFromTestCase(AverageTests)
outcome = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
checks.eq("unittest covers value empty and arity", (outcome.testsRun, outcome.wasSuccessful()), (3, True))
if __name__ == "__main__":
checks = Checks()
temp_parent = Path(gettempdir()).resolve()
with TemporaryDirectory(prefix="mbsky-stdlib-", dir=temp_parent) as directory:
workspace = Path(directory).resolve()
assert workspace.parent == temp_parent and workspace.name.startswith("mbsky-stdlib-")
file_and_process_checks(checks, workspace)
text_number_checks(checks)
network_checks(checks, workspace)
timings = archive_and_measurement_checks(checks, workspace)
test_checks(checks)
checks.eq("owned workspace removed after tests", workspace.exists(), False)
checks.finish("python3-stdlib", runtime=sys.version, operating_system=sys.platform,
timing_seconds=timings, timing_loops=2000,
protocol_scope="Loopback only, no external request, no real email delivery")
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
本章附件与实例包
常见错误与边界检查
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
技术规范与官方资料
练习与参考解答
查看参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。