“subprocess.Popen” - checking for success and errors

前端 未结 5 2144
迷失自我
迷失自我 2020-11-30 07:29

I want to check if a subprocess has finished execution successfully or failed. Currently I have come up with a solution but I am not sure if it is correct and reliable. Is i

5条回答
  •  暖寄归人
    2020-11-30 08:04

    Complete solution with check on return code, stdout and stderr:

    import subprocess as sp
    
    # ok
    pipe = sp.Popen( 'ls /bin', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
    # res = tuple (stdout, stderr)
    res = pipe.communicate()
    print("retcode =", pipe.returncode)
    print("res =", res)
    print("stderr =", res[1])
    for line in res[0].decode(encoding='utf-8').split('\n'):
      print(line)
    
    # with error
    pipe = sp.Popen( 'ls /bing', shell=True, stdout=sp.PIPE, stderr=sp.PIPE )
    res = pipe.communicate()
    print("retcode =", pipe.returncode)
    print("res =", res)
    print("stderr =", res[1])
    

    Prints:

    retcode = 0
    res = (b'bash\nbunzip2\nbusybox\nbzcat\n...zmore\nznew\n', b'')
    stderr = b''
    bash
    bunzip2
    busybox
    bzcat
    ...
    zmore
    znew
    
    retcode = 2
    res = (b'', b"ls: cannot access '/bing': No such file or directory\n")
    stderr = b"ls: cannot access '/bing': No such file or directory\n"
    

提交回复
热议问题