如何确定哪个函数调用在Python中引发异常? [英] How to identify what function call raise an exception in Python?
问题描述
我需要确定谁提出了异常来处理更好的str错误,有办法吗?
i need to identify who raise an exception to handle better str error, is there a way ?
看看我的例子:
try:
os.mkdir('/valid_created_dir')
os.listdir('/invalid_path')
except OSError, msg:
# here i want i way to identify who raise the exception
if is_mkdir_who_raise_an_exception:
do some things
if is_listdir_who_raise_an_exception:
do other things ..
我如何在python中处理呢?
how i can handle this, in python ?
推荐答案
如果您完全依赖于哪个功能执行失败而要执行的任务(如您的代码所示),则尝试使用try /如现有答案所示,exec块可能更好(尽管如果第一个失败,则可能需要跳过第二个部分)。
If you have completely separate tasks to execute depending on which function failed, as your code seems to show, then separate try/exec blocks, as the existing answers suggest, may be better (though you may probably need to skip the second part if the first one has failed).
如果您有很多无论哪种情况,您都需要做一些事情,并且只有很少的工作取决于哪个函数失败,然后分离可能会产生大量的重复和重复,因此您建议的格式可能会更好。 Python标准库中的 traceback 模块可以在此方面提供帮助案例:
If you have many things that you need to do in either case, and only a little amount of work that depends on which function failed, then separating might create a lot of duplication and repetition so the form you suggested may well be preferable. The traceback module in Python's standard library can help in this case:
import os, sys, traceback
try:
os.mkdir('/valid_created_dir')
os.listdir('/invalid_path')
except OSError, msg:
tb = sys.exc_info()[-1]
stk = traceback.extract_tb(tb, 1)
fname = stk[0][2]
print 'The failing function was', fname
当然,如果使用进行检查,您将使用
代替
打印
确切确定要执行的处理。
Of course instead of the print
you'll use if
checks to decide exactly what processing to do.
这篇关于如何确定哪个函数调用在Python中引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!