How to get exit code when using Python subprocess communicate method?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping
--
Chapters
00:00 How To Get Exit Code When Using Python Subprocess Communicate Method?
00:21 Answer 1 Score 19
00:40 Accepted Answer Score 360
01:16 Answer 3 Score 21
01:32 Answer 4 Score 13
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/5631...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #subprocess
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Darkness Approaches Looping
--
Chapters
00:00 How To Get Exit Code When Using Python Subprocess Communicate Method?
00:21 Answer 1 Score 19
00:40 Accepted Answer Score 360
01:16 Answer 3 Score 21
01:32 Answer 4 Score 13
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/5631...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #subprocess
#avk47
ACCEPTED ANSWER
Score 360
Popen.communicate will set the returncode attribute when it's done(*). Here's the relevant documentation section:
Popen.returncode 
  The child return code, set by poll() and wait() (and indirectly by communicate()). 
  A None value indicates that the process hasn’t terminated yet.
  A negative value -N indicates that the child was terminated by signal N (Unix only).
So you can just do (I didn't test it but it should work):
import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode
(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait. 
ANSWER 2
Score 21
.poll() will update the return code.
Try
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
returnCode = child.poll()
In addition, after .poll() is called the return code is available in the object as child.returncode.
ANSWER 3
Score 19
You should first make sure that the process has completed running and the return code has been read out using the .wait method. This will return the code. If you want access to it later, it's stored as .returncode in the Popen object. 
ANSWER 4
Score 13
Use process.wait() after you call process.communicate(). 
For example:
import subprocess
process = subprocess.Popen(['ipconfig', '/all'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
exit_code = process.wait()
print(stdout, stderr, exit_code)