想掌握 Python 标准库,读它的官方文档很重要。本文并不是此文档的复制版,而是对每个库(笔者经常使用的)的归纳以及它的主要函数,由此用什么库内心就会有数了。html
文本处理
- re: 正则表达式支持(pattern, string):match, search, findall, sub, split, finditer
- string: 提供了字符集:ascii_lowercase, ascii_uppercase, digits, hexdigits, punctuation
数据结构
- collections: 其余数据结构: deque, Counter, defaultdict, namedtuple
- pprint: 漂亮地输出文本: pprint
- datetime: 处理日期,建议用arrow代替
- copy: 浅拷贝和深拷贝: copy, deepcopy
- heapq: 堆排序实现: nlargest, nsmallest, merge
- enum: 枚举类的实现: Enum
数学
- math: 数学函数库
- random: 随机数: choice, randint, randrange, sample, shuffle, gauss
- fractions: 分数运算: Fraction as F
- statistics: 统计学函数: mean, median, mode, variance
函数式编程模块
- itertools: 迭代器工具: permutations, combinations, product, chain, repeat, cycle, accumulate
- functools: 函数工具: @wraps, reduce, partial, @lrucache, @singledispatch
- operator: 基本运算符
文件目录访问
- pathlib: 对路径对象进行操做: Path
- shutil: 文件操做: copy, copytree, rmtree, move, make_archive
- tempfile:用来建立临时文件,一关闭就自动删除:TemporaryFile
- linecache: 读取文件的行,缓存优化: getline, getlines
数据持久化
- pickle: 文件 pickle 序列化: dump, dumps, load, loads
- sqlite3: sqlite 数据库接口
文件格式
- csv: 处理 csv 文件: reader, writeheader, writerow
- configparser: 处理配置文件: ConfigParser, get, sections
密码学
- hashlib: 哈希加密算法: sha256, hexdigest
- secrets:密钥生成:token_bytes, token_hex, token_urlsafe
操做系统
- os: 操做系统相关
- time: 计时器: time, sleep, strftime
- io: 在内存中读写 str 和 bytes: StringIO, BytesIO, write, get_value
- argparse, getopt: 命令行处理,建议用click代替
- logging: 打日志: debug, info, warning, error, critical,建议用loguru代替
- getpass: 获取用户输入的密码: getpass
- platform: 提供跨平台支持: system
并发执行
- concurrent.futures: 异步执行模型: ThreadPoolExecutor, ProcessPoolExecutor
- threading: 多线程模型: Thread, start, join
- multiprocessing: 多进程模型: Pool, map, Process
- subprocess: 子进程管理: run
- queue: 同步队列: Queue
进程间通讯和网络
- asyncio: 异步 IO, eventloop, 协程: get_event_loop, run_until_complete, wait, run
网络数据处理
- json: 处理 json: dumps, loads
- base64: 处理 base64 编码: b64encode, b64decode
网络协议支持
- webbrowser: 打开浏览器: open
- wsgiref: 实现 WSGI 接口
- uuid: 通用惟一识别码: uuid1, uuid3, uuid4, uuid5
- ftplib, poplib, imaplib, smptlib: 实现各类网络协议
其他库用requests代替python
GUI
开发工具
- typing: 类型注解,可配合mypy对项目进行静态类型检查
- doctest: 文档测试: python -m doctest [pyfile]
- unittest: 单元测试: python -m unittest [pyfile]
DEBUG 和性能优化
- pdb: Python Debugger: python -m pdb [pyfile]
- cProfile: 分析程序性能: python -m cProfile [pyfile]
- timeit: 检测代码运行时间: python -m timeit [pyfile]
软件打包发布
- setuptools: 编写 setup.py 专用: setup, find_packages
- venv: 建立虚拟环境,建议用pipenv代替
Python 运行时服务
- builtins: 全部的内置函数和类,默认引进(还有一个boltons扩充了许多有用的函数和类)
- __main__: 顶层运行环境,使得 python 文件既能够独立运行,也能够当作模块导入到其余文件。
- sys: 系统环境交互: argv, path, exit, stderr, stdin, stdout
- inspect:用于获取对象的各类信息(自省)
- contextlib: 上下文管理器实现: @contextmanager
自定义 Python 解释器
- code: 实现自定义的 Python 解释器(好比 Scrapy 的 shell): interact