Python 标准库索引 — python -c 一行流速查

Python 标准库 200+ 模块中精选约 25 个最常用模块。每个附带 python -c "" 一行流示例,方便 C 工程师快速上手。
全量分类索引见 4库索引。底层原理见 字节码深度剖析


系统与进程

模块类别一行流说明
sys系统python -c "import sys; print(sys.argv, sys.platform, sys.version)"命令行参数、平台、Python 版本、stdin/out、路径
os系统python -c "import os; print(os.getcwd(), os.listdir('.'))"工作目录、文件列表、环境变量、文件删除/重命名
shutil系统python -c "import shutil; shutil.copy2('src','dst'); shutil.rmtree('dir')"高级文件操作:复制保留元数据、递归删除目录
subprocess进程python -c "import subprocess; r=subprocess.run(['echo','hi'],capture_output=True,text=True); print(r.stdout)"启动子进程捕获输出,C 程序的管道搭档
argparse进程python -c "import argparse; p=argparse.ArgumentParser(); p.add_argument('--name'); print(p.parse_args(['--name','x']))"命令行参数解析,自动生成 —help
pathlib系统python -c "from pathlib import Path; p=Path('/tmp'); print(list(p.glob('*.txt')))"面向对象路径:glob/suffix/stem/read_text
tempfile系统python -c "import tempfile; f=tempfile.NamedTemporaryFile(suffix='.tmp'); print(f.name)"自动清理的临时文件/目录

文本与字符串

模块类别一行流说明
re文本python -c "import re; print(re.findall(r'\b\w{3}\b','abc def ghi'))"正则:search/match/findall/sub/split
string文本python -c "import string; print(string.ascii_letters, string.digits, string.punctuation)"字符常量集、Formatter 模板
textwrap文本python -c "import textwrap; print(textwrap.fill('hello '*20,width=20))"段落换行、缩进、去缩进
difflib文本python -m difflib file1.txt file2.txt文本比对,生成 unified diff

容器与数据结构

模块类别一行流说明
collections容器python -c "from collections import Counter,deque,defaultdict; d=defaultdict(int); d['a']+=1; print(d)"Counter(计数), deque(双端队列), defaultdict(带默认值字典), OrderedDict, namedtuple
heapq容器python -c "import heapq; h=[3,1,4,2]; heapq.heapify(h); print(heapq.heappop(h))"最小堆:heappush/heappop/heapify/nlargest/nsmallest
bisect容器python -c "import bisect; a=[1,2,4,5]; i=bisect.bisect_left(a,3); bisect.insort(a,3); print(a,i)"二分查找插入点,O(log n)
array容器python -c "from array import array; a=array('i',[1,2,3]); print(a.tolist())"C 风格紧密数组,比 list 高效

迭代与函数工具

模块类别一行流说明
itertools迭代python -c "import itertools; print(list(itertools.chain('AB','12')))"迭代器:chain/count/cycle/permutations/combinations/product/groupby
functools函数python -c "import functools; @functools.lru_cache\ndef fib(n): return n if n<2 else fib(n-1)+fib(n-2); print(fib(100))"lru_cache(无脑加速递归), reduce, partial, wraps
operator函数python -c "from operator import itemgetter,attrgetter; data=[(1,'b'),(2,'a')]; print(sorted(data,key=itemgetter(1)))"itemgetter/attrgetter 替代 lambda,运算符函数

文件格式

模块类别一行流说明
json格式python -c "import json; d={'a':1}; print(json.dumps(d)); print(json.loads('{\"b\":2}'))"JSON 编解码,Python ⇄ C 数据交换首选
csv格式python -c "import csv,io; r=csv.reader(io.StringIO('a,b\\n1,2')); print(list(r))"CSV 读写,支持 DictReader/DictWriter
xml格式python -c "import xml.etree.ElementTree as ET; r=ET.fromstring('<a><b>1</b></a>'); print(r.find('b').text)"ElementTree XML 解析器
configparser格式python -c "import configparser,io; c=configparser.ConfigParser(); c.read_string('[D]\\nk=v'); print(c['D']['k'])"INI 配置文件解析
struct格式python -c "import struct; packed=struct.pack('<i2f',42,1.0,2.0); print(struct.unpack('<i2f',packed))"C 结构体二进制打包/解包,< 小端 = 本机

数学与随机

模块类别一行流说明
math数学python -c "import math; print(math.sqrt(2), math.pi, math.factorial(5))"对标 C math.h:三角函数、对数、阶乘、常量
random数学python -c "import random; print(random.choice([1,2,3]), random.sample(range(10),3))"伪随机:choice/shuffle/randint/seed/normalvariate
statistics数学python -c "import statistics as s; print(s.mean([1,2,3]), s.stdev([1,2,3]))"平均值/中位数/众数/标准差/方差
decimal数学python -c "from decimal import Decimal; print(Decimal('0.1')+Decimal('0.2')==Decimal('0.3'))"精确十进制,避免浮点误差
fractions数学python -c "from fractions import Fraction; print(Fraction(1,3)+Fraction(1,3))"有理数精确运算(分数)

日期时间

模块类别一行流说明
datetime时间python -c "from datetime import datetime,timedelta; now=datetime.now(); print(now+timedelta(days=1))"datetime/date/time/timedelta 对象
time时间python -c "import time; t0=time.perf_counter(); time.sleep(0.1); print(time.perf_counter()-t0)"时间戳/sleep/高精度计时
calendar时间python -c "import calendar; print(calendar.month(2026,1)); print(calendar.isleap(2026))"日历打印/闰年判断/星期运算

并发

模块类别一行流说明
threading并发python -c "import threading; t=threading.Thread(target=lambda:print('hi')); t.start(); t.join()"OS 线程(受 GIL 限制,CPU 密集无效)
multiprocessing并发python -c "from multiprocessing import Pool; with Pool(4) as p: print(p.map(str,range(10)))"多进程(绕过 GIL),进程间通讯
concurrent.futures并发python -c "from concurrent.futures import ThreadPoolExecutor; ex=ThreadPoolExecutor(4); list(ex.map(pow,[2]*5,range(5)))"统一的线程/进程池接口
asyncio并发python -c "import asyncio; asyncio.run(asyncio.sleep(0.1)); print('done')"单线程异步框架,适合 I/O 密集型

网络

模块类别一行流说明
socket网络python -c "import socket; print(socket.gethostbyname('localhost'))"BSD socket 接口,与 C 的 socket.h 对应
urllib网络python -c "from urllib.request import urlopen; r=urlopen('http://httpbin.org/get'); print(r.status)"标准库 HTTP 客户端(建议第三方用 requests)
http.server网络python -m http.server 8000一行启动静态文件 HTTP 服务器
email网络python -c "from email.mime.text import MIMEText; msg=MIMEText('body'); msg['Subject']='test'"MIME 邮件构建与解析
ssl网络python -c "import ssl; print(ssl.OPENSSL_VERSION)"TLS/SSL 安全套接字包装

调试与测试

模块类别一行流说明
pdb调试python -c "import pdb; pdb.set_trace()"断点调试器(对标 GDB 的 break/step/print)
logging调试python -c "import logging; logging.basicConfig(level=logging.DEBUG); logging.info('msg')"可配置的日志系统
trace调试python -m trace --trace script.py追踪每一行代码的执行
unittest测试python -m unittest discover -s testsxUnit 风格单元测试
doctest测试python -m doctest -v module.py从 docstring 提取 >>> 示例运行验证

代码工具

模块类别一行流说明
ast代码python -c "import ast; tree=ast.parse('x=1+2'); print(ast.dump(tree,indent=2))"抽象语法树:Python 代码的结构化分析
dis代码python -c "import dis; dis.dis(compile('x=1+2','','exec'))"字节码反汇编(Python 的 “objdump”)
inspect代码python -c "import inspect; print(inspect.signature(print))"运行时反射:获取源码/签名/参数列表
types代码python -c "import types; f=types.SimpleNamespace(x=1,y=2); print(f.x)"类型对象和动态类型创建
typing代码python -c "from typing import List,Optional,Tuple; print(Tuple[int,str])"类型注解,提供 C 级别的”类型文档”

快速参考:按需求查找

需求一行流
打印命令行参数python -c "import sys; print(sys.argv)"
获取当前目录文件列表python -c "import os; print(os.listdir('.'))"
执行外部命令获取输出python -c "import subprocess; print(subprocess.check_output(['echo','hi'],text=True))"
正则查找所有数字python -c "import re; print(re.findall(r'\d+','a1b22c333'))"
字符串出现次数统计python -c "from collections import Counter; print(Counter('abracadabra'))"
笛卡尔积python -c "import itertools; print(list(itertools.product('AB','12')))"
JSON 字符串 → 字典python -c "import json; print(json.loads('{\"k\":[1,2]}'))"
C 结构体打包python -c "import struct; struct.pack('<i2f',1,2.0,3.0)"
计算平方根python -c "import math; print(math.sqrt(2))"
随机抽取样本python -c "import random; print(random.sample(range(1,50),6))"
当前日期时间python -c "from datetime import datetime; print(datetime.now())"
高精度计时python -c "import time; t0=time.perf_counter(); x=sum(range(10**7)); print(time.perf_counter()-t0)"
起 HTTP 服务器python -m http.server 8080
字节码反编译python -c "import dis; dis.dis('x=1+2')"
带缓存的递归python -c "from functools import lru_cache; print((lambda f:(f(100)))((lambda n:n if n<2 else f(n-1)+f(n-2)))" (慎用,建议写两行)
断点调试python -c "import pdb; pdb.set_trace()"
日志输出python -c "import logging; logging.basicConfig(level=logging.INFO); logging.info('started')"
查看函数签名python -c "import inspect; print(inspect.signature(sorted))"
类型注解python -c "from typing import List; x: List[int] = [1,2,3]"

练习

以下题目用于验证本章所学内容:

题号题目链接涉及知识点
本章无对应力扣题请用动手练习题自检