Check a command's return code when subprocess raises a CalledProcessError exception

后端 未结 2 970
鱼传尺愫
鱼传尺愫 2020-12-05 10:20

I want to capture the stdout stream of a shell command in a python (3) script, and being able, at the same time, to check the return code of the shell command i

相关标签:
2条回答
  • 2020-12-05 10:53

    Most likely my answer is no longer relevant, but I think it may be solved with this code:

    import subprocess
    failing_command='ls non_existent_dir'
    
    try:
        subprocess.check_output(failing_command, shell=True, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        ret =   e.returncode 
        if ret in (1, 2):
            print("the command failed")
        elif ret in (3, 4, 5):
            print("the command failed very much")
    
    0 讨论(0)
  • 2020-12-05 11:13

    To get both the process output and the returned code:

    from subprocess import Popen, PIPE
    
    p = Popen(["ls", "non existent"], stdout=PIPE)
    output = p.communicate()[0]
    print(p.returncode)
    

    subprocess.CalledProcessError is a class. To access returncode use the exception instance:

    from subprocess import CalledProcessError, check_output
    
    try:
        output = check_output(["ls", "non existent"])
        returncode = 0
    except CalledProcessError as e:
        output = e.output
        returncode = e.returncode
    
    print(returncode)
    
    0 讨论(0)
提交回复
热议问题