在Python中查找原始异常的模块名称 [英] Find module name of the originating exception in Python

查看:178
本文介绍了在Python中查找原始异常的模块名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

>>> try:
...    myapp.foo.doSomething()
... except Exception, e:
...    print 'Thrown from:', modname(e)

Thrown from: myapp.util.url

在上面的例子中,异常实际上是抛出在myapp / util / url.py模块。有没有办法获得该模块的 __ name __

In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __name__ of that module?

我的目的是在 logging.getLogger function。

My intention is to use this in logging.getLogger function.

推荐答案

这应该可以工作:

import inspect

try:
    some_bad_code()
except Exception, e:
    frm = inspect.trace()[-1]
    mod = inspect.getmodule(frm[0])
    print 'Thrown from', mod.__name__

编辑:Stephan202提到了一个角落。在这种情况下,我认为我们可以默认使用文件名。

Stephan202 mentions a corner case. In this case, I think we could default to the file name.

import inspect

try:
    import bad_module
except Exception, e:
    frm = inspect.trace()[-1]
    mod = inspect.getmodule(frm[0])
    modname = mod.__name__ if mod else frm[1]
    print 'Thrown from', modname

问题是如果模块没有被加载(因为在读取该文件中的代码时抛出异常),那么 inspect.getmodule 调用返回None。所以,我们只是使用违规框架引用的文件的名称。 (感谢您指出这一点,Stephan202!)

The problem is that if the module doesn't get loaded (because an exception was thrown while reading the code in that file), then the inspect.getmodule call returns None. So, we just use the name of the file referenced by the offending frame. (Thanks for pointing this out, Stephan202!)

这篇关于在Python中查找原始异常的模块名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆