Get exit code and stderr from subprocess call

后端 未结 5 2220
逝去的感伤
逝去的感伤 2020-12-14 05:07

I read up on the functions provided by subprocess - call, check_call, check_output, and understand how each works and differs in functionality from one another. I am curren

5条回答
  •  没有蜡笔的小新
    2020-12-14 06:12

    The accepted solution covers the case in which you are ok mixing stdout and stderr, but in cases in which the child process (for whatever reason) decides to use stderr IN ADDITION to stdout for a non failed output (i.e. to output a non-critical warning), then the given solution may not desirable.

    For example, if you will be doing additional processing on the output, like converting to JSON, and you mix in the stderr, then the overall process will fail since the output will not be pure JSON because of the added stderr output.

    I've found the following to work in that case:

    cmd_args = ... what you want to execute ...
    
    pipes = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    #If you are using python 2.x, you need to include shell=True in the above line
    std_out, std_err = pipes.communicate()
    
    if pipes.returncode != 0:
        # an error happened!
        err_msg = "%s. Code: %s" % (std_err.strip(), pipes.returncode)
        raise Exception(err_msg)
    
    elif len(std_err):
        # return code is 0 (no error), but we may want to
        # do something with the info on std_err
        # i.e. logger.warning(std_err)
    
    # do whatever you want with std_out
    # i.e. json.loads(std_out)
    

提交回复
热议问题