How do I retrieve the exit code when using Python’s subprocess
module and the communicate()
method?
Relevant code:
JavaScript
x
3
1
import subprocess as sp
2
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
3
Should I be doing this another way?
Advertisement
Answer
Popen.communicate
will set the returncode
attribute when it’s done(*). Here’s the relevant documentation section:
JavaScript
1
6
1
Popen.returncode
2
The child return code, set by poll() and wait() (and indirectly by communicate()).
3
A None value indicates that the process hasn’t terminated yet.
4
5
A negative value -N indicates that the child was terminated by signal N (Unix only).
6
So you can just do (I didn’t test it but it should work):
JavaScript
1
5
1
import subprocess as sp
2
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
3
streamdata = child.communicate()[0]
4
rc = child.returncode
5
(*) This happens because of the way it’s implemented: after setting up threads to read the child’s streams, it just calls wait
.