74

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
  • 37,207
  • 50
  • 124
  • 185
  • 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
  • 5
    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

124

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
  • 588,541
  • 66
  • 880
  • 895
36

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
  • 278,309
  • 50
  • 514
  • 539
  • 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
  • The exit() is defined in site.py and it works only if the site module is imported so it should be used in the interpreter only. https://www.scaler.com/topics/exit-in-python/ https://www.geeksforgeeks.org/python-exit-commands-quit-exit-sys-exit-and-os-_exit/ – bgrupczy May 16 '23 at 01:12
13

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

raise SystemExit, 0
ecik
  • 819
  • 5
  • 11
7

use sys module

import sys
sys.exit()
pyfunc
  • 65,343
  • 15
  • 148
  • 136
2

Call sys.exit.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964