0

I am working with code that my client insists cannot be changed. It needs to be called using a python command like subprocess.call() ... The code includes a use of the exit() function. When exiting, the exit() function contains data as a parameter:

exit(data)

How can I capture the data parameter that the script is using when calling exit() without modifying the code to use a return or anything like that?

Jonathan Math
  • 81
  • 1
  • 6

2 Answers2

0

If your data is a valid exit code (i.e., a number in 0-127, I believe), then you can get the exit code via the subprocess API as the return value of the call function:

>>> import subprocess
>>> subprocess.call(['python3', '-c', 'exit(24)'])
24

If it's not, then it will be printed out, so the easiest way is probably to capture the stderr of the process and parse it out of there.

Reed Oei
  • 1,177
  • 2
  • 9
  • 16
0

From the docs for exit:

exit(code=None) ... when called, raise SystemExit with the specified exit code.

From the docs for SystemExit:

If the value is an integer, it specifies the system exit status (passed to C’s exit() function); if it is None, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one.

So the answer depends whether data is an integer or not. If it is an integer, then it is the subprocess's exit code; see this question for how to get it from subprocess. If data is not an integer, then it's printed to stderr; see this question for how to get it from subprocess.

chepner
  • 389,128
  • 51
  • 403
  • 529
kaya3
  • 31,244
  • 3
  • 32
  • 61
  • 1
    The value of the `SystemExit` exception is written to standard error (I edited that); the linked question describes how to capture standard output, though it should be easy to adapt to standard error instead. – chepner Feb 04 '20 at 18:52
  • @chepner Oh, of course. I assumed it would be stdout since the docs didn't specify stderr, but I should have checked. Thanks for fixing! – kaya3 Feb 04 '20 at 18:54