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

在使用 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 脚本的执行结果,从而在管道中实现所需的错误处理和传递。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值