在Python中,有兩個相似命名的函數exit()
和sys.exit()
。有什麼區別,我應該什麼時候使用一個呢?Python中的exit()和sys.exit()之間的區別
293
A
回答
363
exit
是交互式shell的幫手 - sys.exit
是專門用於程序中的。
的
site
模塊(其被啓動時自動導入,除了如果-S
命令行選項)添加了幾個常數的內置名稱空間(例如exit
)。 它們對交互式解釋器外殼非常有用,不應在程序中使用。
從技術上講,他們大多是相同的:提高SystemExit
。 sys.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;
}
雖然exit
在site.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()
之後的子進程中使用)。
7
如果我在代碼中使用exit()
並在shell中運行它,它會顯示一條消息,詢問我是否想要殺死該程序。這真的很令人不安。 See here
但是sys.exit()
在這種情況下更好。它關閉程序並且不創建任何對話框。
相關問題
- 1. 「return 0」和「exit(0)」之間的區別
- 2. exit和quick_exit之間的區別
- 3. pthread_exit()和exit()之間的區別?
- 4. Python 2.7:exit()和raise ValueError(「example」)之間的區別
- 5. 調用sys.exit()和拋出異常之間的區別
- 6. python中的[]和[,,]之間的區別
- 7. Python中cStringIO.StringIO.write和String.StringIO.write之間的區別
- 8. Python中dir()和locals()之間的區別?
- 9. 系統調用:sys_exit(),SYS_exit和exit()之間的區別
- 10. android sha224和python之間的區別sha224
- 11. Python - os.access和os.path.exists之間的區別?
- 12. python:!=和<>之間的區別?
- 13. Python - docopt和argparse之間的區別
- 14. ruby和python之間的語法區別?
- 15. basetring和types.StringType之間的python區別?
- 16. python pygir-ctypes和gi.repository之間的區別
- 17. memcache和python字典之間的區別
- 18. randn和普通Python之間的區別
- 19. Python 3.5 - '//'和'int()'之間的區別
- 20. NodeJS和Python散列之間的區別
- 21. Smalltalk和python之間的區別?
- 22. Python:!=和「不是」之間的區別
- 23. Python:`is`和`==`之間的區別?
- 24. python tkinter spinbox和optionmenu之間的區別
- 25. [:] = b和a = b [:]之間的區別? (Python)
- 26. 之間的〜/和的區別../
- 27. Python中列表之間的區別
- 28. '#','%'和'$'之間的區別
- 29. {!!之間的區別!!}和{{}}
- 30. '+ ='和'= +'之間的區別?
我懷疑退出(main())是一個常見的習慣用語,因爲人們不接受*,不應該在程序*註釋中使用。除非使用['-S'](http://docs.python.org/using/cmdline.html#cmdoption-S),否則它工作正常。使用'-S'工作的一種方法是指定'from sys import *'。 – nobar
@nobar,真的,但是你真的不想使用'from module import *'。 – miku
那麼如何在其他線程中引發'SystemExit'?是嗎,甚至? –