Python中exit()和sys.exit()之間的區別

在Python中,有兩個相似命名的函數, exit()sys.exit() 。 有什麼區別,何時應該使用一個而不是另外一個? html


#1樓

若是我在代碼中使用exit()並在shell中運行它,它會顯示一條消息,詢問我是否要終止該程序。 這真的使人不安。 看這裏 python

但在這種狀況下, sys.exit()更好。 它會關閉程序而且不會建立任何對話框。 git


#2樓

exit是交互式shell的助手 - sys.exit旨在用於程序。 github

site模塊(在啓動期間自動導入,除非給出-S命令行選項)將幾個常量添加到內置命名空間(例如exit它們對交互式解釋器shell頗有用,不該在程序中使用shell


從技術上講,它們大體相同:提高SystemExitsys.exitsysmodule.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

相關文章
相關標籤/搜索