Is sys.exit equivalent to raise SystemExit?

天涯浪子 提交于 2019-12-23 10:56:33

问题


According to the documentation on sys.exit and SystemExit, it seems that

def sys.exit(return_value=None):  # or return_value=0
    raise SystemExit(return_value)

is that correct or does sys.exit do something else before?


回答1:


According to Python/sysmodule.c, raising SystemExit is all it does.

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;
}



回答2:


As you can see at source code https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Python/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;
}

it's only raise SystemExit and doesn't do anything else




回答3:


Yes, raising SystemExit and calling sys.exit are functionally equivalent. See sys module source.

The PyErr_SetObject function is how CPython implements the raising of a Python exception.



来源:https://stackoverflow.com/questions/36302165/is-sys-exit-equivalent-to-raise-systemexit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!