在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