Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exit code when using Python subprocess communicate method?

How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

Relevant code:

import subprocess as sp data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0] 

Should I be doing this another way?

like image 959
CarpeNoctem Avatar asked Apr 12 '11 07:04

CarpeNoctem


People also ask

How do I find the exit code in Python?

You can set an exit code for a process via sys. exit() and retrieve the exit code via the exitcode attribute on the multiprocessing.

What does Popen return Python?

Description. Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.


1 Answers

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.

like image 51
Eli Bendersky Avatar answered Oct 02 '22 03:10

Eli Bendersky