Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ipython: exit() statement not working as expected

I am running a script into ipython (1.2.1) and I need it to stop if a certain condition is not met. I tried to use the exit() statement, but it is not behaving as expected.

Take for example the following script which I called test.py:

if(True):
    print('Error')
    exit()
print('Still here!')

When I run it using python test.py, I get:

$python test.py
Error

And then the execution is terminated, as expected.

But if I run it from ipython using run -i test.py, then I get:

In [1]: run -i test.py
Error
Still here!

And finally the execution of ipython is terminated. The problem is that in this case the second print statement is still executed, while I would need the execution of the script to be terminated as soon as the exit() statement is encountered.

Why is this happening and how can I obtain the result I want? (I am running python 2.7.6)

like image 895
valerio Avatar asked May 26 '17 13:05

valerio


1 Answers

exit() alone is meant for the REPL, not really meant to be used by scripts.

Try using sys.exit(0) after you import sys, of course

like image 82
OneCricketeer Avatar answered Dec 17 '22 21:12

OneCricketeer