写小脚本调外部工具时,直接 subprocess.run(["ffmpeg", ...]),机器上没装的话会在运行到那一步才炸 FileNotFoundError。如果想把错误提示做得友好一点,可以先用标准库的 shutil.which() 探一下。
环境:Python 3.10+,Linux/macOS/Windows,只用标准库。保存为 which-before-run.py:
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")
result = subprocess.run(
[python, "--version"],
text=True,
capture_output=True,
check=True,
)
print(result.stdout.strip() or result.stderr.strip())
跑一下:
python3 which-before-run.py
这个适合放在脚本启动阶段,缺什么直接报清楚。还有个小细节:which() 返回的是解析后的路径,后面 subprocess.run() 继续用列表参数就行,别为了拼命令字符串再绕回 shell。