想掌握 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