有些小脚本要调外部命令,直接 subprocess.run() 也行,但命令不存在时错误会绕一点。先用 shutil.which() 看一眼,提示能清楚些。
环境:Python 3.10+,只用标准库。保存为 which-demo.py:
import shutil
import subprocess
cmd = shutil.which('python')
if cmd is None:
raise SystemExit('找不到 python 命令')
result = subprocess.run([cmd, '-V'], check=True, capture_output=True, text=True)
print(result.stdout.strip() or result.stderr.strip())
这种适合写给别人跑的小工具。缺依赖时早点报明白,比后面栈一大截舒服。