sys.exit(n)和exit()、os._exit(n)

来源:互联网 发布:webshell powershell 编辑:程序博客网 时间:2024/05/22 10:32

1. os._exit(n)
直接退出, 不抛异常, 不执行相关清理工作. 常用在子进程的退出.
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()).

2. sys.exit(n) 
退出程序引发SystemExit异常, 可以捕获异常执行些清理工作. n默认值为0, 表示正常退出. 其他都是非正常退出. 还可以sys.exit("sorry, goodbye!"); 一般主程序中使用此退出.


3. exit()/quit()
抛出SystemExit异常. 一般在交互式shell中退出时使用.



sys.exit()和exit(), they do mostly the same: raising SystemExit

sys.exit does so in sysmodule.c:

static PyObject *sys_exit(PyObject *self, PyObject *args){    PyObject *exit_code = 0;    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))        return NULL;    /* Raise SystemExit so callers may catch it or clean up. */    PyErr_SetObject(PyExc_SystemExit, exit_code);   return NULL;}

While exit is defined in site.py:

class Quitter(object):    def __init__(self, name):        self.name = name    def __repr__(self):        return 'Use %s() or %s to exit' % (self.name, eof)    def __call__(self, code=None):        # Shells like IDLE catch the SystemExit, but listen when their        # stdin wrapper is closed.        try:            sys.stdin.close()        except:            pass        raise SystemExit(code)__builtin__.quit = Quitter('quit')__builtin__.exit = Quitter('exit')

The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace (e.g. exit). They are useful for the interactive interpreter shell and should not be used in programs.