Is sys.exit equivalent to raising SystemExit?

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 correct or is sys.exit doing something else before?

+5
source share
3 answers

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

As you can see in the 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 only raises SystemExit and does nothing

+3
source

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

The PyErr_SetObject function is how CPython implements the Python exception raise.

+3
source

Source: https://habr.com/ru/post/1246044/


All Articles