python中sys.exit()与return的区别

文章目录

sys.exit()

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        			
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值