在Python中,有两个相似命名的函数, exit()
和sys.exit()
。 有什么区别,何时应该使用一个而不是另外一个? html
若是我在代码中使用exit()
并在shell中运行它,它会显示一条消息,询问我是否要终止该程序。 这真的使人不安。 看这里 python
但在这种状况下, sys.exit()
更好。 它会关闭程序而且不会建立任何对话框。 git
exit
是交互式shell的助手 - sys.exit
旨在用于程序。 github
site
模块(在启动期间自动导入,除非给出-S
命令行选项)将几个常量添加到内置命名空间(例如exit
) 。 它们对交互式解释器shell颇有用,不该在程序中使用 。 shell
从技术上讲,它们大体相同:提高SystemExit
。 sys.exit
在sysmodule.c中这样作 : 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; }
虽然exit
分别在site.py和_sitebuiltins.py中定义。 app
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')
请注意,有一个第三个退出选项,即os._exit ,它在不调用清理处理程序,刷新stdio缓冲区等的状况下退出(而且一般只能在fork()
以后的子进程中使用)。 ide