如何在 python 脚本中停止执行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3376534/
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
how do I halt execution in a python script?
提问by Blankman
Possible Duplicates:
Programatically stop execution of python script?
Terminating a Python script
I want to print a value, and then halt execution of the script.
我想打印一个值,然后停止执行脚本。
Do I just use return?
我只使用 return 吗?
采纳答案by Mark Byers
You can use return inside the main function in you have one, but this isn't guaranteed to quit the script if there is more code after your call to main.
您可以在 main 函数中使用 return ,但是如果在调用 main 之后还有更多代码,则不能保证退出脚本。
The simplest that nearly always works is sys.exit():
几乎总是有效的最简单的是sys.exit():
import sys
sys.exit()
Other possibilities:
其他可能性:
- Raise an error which isn't caught.
- Let the execution point reach the end of the script.
- If you are in a thread other than the main thread use
thread.interrupt_main().
- 引发未捕获的错误。
- 让执行点到达脚本的末尾。
- 如果您在主线程以外的线程中,请使用
thread.interrupt_main().

