blog icon indicating copy to clipboard operation
blog copied to clipboard

os._exit vs sys.exit

Open junnplus opened this issue 9 years ago • 0 comments

问题来自下面这段代码 https://github.com/thesharp/daemonize/blob/master/daemonize.py#L103

try:
    process_id = os.fork()
except OSError as e:
    self.logger.error("Unable to fork, errno: {0}".format(e.errno))
    sys.exit(1)
if process_id != 0:
    # This is the parent process. Exit without cleanup,
    # see https://github.com/thesharp/daemonize/issues/46
    os._exit(0)

一段代码使用了两种exit方法,以前并不知道还有os._exit()这样的退出方式。

文档上对这两种方法的描述是这样的:

os._exit(status)

Exit to the system with specified status, without normal exit processing.

sys.exit(status)

Exit the interpreter by raising SystemExit(status). If the status is omitted or None, it defaults to zero (i.e., success). If the status is an integer, it will be used as the system exit status. If it is another kind of object, it will be printed and the system exit status will be one (i.e., failure).

os._exit()会直接将python程序终止,之后的所有代码都不会继续执行。

sys.exit()会引发一个异常:SystemExit,如果这个异常没有被捕获,那么python解释器将会退出。如果有捕获此异常的代码,那么这些代码还是会执行。

关于SystemExit这个异常类,可以看官方的文档描述

The os._exit() function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call to os.fork()).

文档上说明了在fork出来的子进程中使用os._exit()而不是使用sys.exit()。 通常来说,使用sys.exit()来退出程序更优雅,捕捉SystemExit异常执行相关的清除工作。

参考链接:

  • http://stackoverflow.com/questions/9591350/what-is-difference-between-sys-exit0-and-os-exit0
  • http://stackoverflow.com/questions/19747371/python-exit-commands-why-so-many-and-when-should-each-be-used

Life such short, be Pythonic .

junnplus avatar May 04 '16 08:05 junnplus