user2499879
user2499879

Reputation: 693

How to get the return status in python

I am calling the executable from python script using sub process call. these are the following code I have used:

try:
    p = subprocess.Popen([abc.exe], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

except Exception as e:
    print str(e)

from abc.exe, I have return 1 in failure case and return 0 for success case. But I don't know how to check the return value in python script.

thanks,

Upvotes: 1

Views: 1396

Answers (3)

Brian Neal
Brian Neal

Reputation: 32389

Another way to do this is to use subprocess.check_output() since you mention Python 2.7. This runs the command with the same arguments as Popen. The output of the command is returned as a string. If the command returns a non-zero value, a subprocess.CalledProcessError exception is raised.

So I think you can rework your code to something like this:

try:
    output = subprocess.check_output(['abc.exe'], shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
    # an error occurred
    retcode = ex.returncode
    output = ex.output
else:
    # no error occurred
    process(output)

Note that you can't use the stdout argument in check_output since it is used internally. Here are the docs.

Upvotes: 1

askewchan
askewchan

Reputation: 46530

You've saved as p the output from .communicate(), not Popen object. Perhaps try:

try:
    p = subprocess.Popen(['abc.exe'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

except OSError as e:
    print str(e)

stdoutdata, stderrdata = p.communicate()
retcode = p.returncode

Upvotes: 1

poke
poke

Reputation: 387607

Popen.returncode contains the return code when the process has terminated. You can ensure that using Popen.wait.

Upvotes: 3

Related Questions