10

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)

user3382203
  • 169
  • 1
  • 6
  • 25
valerio
  • 677
  • 4
  • 12
  • 25
  • 3
    `import sys; sys.exit(0)` – OneCricketeer May 26 '17 at 13:46
  • 4
    I don't know ipython, but give `sys.exit()` a try. Of course you will also need to `import sys` if you haven't already done so. The plain `exit()` function is a bit strange: it's designed as a convenience for use in the standard Python interactive interpreter, but it's generally not a good idea to use it in other contexts. – PM 2Ring May 26 '17 at 13:47
  • update to ipython 5 – Yasin Yousif May 26 '17 at 13:55
  • @cricket_007 It works! But why exactly doesn't exit() work? If you transform your comment in an answer and explain this to me I will be glad to accept it! – valerio May 26 '17 at 14:29

1 Answers1

9

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • In an interactive Ipython session, the REPL catches `sys.exit`. I rely on that all the time when testing `argparse` examples. – hpaulj May 26 '17 at 16:28