我有這樣的功能
def try_strip(s):
try:
return s.strip()
except Exception as e:
print(e)
# (I've tried inspect, traceback, logging, sys)
如果我這樣稱呼它
try_strip('could be a string or not')
那么例外行號將是定義 try_strip 的行號。有沒有辦法獲取有關它在哪里呼叫的資訊?先感謝您。
uj5u.com熱心網友回復:
Python 中包含的 Traceback 模塊提供了此功能。根據其檔案:
提供標準介面來提取、格式化和列印 Python 程式的堆疊跟蹤。它在列印堆疊跟蹤時完全模仿 Python 解釋器的行為。
該函式traceback.format_stack()會將您需要的堆疊跟蹤資訊作為字串串列回傳,而該函式traceback.print_stack()會將堆疊跟蹤資訊列印到控制臺。下面我包含了一些代碼,這些代碼顯示了您在提供的示例中如何使用它:
import traceback
def try_strip(s):
try:
return s.strip()
except Exception as e:
traceback.print_stack()
stack_trace_info = traceback.format_stack()
# Code that write stack_trace_info to a log could go here
try_strip(5) # This will cause an error at runtime
有關 Traceback 模塊的更多資訊,請參閱https://docs.python.org/3/library/traceback.html。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482873.html
下一篇:Python雙函式遞回
