I would like to run a python script with IPython and be able to tell whether the script was successful (ran all the way through) or unsuccessful (an exception was raised).
Normally one can tell whether a command is successful by inspecting its return value, where the convention is 0 for success and some other integer for an error (the value indicating which error). This is the behaviour when running scripts with python script.py
, but when using ipython script.py
, IPython automatically captures the error and (unhelpfully) returns exit code 0.
How can I disable this behaviour when running the script with IPython?
Incidentally, I need to run the script in IPython instead of Python because the script has been generated from an IPython notebook (.ipynb) and contains some IPython magic commands.
Here is a minimal working example.
fail.py
#! /usr/bin/env python
mytext = 'Hello World!'
if __name__=="__main__":
print(missing_variable)
When running the script with IPython, the exception is printed to stdout and the return value is 1, correctly denoting failure of the script.
~$ python fail.py
Traceback (most recent call last):
File "fail.py", line 4, in <module>
print(missing_variable)
NameError: name 'missing_variable' is not defined
~$ echo $?
1
When running the script with IPython, the exception is caught and the traceback is printed to stdout, then IPython exits and returns 0 (which is not desirable, since the script did not succeed).
~$ ipython fail.py
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~/fail.py in <module>()
2 mytext = 'Hello World!'
3 if __name__=="__main__":
----> 4 print(missing_variable)
NameError: name 'missing_variable' is not defined
~$ echo $?
0