2

I have a script that I want to exit early under some condition:

if not "id" in dir():
     print "id not set, cannot continue"
     # exit here!
# otherwise continue with the rest of the script...
print "alright..."
[ more code ]

I run this script using execfile("foo.py") from the Python interactive prompt and I would like the script to exit going back to interactive interpreter. How do I do this? If I use sys.exit(), the Python interpreter exits completely.

fuenfundachtzig
  • 7,952
  • 13
  • 62
  • 87

4 Answers4

7

In the interactive interpreter; catch SystemExit raised by sys.exit and ignore it:

try:
    execfile("mymodule.py")
except SystemExit:
    pass
ChristopheD
  • 112,638
  • 29
  • 165
  • 179
3

Put your code block in a method and return from that method, like such:

def do_the_thing():
    if not "id" in dir():
         print "id not set, cannot continue"
         return
         # exit here!
    # otherwise continue with the rest of the script...
    print "alright..."
    # [ more code ]

# Call the method
do_the_thing()

Also, unless there is a good reason to use execfile(), this method should probably be put in a module, where it can be called from another Python script by importing it:

import mymodule
mymodule.do_the_thing()
Frederik
  • 14,156
  • 10
  • 45
  • 53
  • Even easier would be to invert the if-condition and execute the rest of the script only if this condition is fulfilled. I just thought there might be a simpler way to stop the execution of the script. But apparently there is not :) – fuenfundachtzig Apr 07 '10 at 12:15
  • Actually, it *is* a good idea to make sure your preconditions are met at the beginning of a method. So checking first and only continuing if all conditions are correct is a good approach. – Frederik Apr 07 '10 at 14:38
2

I'm a little obsessed with ipython for interactive work but check out the tutorial on shell embedding for a more robust solution than this one (which is your most direct route).

Community
  • 1
  • 1
colgur
  • 180
  • 7
  • I know I'm two years too late to this party, But is there an updated link? – Glycerine Oct 15 '12 at 09:44
  • 1
    Shell embedding is sustained by the ipython project. The latest one is here: http://ipython.org/ipython-doc/rel-0.13.1/interactive/reference.html#embedding-ipython. – colgur Nov 16 '12 at 23:01
  • Man!!!! I've been searching for this for sooooooo long! Thanks a lot! Making it easier for the lazy ones: import ipython `from IPython import embed` and then use embed() in the place you want to stop execution and go for interactive work `embed() # this call anywhere in your program will start IPython` – Homero Esmeraldo Jun 17 '14 at 23:35
0

Instead of using execfile, you should make the script importable (name=='main protection, seperated into functions, etc.), and then call the functions from the interpreter.