首页 > 解决方案 > 如何从 Python 的子进程中捕获 sys.exit()?

问题描述

我创建了一个master.py来启动其他脚本。

from subprocess import PIPE, STDOUT, run


def main():
    command = ["python3", "file1.py"]
    print("Executing: {}".format(command))
    exit_code, output_string = run_command(command)
    print(output_string)

    command = ["python3", "file2.py"]
    print("Executing: {}".format(command))
    exit_code, output_string = run_command(command)
    print(output_string)

    command = ["python3", "file3.py"]
    print("Executing: {}".format(command))
    exit_code, output_string = run_command(command)
    print(output_string)

    print("Exiting master.py with status_code of {} because {NAME_OF_FILE_THAT_FAILED} failed.")


def run_command(command_to_run):
    result = run(command_to_run, stdout=PIPE, stderr=STDOUT)
    return result.returncode, result.stdout.decode()


if __name__ == "__main__":
    main()

我正在尝试捕获sys.exit()每个子进程脚本,即捕获什么file1.pyfile2.py然后file3.py退出。如果所有作业都通过,那么master.py将存在,0但如果至少 1 个子作业失败并退出,1那么我希望主作业也以 1 退出。

一旦它sys.exit从所有子作业中捕获,根据它们的结果,我想在主的最终输出(打印语句)上打印该错误

标签: pythonpython-3.xsubprocesssys

解决方案


如果子进程以状态码 1 退出,则该值将被存储result.returncoderesult.stderr.decode()您也可以通过返回来获取错误消息run_command()

对于master.py每个子进程终止后的行为,我相信你可以简单地使用 if else 语句来控制它。


推荐阅读