在Python中查找原始异常的模块名称

发布于 2024-07-27 05:33:14 字数 296 浏览 6 评论 0原文

示例:

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

Thrown from: myapp.util.url

在上面的示例中,异常实际上是在 myapp/util/url.py 模块中抛出的。 有没有办法获取该模块的 __name__ ?

我的目的是在logging.getLogger函数中使用它。

Example:

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

Thrown from: myapp.util.url

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

初心未许 2024-08-03 05:33:14

这应该有效:

import inspect

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

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

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!)

This should work:

import inspect

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

EDIT: 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

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!)

内心荒芜 2024-08-03 05:33:14

您可以使用 traceback 模块 以及 sys.exc_info(),以编程方式获取回溯:

try:
    myapp.foo.doSomething()
except Exception, e:
    exc_type, exc_value, exc_tb = sys.exc_info()
    filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
    print 'Thrown from: %s' % filename

You can use the traceback module, along with sys.exc_info(), to get the traceback programmatically:

try:
    myapp.foo.doSomething()
except Exception, e:
    exc_type, exc_value, exc_tb = sys.exc_info()
    filename, line_num, func_name, text = traceback.extract_tb(exc_tb)[-1]
    print 'Thrown from: %s' % filename
抱猫软卧 2024-08-03 05:33:14

这应该可以解决问题:

import inspect
def modname():
    t=inspect.trace()
    if t:
        return t[-1][1]

This should do the trick:

import inspect
def modname():
    t=inspect.trace()
    if t:
        return t[-1][1]
少跟Wǒ拽 2024-08-03 05:33:14

Python 的日志记录包已支持此功能 - 请查看文档。 您只需在格式字符串中指定 %(module)s 即可。 但是,这会为您提供捕获异常的模块 - 不一定与引发异常的模块相同。 当然,回溯可以为您提供引发异常的精确位置。

Python's logging package already supports this - check the documentation. You just have to specify %(module)s in the format string. However, this gives you the module where the exception was caught - not necessarily the same as the one where it was raised. The traceback, of course, gives you the precise location where the exception was raised.

前事休说 2024-08-03 05:33:14

我在公司博客上有一个关于 CrashKit 如何从 Python 堆栈跟踪计算类名和包名的故事:“Python 堆栈跟踪传奇”。 包括工作代码。

I have a story about how CrashKit computes class names and package names from Python stack traces on the company blog: “Python stack trace saga”. Working code included.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文