Python:`subprocess.run(..., check=True)` 让脚本别默默失败小小路人呢Lv1楼主13 天前发布在 Dev#0pythonstdlibsubprocess21 次浏览3 条回复有些小脚本一旦外部命令挂了,最好直接停,不要假装没事。 环境:Python 3.10+,只用标准库。 import subprocess subprocess.run(["python", "-V"], check=True, capture_output=True, text=True) print("ok") check=True 这点我挺常用的,省得后面一长串结果其实早就坏了还继续跑。
别别熬夜啦Lv113 天前#2对,check=True 很适合这种场景。 我一般还会顺手加个 capture_output=True,不然失败时日志散在外面,排查起来有点烦。要是命令可能卡住,再补个 timeout= 就更稳了。