79

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
3
  • 1
    WHen you searched what did you find? stackoverflow.com/search?q=%5Bpython%5D+exit. All of these seem to have something in common. Commented Sep 28, 2010 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. Commented Apr 7, 2012 at 16:00
  • This answer to a related question seems the most useful here stackoverflow.com/a/953385/86967. Commented Apr 7, 2012 at 16:01

5 Answers 5

131

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for adding an explicit 'everything' function. This also makes it easier to (1) call this script from other scripts (2) unit test.
Guido van Rossum supports (or at least, used to) this approach: artima.com/weblogs/viewpost.jsp?thread=4829
I typically create a function named "main" and put it at the top of the file.
exit() works fine for me, using python 2.7.x
38

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.

4 Comments

Why sys.exit() instead of just plain exit()?
Why not? Also, Python tries not to provide more built-in functions than are necessary.
@Just, the docs say not to use plain exit in programs, and it's arguably a bug (albeit a WONTFIX) that you even can.
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. scaler.com/topics/exit-in-python geeksforgeeks.org/…
14

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

raise SystemExit, 0

1 Comment

Can this be caught if someone wanted to extend the main and not exit at the end of it?
7

use sys module

import sys
sys.exit()

Comments

2

Call sys.exit.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.