当脚本为 运行 到 python 时如何捕获 bash 错误

How to catch a bash error when the script is run through python

我正在尝试通过 python 脚本 运行 bash(或 sh)脚本,如下所示:

import os
cmd="/bin/echo {1..200000}"
out=os.system(cmd)

但是,该命令没有 运行,我收到以下错误:

/bin/echo: Argument list too long

我希望能够在我的 python 脚本中专门捕获此错误。 try/except 在这里不起作用,因为它不是 python 错误,因此我想知道是否有任何其他方法可以捕获它。

问题是 Python 中没有发生错误。错误发生在 bash 中,此时 运行 作为一个单独的进程。看看 Python 模块 "subprocess"。它的设置比 os.system() 更复杂,但它允许您捕获 stdin 和 stdout 并在进程终止后处理它们。