Python how to exit main function

Python

Python Problem Overview


> 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

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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

raise SystemExit, 0

Solution 4 - Python

use sys module

import sys
sys.exit()

Solution 5 - Python

Call sys.exit.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStanView Question on Stackoverflow
Solution 1 - PythonDaniel RosemanView Answer on Stackoverflow
Solution 2 - PythonMatthew FlaschenView Answer on Stackoverflow
Solution 3 - PythonecikView Answer on Stackoverflow
Solution 4 - PythonpyfuncView Answer on Stackoverflow
Solution 5 - PythonSLaksView Answer on Stackoverflow