Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to exit main function [duplicate]

Tags:

python

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 
like image 229
Stan Avatar asked Sep 28 '10 18:09

Stan


People also ask

How do I stop a Python script condition?

exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute.

How do you exit a function from another function in Python?

Break up the loop. Have it just do one iteration (or, say, 100 iterations, if they're really quick), and then use after or after_idle to ask Tkinter to call a function that does another one iteration (or 100 iterations) and after s again, and so on, until they're all done.


1 Answers

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.

like image 93
Daniel Roseman Avatar answered Sep 18 '22 06:09

Daniel Roseman