最近在公司用python寫一個(gè)獨(dú)立的exe,寫了如下幾行代碼:
...
exit_code = func(xxx)
sys.exit(exit_code)
最開(kāi)始調(diào)試并沒(méi)有任何問(wèn)題,進(jìn)程退出,并將退出碼設(shè)置為func的返回值。
后面加上異常保護(hù)后(我寫代碼有個(gè)習(xí)慣,最開(kāi)始只寫粗框架,必要時(shí)會(huì)加上為了讓自己理清邏輯的注釋。等框架搭完后再完善日志、注釋和異常保護(hù)等),代碼卻出問(wèn)題,修改后的代碼如下:
try:
? ? ...
? ? exit_code = func(xxx)
? ? sys.exit(exit_code)
except:
? ? print traceback.format_exc()
每次程序執(zhí)行完都會(huì)打出一個(gè)SystemExit的異常。

看了python doc后,才發(fā)現(xiàn)使用sys.exit()函數(shù)的正確姿勢(shì)。
Exit from Python. This is implemented by raising the?SystemExit?exception, so cleanup actions specified by finally clauses of?try?statements are honored, and it is possible to intercept the exit attempt at an outer level.
The optional argument?arg?can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed,?None?is equivalent to passing zero, and any other object is printed to?stderr?and results in an exit code of 1. In particular,?sys.exit("some?error?message")?is a quick way to exit a program when an error occurs.
通過(guò)說(shuō)明可以看到, sys.exit()這個(gè)函數(shù),只有認(rèn)為退出碼為0是正常退出,而其他退出碼則會(huì)認(rèn)為是異常退出,系統(tǒng)自動(dòng)拋出SystemExit的異常,方便開(kāi)發(fā)人員在外層捕獲并處理。
如果需要返回退出碼,而不拋出異常的話,可以使用os._exit()函數(shù)。
哎,學(xué)習(xí)不精呀,平時(shí)都是在寫django,python的main都沒(méi)寫過(guò)幾個(gè),雖然是python基礎(chǔ)知識(shí),還是得mark一下的~
