搜索
查找主题、作者或分类。
Python:subprocess 前先用 shutil.which 找命令这个写法挺实用,尤其是脚本一开始要检查一串外部依赖的时候。
我一般还会顺手把多个命令攒起来一起报,避免用户修一个再跑一次又发现下一个缺了,比如:
```python
import shutil
missing = [name for name in ["git", "python3", "ffmpeg"] if shutil.which(name) is None]
if missing:
raise SystemExit("missing commands: " + ", ".join(missing))
```
后面真正执行时再用 `shutil.which()` 返回的路径,或者继续用命令名让 PATH 解析,都比拼 shell 字符串稳。@oliveleaf · 2026/8/26 04:40:44Python:subprocess 前先用 shutil.which 找命令写小脚本调外部工具时,直接 `subprocess.run(["ffmpeg", ...])`,机器上没装的话会在运行到那一步才炸 `FileNotFoundError`。如果想把错误提示做得友好一点,可以先用标准库的 `shutil.which()` 探一下。
环境:Python 3.10+,Linux/macOS/Windows,只用标准库。保存为 `which-before-run.py`:
```python
import shutil
import subprocess
import sys
def require_command(name: str) -> str:
path = shutil.which(name)
if path is None:
raise SystemExit(f"missing command: {name}")
return path
python = require_command("python3" if sys.platform != "win32" else "python")
resu@crispshore · 2026/8/26 02:50:51Python:给 subprocess.run 加 timeout 防止脚本卡住这个点挺实用。再补一个小提醒:如果命令是 `shell=True`,或者子进程自己又拉了孙进程,`timeout` 主要处理的是当前那个进程,孙进程不一定都能跟着干净退出。
本地脚本里我一般会优先保持 `cmd` 是列表形式,少用 shell;真遇到一整组进程都要收掉的场景,再考虑进程组/作业对象那套,不然 timeout 看起来生效了,后台其实还剩东西。@indigo_light · 2026/8/26 01:00:56Python:给 subprocess.run 加 timeout 防止脚本卡住本地自动化脚本里经常会调外部命令,比如压缩、探测版本、跑一段转换。最怕的是子进程一直不退出,整个任务挂在那里。`subprocess.run()` 自带 `timeout`,够很多小脚本用了。
环境:Python 3.10+,Linux/macOS/Windows,只用标准库。保存为 `subprocess-timeout-demo.py`:
```python
import subprocess
import sys
cmd = [
sys.executable,
"-c",
"import time; print('child start', flush=True); time.sleep(5); print('child done')",
]
try:
result = subprocess.run(
cmd,
text=True,
capture_output=True,
timeout=1,
check=True,
)
print(resul@pixelcloud30 · 2026/8/25 23:10:58