90 % 场景够用!Python subprocess & signal 最小记忆手册
一、为什么只需要记“最小集合”
- subprocess 文档很长,但日常 90 % 场景就是“跑命令、抓输出、建管道”。
- signal 涉及平台差异,背完整张表不如记住 3-4 个常用信号。
- 把“最小可运行代码”贴进笔记,用时复制即可。
二、subprocess 最小记忆清单
需求 | 模板代码 |
---|
运行命令并检查返回码 | subprocess.run(cmd, check=True) |
抓 stdout / stderr | subprocess.run(cmd, capture_output=True, text=True) |
丢黑洞(不显示) | subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
简单管道 cat|grep|cut | 见下方完整示例 |
2.1 最小管道示例:cat → grep → cut
import subprocess as sp
cat = sp.Popen(['cat', 'index.rst'], stdout=sp.PIPE)
grep = sp.Popen(['grep', '.. literalinclude'], stdin=cat.stdout, stdout=sp.PIPE)
cut = sp.Popen(['cut', '-f', '3', '-d:'], stdin=grep.stdout, stdout=sp.PIPE)
for line in cut.stdout:
print(line.decode().strip())
没有 index.rst
?把第一个命令换成 ['echo', 'hello:world']
自己造数据即可。
三、signal 最小记忆清单
信号 | 何时用 |
---|
SIGINT | Ctrl-C 优雅退出 |
SIGTERM | kill <pid> 优雅退出 |
SIGALRM | 实现超时 |
SIGUSR1/SIGUSR2 | 自定义通知(热加载、重读配置) |
3.1 守护进程:捕获 SIGINT/SIGTERM 优雅退出
import signal
import sys
import time
def graceful(signum, frame):
print(f"\n[{signum}] 收到退出信号,清理资源…")
sys.exit(0)
signal.signal(signal.SIGINT, graceful)
signal.signal(signal.SIGTERM, graceful)
print("PID:", __import__('os').getpid())
while True:
time.sleep(2)
3.2 超时保护:2 秒没完成就抛异常
import signal
def _timeout_handler(signum, frame):
raise TimeoutError("操作超时")
signal.signal(signal.SIGALRM, _timeout_handler)
signal.alarm(2)
try:
import time; time.sleep(10)
finally:
signal.alarm(0)
四、一张图总结(保存即可)
场景 | 关键 API |
---|
跑命令 | subprocess.run |
建管道 | Popen + stdout=PIPE |
优雅退出 | signal.signal(SIGTERM, handler) |
超时 | signal.alarm + SIGALRM |
五、结语
把本文的 3 段示例代码放进你的 snippets,90 % 的脚本需求都能 1 分钟写完。
需要更复杂功能时再翻官方文档即可!