Skip to main content
 首页 » 编程设计

python之如何从 Python 的子进程中捕获 sys.exit()

2024年11月24日9mate10pro

我创建了一个 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() 

我正在 try catch 每个子进程脚本的 sys.exit(),即捕获什么 file1.py、file2.py 和 file3.py 退出。如果所有作业都通过,则 master.py 将以 0 存在,但如果至少有 1 个子作业失败并以 1 退出,那么我想要主作业也以 1 退出。

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

请您参考如下方法:

如果子进程以状态码 1 退出,则该值将存储在 result.returncode 中。您还可以通过在 run_command()

中返回 result.stderr.decode() 来获取错误消息

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