Python how to exit main function

Question:

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
Asked By: Stan

||

Answers:

use sys module

import sys
sys.exit()
Answered By: pyfunc

Call sys.exit.

Answered By: SLaks

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.

Answered By: Matthew Flaschen

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.

Answered By: Daniel Roseman

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

raise SystemExit, 0
Answered By: ecik
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.