python筆記:sys.exit()的用法

最近在公司用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一下的~


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,817評(píng)論 0 10
  • 得不到的付出,要懂得適可而止 生活給了你舒適,你偏偏選擇了逆向思維 過(guò)去的你不會(huì)讓現(xiàn)在的你滿意 ...
    糖豆兒123閱讀 221評(píng)論 0 0
  • 1. 城里的燈光又明又暗,明的都在眼前,暗的都在心里。尤其是雨后的街,光影在地上交織于泥濘里,像倉(cāng)皇的心事。 他深...
    愛(ài)逛大觀園的劉姥姥閱讀 614評(píng)論 14 12
  • 我要你健康 我要你快樂(lè) 我要你幸福 我要你擁有這世上所有的美好 然而,我知道 人活一生困難和挫折都不會(huì)少 于是,我...
    桑小榆閱讀 196評(píng)論 0 1
  • import UIKit @UIApplicationMain class AppDelegate: UIResp...
    沫晴er閱讀 261評(píng)論 0 0

友情鏈接更多精彩內(nèi)容