65

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
Community
  • 1
  • 1
Stan
  • 35,251
  • 46
  • 120
  • 177
  • 1
    WHen you searched what did you find? http://stackoverflow.com/search?q=%5Bpython%5D+exit. All of these seem to have something in common. – S.Lott Sep 28 '10 at 18:25
  • 4
    I think people have missed the point of this question. The OP is not looking for a generic way to terminate a program. He wants to know why, in this case, `return` does not work for that purpose. – Brent Bradburn Apr 07 '12 at 16:00
  • This answer to a related question seems the most useful here http://stackoverflow.com/a/953385/86967. – Brent Bradburn Apr 07 '12 at 16:01

5 Answers5

113

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
  • 567,968
  • 59
  • 825
  • 842
30

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
  • 268,153
  • 48
  • 509
  • 534
  • 2
    Why `sys.exit()` instead of just plain `exit()`? – Kirk Strauser Sep 28 '10 at 18:26
  • 1
    Why not? Also, Python tries not to provide more built-in functions than are necessary. – David Z Sep 28 '10 at 18:32
  • 3
    @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 Sep 28 '10 at 18:42
12

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

raise SystemExit, 0
ecik
  • 799
  • 4
  • 11
5

use sys module

import sys
sys.exit()
pyfunc
  • 63,167
  • 15
  • 145
  • 135
2

Call sys.exit.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933