Get output code from running Python script via IPython

  ipython, python

Say I have t.py:

import sys

if __name__ == '__main__':
    sys.exit(123)

and run.py:

import subprocess

output = subprocess.run(['python', 't.py'])
print(output)

Running run.py, I get:

% python run.py
CompletedProcess(args=['python', 't.py'], returncode=123)

However, if I then modify run.py to be:

import subprocess

output = subprocess.run(['ipython', 't.py'])
print(output)

then I get:

% python run.py
---------------------------------------------------------------------------
SystemExit                                Traceback (most recent call last)
~/tmp/t.py in <module>
      2 
      3 if __name__ == '__main__':
----> 4     sys.exit(123)

SystemExit: 123
CompletedProcess(args=['ipython', 't.py'], returncode=1)

In the second case, when I’m running ipython, how can I get the correct return code?
How should I write t.py such that, when I run it via ipython, then the exit code is 123?

Source: Python Questions

LEAVE A COMMENT