2011-06-28 73 views

回答

363

exit是交互式shell的幫手 - sys.exit是專門用於程序中的。

site模塊(其被啓動時自動導入,除了如果-S命令行選項)添加了幾個常數的內置名稱空間(例如exit它們對交互式解釋器外殼非常有用,不應在程序中使用。


從技術上講,他們大多是相同的:提高SystemExitsys.exit這樣做在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; 
} 

雖然exitsite.py定義:

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()之後的子進程中使用)。

+2

我懷疑退出(main())是一個常見的習慣用語,因爲人們不接受*,不應該在程序*註釋中使用。除非使用['-S'](http://docs.python.org/using/cmdline.html#cmdoption-S),否則它工作正常。使用'-S'工作的一種方法是指定'from sys import *'。 – nobar

+5

@nobar,真的,但是你真的不想使用'from module import *'。 – miku

+1

那麼如何在其他線程中引發'SystemExit'?是嗎,甚至? –

7

如果我在代碼中使用exit()並在shell中運行它,它會顯示一條消息,詢問我是否想要殺死該程序。這真的很令人不安。 See here

但是sys.exit()在這種情況下更好。它關閉程序並且不創建任何對話框。

相關問題