2

I'd like to return a value from a python subprocess call corresponding to the kind of error returned. E.g.:

test.py

RETCODE_OK = 0
RETCODE_THING_1_FAILED = 1
RETCODE_THING_2_FAILED = 2

def main():
    return RETCODE_THING_2_FAILED

if __name__ == '__main__':
    main()

Then I'm calling it with subprocess, like so:

>>> import subprocess
>>> proc = subprocess.Popen('python test.py', shell=True)
>>> proc.communicate()
(None, None)
>>> proc.returncode
0

I'd like this to return whatever was returned in main(), in this case 2. I've also got other stuff in the stdout and stderr streams, so I can't just print RETCODE_THING_2_FAILED and get the stdout.

0

1 Answer 1

3

Processes uses exit codes, not return statements. You should use sys.exit(STATUS) rather than return STATUS statement:

test2.py:
---------
import sys

def main():
    sys.exit(RETCODE_THING_2_FAILED)

if __name__ == '__main__':
    main()

interpreter:
------------
>>> p = subprocess.Popen('python test2.py')
>>> p.communicate()
(None, None)
>>> p.returncode
2

This is because the process is actually closing/exiting, not returning a value to another function.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.