美文网首页
python笔记:sys.exit()的用法

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

作者: 陈可安 | 来源:发表于2018-06-13 20:14 被阅读0次

    最近在公司用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一下的~

    相关文章

      网友评论

          本文标题:python笔记:sys.exit()的用法

          本文链接:https://www.haomeiwen.com/subject/yxjseftx.html