天天看點

python中sys.exit() os._exit() exit() quit()的簡單使用

1》sys.exit() 

>>> import sys

>>> help(sys.exit)

Help on built-in function exit in module sys:

exit(...)

    exit([status])

    Exit the interpreter by raising SystemExit(status).

    If the status is omitted or None, it defaults to zero (i.e., success).

    If the status is an integer, it will be used as the system exit status.

    If it is another kind of object, it will be printed and the system

    exit status will be one (i.e., failure).

執行該語句會直接退出程式,這也是經常使用的方法,也不需要考慮平台等因素的影響,一般是退出Python程式的首選方法。

退出程式引發SystemExit異常,(這是唯一一個不會被認為是錯誤的異常), 如果沒有捕獲這個異常将會直接退出程式執行,

當然也可以捕獲這個異常進行一些其他操作(比如清理工作)。

sys.exit()函數是通過抛出異常的方式來終止程序的,也就是說如果它抛出來的異常被捕捉到了的話程式就不會退出了,

而是去進行一些清理工作。

SystemExit 并不派生自Exception 是以用Exception捕捉不到該SystemEixt異常,應該使用SystemExit來捕捉。

該方法中包含一個參數status,預設為0,表示正常退出, 其他都是異常退出。

還可以這樣使用:sys.exit("Goodbye!"); 一般主程式中使用此退出.

捕獲到SystemExit異常,程式沒有直接退出!

[email protected]:~$ vi systemExit.py

[email protected]:~$ more systemExit.py

#!/usr/bin/python

#!coding:utf-8

import sys

if __name__=='__main__':

    try:

        sys.exit(825)

    except SystemExit,error:

        print 'the information of SystemExit:{0}'.format(error)

        print "the program doesn't exit!"

    print 'Now,the game is over!'

[email protected]:~$ python systemExit.py

the information of SystemExit:825

the program doesn't exit!

Now,the game is over!

[email protected]:~$ 

沒有捕獲到SystemExit異常,程式直接退出,後邊的代碼不執行!

[email protected]:~$ vi systemExit.py

[email protected]:~$ more systemExit.py

#!/usr/bin/python

#!coding:utf-8

import sys

if __name__=='__main__':

    try:

        sys.exit(825)

    except Exception,error:

        print 'the information of SystemExit:{0}'.format(error)

        print "the program doesn't exit!"

    print 'Now,the game is over!'

[email protected]:~$ python systemExit.py

[email protected]:~$ 

沒有捕獲到SystemExit異常,輸出'Goodbye!'後,程式直接退出,後邊的代碼不執行!

[email protected]:~$ vi systemExit.py

[email protected]:~$ more systemExit.py

#!/usr/bin/python

#!coding:utf-8

import sys

if __name__=='__main__':

    try:

        sys.exit('Goodbye!')

    except Exception,error:

        print 'the information of SystemExit:{0}'.format(error)

        print "the program doesn't exit!"

    print 'Now,the game is over!'

[email protected]:~$ python systemExit.py

Goodbye!

[email protected]:~$ 

2》os._exit(), 直接退出 Python 解釋器, 不抛異常, 不執行相關清理工作,其後的代碼都不執行,

其使用會受到平台的限制,但我們常用的Win32平台和基于UNIX的平台不會有所影響, 常用在子程序的退出.

一般來說os._exit() 用于線上程中退出,sys.exit() 用于在主線程中退出。

3》exit()/quit(), 抛出SystemExit異常. 一般在互動式shell中退出時使用.

友情連結:

關于python中format()方法的使用,參考:python format()方法

(完)