Python如何退出main函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3815860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python how to exit main function
提问by Stan
Possible Duplicates:
Terminating a Python script
Terminating a Python Program
可能的重复:
终止 Python 脚本
终止 Python 程序
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.
我的问题是如何在 Python main 函数中退出?我试过 ' return' 但它给出了错误SyntaxError: 'return' outside function。任何人都可以帮忙吗?谢谢。
if __name__ == '__main__':
try:
if condition:
(I want to exit here)
do something
finally:
do something
采纳答案by Daniel Roseman
You can use sys.exit()to exit from the middle of the main function.
您可以使用sys.exit()从主函数中间退出。
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.
但是,我建议不要在那里做任何逻辑。相反,将所有内容放在一个函数中,__main__然后从-调用它- 然后您可以正常使用 return 。
回答by pyfunc
use sys module
使用系统模块
import sys
sys.exit()
回答by SLaks
Call sys.exit.
打电话sys.exit。
回答by Matthew Flaschen
You can't return because you're not in a function. You can exitthough.
你不能返回,因为你不在一个函数中。你可以exit。
import sys
sys.exit(0)
0 (the default) means success, non-zero means failure.
0(默认值)表示成功,非零表示失败。
回答by ecik
If you don't feel like importing anything, you can try:
如果您不想导入任何内容,可以尝试:
raise SystemExit, 0

