如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:43:36  来源:igfitidea点击:

how do I halt execution in a python script?

python

提问by Blankman

Possible Duplicates:
Programatically stop execution of python script?
Terminating a Python script

可能的重复:以
编程方式停止执行 python 脚本?
终止 Python 脚本

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().

回答by NullUserException

回答by cji

There's exitfunction in sysmodule ( docs):

模块中有exit功能sysdocs):

import sys
sys.exit( 0 ) # 0 will be passed to OS

You can also

你也可以

raise SystemExit

or any other exception that won't be caught.

或任何其他不会被捕获的异常。