90 % 场景够用!Python subprocess & signal 最小记忆手册


一、为什么只需要记“最小集合”

  • subprocess 文档很长,但日常 90 % 场景就是“跑命令、抓输出、建管道”。
  • signal 涉及平台差异,背完整张表不如记住 3-4 个常用信号。
  • 把“最小可运行代码”贴进笔记,用时复制即可。

二、subprocess 最小记忆清单

需求模板代码
运行命令并检查返回码subprocess.run(cmd, check=True)
抓 stdout / stderrsubprocess.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 index.rst | grep ".. literalinclude" | cut -f 3 -d:
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 最小记忆清单

信号何时用
SIGINTCtrl-C 优雅退出
SIGTERMkill <pid> 优雅退出
SIGALRM实现超时
SIGUSR1/SIGUSR2自定义通知(热加载、重读配置)

3.1 守护进程:捕获 SIGINT/SIGTERM 优雅退出

import signal
import sys
import time

def graceful(signum, frame):
    print(f"\n[{signum}] 收到退出信号,清理资源…")
    # TODO: 这里做文件、网络或数据库清理
    sys.exit(0)

signal.signal(signal.SIGINT, graceful)   # Ctrl-C
signal.signal(signal.SIGTERM, graceful)  # kill <pid>

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)          # 2 秒后发送 SIGALRM
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 分钟写完。
需要更复杂功能时再翻官方文档即可!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值