文章目录
sys.exit()
从Python中退出。实现方式是抛出一个 SystemExit 异常。异常抛出后 try 声明的 finally 分支语句的清除动作将被触发。此动作有可能打断更外层的退出尝试。
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object.
If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.
Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.
If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1.
In particular, sys.exit(“some error message”) is a quick way to exit a program when an error occurs.
由于 exit() 最终“只是”抛出一个异常,因此当从主线程调用时,只会从进程退出;而异常不会因此被打断。
当一段程序成功运行,正常进程结束时Exit code为0。Pycahrm集成环境下运行脚本成功后,可以看到输出Process finished with exit code 0
exit()函数用来从主进程退出,并可以指定退出状态。参数可以用来指定状态返回值。
默认参数值为0.代表成功退出。非零则代表异常退出。当然参数可以是整数之外的其他类型对象。比如可以自定义一段信息作为stderr输出
注:None
对象相当于参数为0.
当其他对象作为标准错误输出时,Exit code为1
import sys
try:
print("this is a try")
sys.exit("this is a error exit")
finally:
print("结束")
-----------------------------输出--------------------------------
this is a try
this is a error exit