Get return value from python script executed with subprocess.Popen

Viewed 1279

I have a main.py that execute file.py using subprocess.Popen:

# Execute request
url = "http://something:50001/dosomething/run"
test = ["python", "file.py", "url", url]
writer = subprocess.Popen(test, shell=False)

File.py execute a function that get an "exit code" when it request the url :

exitCode = None
answer = requests.get(url)
janswer = answer.json()
exitCode = janswer.get("exitCode")
return exitCode

For some reason, I need to execute this file.py using subprocess.Popen so that some code in main.py execute while file.py does its stuff.

What I'm trying to do now is to recover the exitCode from file.py to main.py.

I tried to use stdout=subprocess.Pipe and recover the exit code with a print, but for some reason it doesn't work.

Getting the writer.returncode isn't the solution to because it will give me the code from the subprocess, not from the function function return exitCode = -2, subprocess return returncode = 0, I need that -2. (-2 is just an example, the exitCode isn't the same all the time and depends on some parameters.)

1 Answers

Here is a short program that illustrates how you can get a number from a subprocess either via pipe or sys.exit(). Note that the range of values that can be returned from sys.exit() is limited, though.

import sys
import subprocess

def sub():
    try:
        print(42)
    except:
        # Print something even in case of an exception                          
        print(-1)
        raise
    sys.exit(43)

def main():
    writer = subprocess.Popen(["python3", sys.argv[0], "sub"],
                              stdout = subprocess.PIPE)
    for line in writer.stdout:
        print(int(line))
    exitcode = writer.wait()
    print('exitcode', exitcode)

if len(sys.argv) > 1 and sys.argv[1] == 'sub':
    sub()
else:
    main()

This prints

42
exitcode 43
Related