python - 如何从 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.py
,file2.py
然后file3.py
退出。如果所有作业都通过,那么master.py
将存在,0
但如果至少 1 个子作业失败并退出,1
那么我希望主作业也以 1 退出。
一旦它sys.exit
从所有子作业中捕获,根据它们的结果,我想在主的最终输出(打印语句)上打印该错误
解决方案
如果子进程以状态码 1 退出,则该值将被存储result.returncode
。result.stderr.decode()
您也可以通过返回来获取错误消息run_command()
对于master.py
每个子进程终止后的行为,我相信你可以简单地使用 if else 语句来控制它。
推荐阅读
- c# - 在 OPC UA (UA-.NETStandard) 中创建自定义复杂数据类型
- pm2 - pm2 将生产和登台部署到具有不同应用程序名称的相同服务
- sql-server - SQL Server 可以在 SCO SantaCruz Operations SO (Linux) 上运行吗?
- python - 如何使用 __getattribute__ 或类似方法捕获多个属性及其参数?
- javascript - Node.js 中的 OAuth1.0 标头
- google-data-studio - 围绕数据工作室构建
- google-bigquery - BigQuery DML 更新是否比联接更好?
- google-cloud-platform - 如何输出创建的资源的属性?
- javascript - 我的 CSS 在 localhost 中运行良好,但在我在线发布应用程序时中断?
- r - 下载非 CRAN 软件包时遇到问题