Python 调 shell 命令一直报 CalledProcessError returncode 1 怎么拿到真实 stderr 而不是空

现象:subproCess.run 抛 CalledProcessError,stderr 打印是空

用 Python 调 ffmpeg 压缩视频,subprocess.run 抛 CalledProcessError,returncode 是 1,按说 stderr 能看到 ffmpeg 报错,但 print(e.stderr) 出来是空。把 check=False 去掉自己判断 returncode 也一样,stderr 就是空。排查半天发现是 shell=True 导致 pipe 没正确接。

先搞清楚 check 和 shell 两个参数的组合

subprocess.run 默认 check=False、shell=False,任何命令都能跑通不抛异常,得自己判断 returncode。加上 check=True 才会在 returncode 非零时抛 CalledProcessError。但 shell=True 有坑:先启一个 shell(默认 /bin/sh),再在 shell 里执行命令,shell 和子进程间的 pipe 容易串。特别是 ffmpeg 这种把错误写在 stdout 的程序,shell=True 加 capture_output=True 反而把真正的 stderr 丢了。

# 错误写法:shell=True 抓不到真正的 stderr
result = subprocess.run("ffmpeg -i input.mp4 out.mp4",
                       capture_output=True, text=True, check=True, shell=True)
print(result.stderr)  # 可能是空的

# 正确写法:shell=False,参数传列表
result = subprocess.run(["ffmpeg", "-i", "input.mp4", "out.mp4"],
                       capture_output=True, text=True, check=True)
print(result.stderr)  # 能看到 ffmpeg 真正的错误信息

必须用 shell=True 时用 Popen 手动接 PIPE

含管道、重定向或通配符的命令,必须 shell=True 才能生效。这时用 Popen 手动把 stderr 接出来,比 run 更可控:

p = subprocess.Popen("ls -la *.mp4 | head -5",
                     shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print(stdout.decode(), stderr.decode())

CalledProcessError 里的 stderr 怎么拿

用 run 且 check=True 时,CalledProcessError 对象本身携带 stderr,前提是传了 capture_output=True。直接 e.stderr 就能拿到:

try:
    subprocess.run(["ffmpeg", "-i", "input.mp4", "out.mp4"],
                   capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
    print(f"退出码: {e.returncode}")
    print(f"错误输出: {e.stderr}")  # 这里就能看到

总结:subprocess 拿不到 stderr 八成是 shell=True 和 capture_output=True 组合的问题。能不用 shell 就不用,拆成列表传参最稳。必须用 shell 时用 Popen + communicate。遇到 CalledProcessError 直接从异常对象的 .stderr 属性拿,不要重跑。

您可以还会对下面的文章感兴趣: