1

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,

1
  • 3
    There are two problems with this code: 1. You forgot quotes around 'abc.exe', which will cause a NameError to be raised for a non-existent variable 'abc' 2. You're catching Exception, which will catch the NameError. You should only catch OSError. Commented Sep 16, 2013 at 13:25

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.