首页 > 编程语言 >python 通过 subprocess 运行的代码 exit(1) 不能使得pipeline fail

python 通过 subprocess 运行的代码 exit(1) 不能使得pipeline fail

时间:2024-05-31 23:29:47浏览次数:14  
标签:pipeline returncode python subprocess 进程 print output check

在使用 Python 的 subprocess 模块运行外部命令时,如果你希望子进程的退出状态码能够影响 Python 脚本的执行结果,尤其是在使用管道(pipeline)时,你需要手动检查子进程的返回码并采取相应的措施。简单地使用 subprocess.runsubprocess.call 运行子进程并不会自动使 Python 脚本失败,即使子进程的退出状态码是非零的。

以下是一些解决方案,以确保子进程的退出状态码能影响到 Python 脚本的执行:

使用 subprocess.run

subprocess.run 可以捕获子进程的返回码,并且可以通过检查 returncode 来决定是否退出 Python 脚本。

import subprocess

result = subprocess.run(['your_command', 'arg1', 'arg2'])
if result.returncode != 0:
    print(f"Command failed with return code {result.returncode}")
    exit(result.returncode)

使用 subprocess.check_call

subprocess.check_call 在子进程返回非零退出码时会抛出 subprocess.CalledProcessError 异常,你可以捕获这个异常并采取相应的措施。

import subprocess

try:
    subprocess.check_call(['your_command', 'arg1', 'arg2'])
except subprocess.CalledProcessError as e:
    print(f"Command failed with return code {e.returncode}")
    exit(e.returncode)

使用 subprocess.check_output

subprocess.check_output 在子进程返回非零退出码时也会抛出 subprocess.CalledProcessError 异常。

import subprocess

try:
    output = subprocess.check_output(['your_command', 'arg1', 'arg2'], stderr=subprocess.STDOUT)
    print(output)
except subprocess.CalledProcessError as e:
    print(f"Command failed with return code {e.returncode}")
    print(f"Output: {e.output.decode()}")
    exit(e.returncode)

在管道中使用

如果你在管道中使用多个子进程,可以将它们组合在一起,并在每个步骤后检查返回码。

import subprocess

try:
    p1 = subprocess.Popen(['command1', 'arg1'], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['command2', 'arg2'], stdin=p1.stdout, stdout=subprocess.PIPE)
    p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits
    output, error = p2.communicate()
    
    if p1.returncode != 0:
        print(f"Command1 failed with return code {p1.returncode}")
        exit(p1.returncode)
    if p2.returncode != 0:
        print(f"Command2 failed with return code {p2.returncode}")
        exit(p2.returncode)

    print(output.decode())
except subprocess.CalledProcessError as e:
    print(f"Pipeline failed with return code {e.returncode}")
    exit(e.returncode)

总结

  • 检查返回码:确保在运行子进程后检查其返回码,并根据需要退出或处理错误。
  • 捕获异常:使用 check_callcheck_output 等方法自动捕获和处理异常。
  • 管道处理:在管道处理多个子进程时,逐个检查每个子进程的返回码。

通过上述方法,可以确保子进程的退出状态码能够影响到 Python 脚本的执行结果,从而在管道中实现所需的错误处理和传递。

标签:pipeline,returncode,python,subprocess,进程,print,output,check
From: https://blog.csdn.net/lycwhu/article/details/139345499

相关文章

  • python pip install git+ssh
    网上比较容易找到的是pipinstallgit+https://github.com/waketzheng/fastapi-cdn-host.git这种方式如果电脑未配置或没启用外网加速器,这种方式简直慢得像蜗牛,改用ssh则会块很多很多:一般情况pipinstallgit+ssh://[email protected]/waketzheng/fastapi-cdn-host.git即:只需把h......
  • Python中的tqdm库:简化进度条的实用工具
    介绍在Python编程中,经常会遇到需要显示长时间运行任务的进度的情况,这时候使用进度条工具可以让用户清晰了解任务的完成进度。tqdm是一个Python的进度条库,它的全称是"taqaddum",这个词来自阿拉伯语,意为"进步"。tqdm库提供了一种在Python中显示进度条的简单而灵活的方式......
  • 基于Python的房屋信息可视化及价格预测系统
    基于Python的房屋信息可视化及价格预测系统开发语言:Python数据库:MySQL所用到的知识:Django框架工具:pycharm、Navicat、Maven系统功能实现首页展示用户在输入正确的域名后即可访问本系统,不过用户在注册用户之前只能访问系统公告及站内新闻等信息。本系统的首页使用上中下......
  • Python背记手册让我拿到了华为OD的Offer(附面经和文档)
    24届-Python面经(华为OD)4月4日-6日24应届,目标院校非科班。临近毕业,校招没找到合适的工作,因为自己算是零基础,先从栗栗姐给的几道入门基础题开始刷,熟悉一些常考的数据结构和算法,刚开始刷基本不太会,刷的也比较慢,后来偶然得到学姐的Python面试笔记,刷题速度飞升,编程和理解能力飞升......
  • 线性规划灵敏度分析——Python实现
    灵敏度分析(SensitivityAnalysis)是线性规划的一个重要部分,用于研究在模型参数发生变化时,最优解和目标函数值的变化情况。它能够识别和评估参数变动对解的影响,从而帮助决策者了解模型的稳定性及其对不同条件变化的反应。例如,通过灵敏度分析,决策者可以确定在什么范围内,目标函数系数......
  • ESP32 实时人脸检测系统:ESP32 与上位机通信(microPython框架)
    实时人脸检测系统:ESP32与上位机通信在这篇博客中,我将介绍如何使用ESP32摄像头捕获图像,并通过UDP协议将图像传输到上位机进行实时人脸检测。我们将使用Python编程语言和OpenCV库来实现上位机端的人脸检测功能。硬件与软件准备ESP32开发板:我们使用ESP32开发板......
  • windows 电脑下使用pyenv安装python太慢 完美解决方案
    打开https://www.python.org/ftp/python找到需要安装的版本然后下载python-3.8.0-amd32.exe或python-3.8.0-amd64.exe,现在都是64位的,下载之后然后放到pyenv本地路径里面的install_cache文件夹中执行安装命令pyenvinstall3.8.0大功搞成......
  • 用Python脚本迁移MongoDB数据到金仓-kingbase数据库
    1、首先需要明确MongoDB与kingbase的对应关系,collection相当于table,filed相当于字段,根据这个对应关系创建表;此次迁移的MongoDB里的数据字段是:_id(自动生成的objectid),image(转成二进制存储的文档)所以在金仓里创建表createtableadmin(idvarchar,imagebytea);2、安装Python环境......
  • python数据处理
    Python在数据处理方面非常强大,主要得益于其丰富的库,如Pandas、NumPy和Matplotlib等。以下是一些基本的Python代码示例,用于数据加载、处理和可视化。1.导入库importpandasaspdimportnumpyasnpimportmatplotlib.pyplotasplt2.加载数据#从CSV文件加载......
  • Python-pptx正确设置中文字体
    使用pptx_ea_font库设置中文字体:1.安装pptx_ea_font库:pipinstallpptx-ea-font2.p=text_frame.paragraphs[0]#取文本段落 run=p.runs[0]#取文本运行对象,该对象为段落的子元素pptx_ea_font.set_font(run,'微软雅黑')#以下方法只能修改数字和英文#run.font.name=......