Python的traceback__Python

來源:互聯網
上載者:User

Python異常模組traceback用法舉例

traceback.print_exc() #把返回資訊輸出到控制台

fp = StringIO.StringIO()    #建立記憶體檔案對象
traceback.print_exc(file=fp) #把返回資訊寫到檔案中去
message = fp.getvalue() #獲得資訊

搞清楚 Python traceback

其實traceback.print_exc()函數只是traceback.print_exception()函數的一個簡寫形式,而它們擷取異常相關的資料都是通過sys.exc_info()函數得到的。

traceback模組使用traceback對象

print_exception(etype, value, tb[, limit[, file]])

print_exc([limit[, file]])是print_exception的簡寫print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)(它使用sys.exc_info())

format_exc([limit])(很像print_exc(limit))直接返回字串,不輸出到流,不必要使用上文的StringIO得到字串,在2.4中新加的

limit參數,限制返回的錯誤層數,即在函數A調用函數B,一個異常發生在函數B裡面,如果limit=1,則只返回顯示函數A裡面發生錯誤,而如果設定limit,則全部返回。

file參數,指定輸出到檔案裡。

其他方法見官方文檔traceback — Print or retrieve a stack traceback

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.