tags:

views:

149

answers:

5

Possible Duplicates:
Terminating a Python script
Terminating a Python Program

My question is how to exit out in Python main function? I have tried 'return' but it gave the error SyntaxError: 'return' outside function. Can anyone help? Thanks.

if __name__ == '__main__':
  try:
    if condition:
    (I want to exit here) 
    do something
  finally:
    do something
+1  A: 

use sys module

import sys
sys.exit()
pyfunc
+1  A: 

Call sys.exit.

SLaks
+5  A: 

You can't return because you're not in a function. You can exit though.

import sys
sys.exit(0)

0 (the default) means success, non-zero means failure.

Matthew Flaschen
Why `sys.exit()` instead of just plain `exit()`?
Just Some Guy
Why not? Also, Python tries not to provide more built-in functions than are necessary.
David Zaslavsky
@Just, the [docs](http://docs.python.org/library/constants.html#exit) say not to use plain `exit` in programs, and it's arguably a [bug](http://bugs.python.org/issue8220) (albeit a WONTFIX) that you even can.
Matthew Flaschen
+14  A: 

You can use sys.exit() to exit from the middle of the main function.

However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.

Daniel Roseman
+1 for adding an explicit 'everything' function. This also makes it easier to (1) call this script from other scripts (2) unit test.
Manoj Govindan
Guido van Rossum supports (or at least, used to) this approach: http://www.artima.com/weblogs/viewpost.jsp?thread=4829
ide
I typically create a function named "main" and put it at the top of the file.
Bryan Oakley
+2  A: 

If you don't feel like importing anything, you can try:

raise SystemExit, 0
ecik