views:

7143

answers:

9

Possible Duplicate:
Terminating a Python script

I have a simple Python script that I want to stop executing if a condition is met.

For example:

done = True
if done:
    # quit/stop/exit
else:
    # do other stuff

Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.

+3  A: 

exit() should do the trick

Sec
THree seconds faster than me :P
Dana
And I even tested it in a shell first :-)
Sec
Damn you, I didn't see this/react in time (was also testing in the interpreter to be sure) *shakes fist* ;)
Runevault
Fastest Gun in The West ! http://blog.stackoverflow.com/2008/10/solving-the-fastest-gun-in-the-west-problem/
gimel
Well, I'm not sure if this question needed a long and thoughtful answer :P
Dana
this only works in version 2.5 and later
Moe
+1  A: 

exit() should do it.

Dana
+1  A: 

If the entire program should stop use sys.exit() otherwise just use an empty return.

André
+14  A: 
import sys
sys.exit()
gimel
+2  A: 
done = True
if not done:
    # do other stuff
Corey Goldberg
+4  A: 

You could put the body of your script into a function and then you could return from that function.

def main():
  done = True
  if done:
    return
    # quit/stop/exit
  else:
    # do other stuff

if __name__ == "__main__":
  #Run as main program
  main()
David Locke
+20  A: 

To exit a script you can use,

import sys
sys.exit()

You can also provide an exit status value, usually an integer.

import sys
sys.exit(0)

Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.

import sys
sys.exit("aa! errors!")

Prints "aa! errors!" and exits with a status code of 1.

There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.

The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.

ryan_s
+5  A: 

You can either use:

import sys
sys.exit(...)

or:

raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

efotinis
A: 

Try

sys.exit("message")

It is like the perl

die("message")

if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function

GabrieleV
did none of the answers suggested such an approach?
SilentGhost