python笔记:sys.exit()的用法

最近在公司用python写一个独立的exe,写了如下几行代码:

...

exit_code = func(xxx)

sys.exit(exit_code)

最开始调试并没有任何问题,进程退出,并将退出码设置为func的返回值。

后面加上异常保护后(我写代码有个习惯,最开始只写粗框架,必要时会加上为了让自己理清逻辑的注释。等框架搭完后再完善日志、注释和异常保护等),代码却出问题,修改后的代码如下:

try:

    ...

    exit_code = func(xxx)

    sys.exit(exit_code)

except:

    print traceback.format_exc()


每次程序执行完都会打出一个SystemExit的异常。


看了python doc后,才发现使用sys.exit()函数的正确姿势。

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

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.

通过说明可以看到, sys.exit()这个函数,只有认为退出码为0是正常退出,而其他退出码则会认为是异常退出,系统自动抛出SystemExit的异常,方便开发人员在外层捕获并处理。

如果需要返回退出码,而不抛出异常的话,可以使用os._exit()函数。

哎,学习不精呀,平时都是在写django,python的main都没写过几个,虽然是python基础知识,还是得mark一下的~


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,713评论 0 10
  • 得不到的付出,要懂得适可而止 生活给了你舒适,你偏偏选择了逆向思维 过去的你不会让现在的你满意 ...
    糖豆儿123阅读 221评论 0 0
  • 1. 城里的灯光又明又暗,明的都在眼前,暗的都在心里。尤其是雨后的街,光影在地上交织于泥泞里,像仓皇的心事。 他深...
    爱逛大观园的刘姥姥阅读 611评论 14 12
  • 我要你健康 我要你快乐 我要你幸福 我要你拥有这世上所有的美好 然而,我知道 人活一生困难和挫折都不会少 于是,我...
    桑小榆阅读 196评论 0 1
  • import UIKit @UIApplicationMain class AppDelegate: UIResp...
    沫晴er阅读 261评论 0 0

友情链接更多精彩内容