简体   繁体   English

如何从回溯中获取功能和模块名称?

[英]How to get the function and module names from a traceback?

I'm trying to extract info from a traceback, but I'm getting errors. 我正在尝试从追溯中提取信息,但出现错误。

I want to get rid of the call variable in the following example code. 我想摆脱以下示例代码中的call变量。 I want to search the traceback and get the name of the called socket module function. 我想搜索回溯并获取被调用的套接字模块函数的名称。 How can I do this? 我怎样才能做到这一点?

try:
    sock = None
    call = "socket"
    sock = socket.socket(family, stype)
    call = "setsockopt"
    set_my_options():
    call = "connect"
    sock.connect(addr)
except OSError as err:
    if sock is not None:
        sock.close()
    # call = name of the failed socket.XXX() call
    raise RPCError("{} failed".format(call))

I have tried to begin with (Python3 only): 我尝试从(仅限Python3)开始:

stack = traceback.extract_stack(err.__traceback__)

or (Python2 and Python3) 或(Python2和Python3)

stack = traceback.extract_stack(sys.exc_info()[2])

but got: 但得到:

AttributeError: 'traceback' object has no attribute 'f_lineno' AttributeError:“ traceback”对象没有属性“ f_lineno”


Edit1 : 编辑1

After fixing the overlooked error, this is what I have now: 解决了被忽略的错误之后,这就是我现在所拥有的:

    ....
except OSError as err:
    tb = traceback.extract_tb(err.__traceback__)
    for tb_entry in reversed(tb):
        if tb_entry[0] == __file__:
            failed = tb_entry[3]
            break
    ....

It extracts the last traceback entry where the executed code was still in the current file. 它提取执行代码仍在当前文件中的最后一个追溯条目。 Internals of a foreign module would not be very helpfull. 外部模块的内部信息不会很有帮助。 The result is a line of code, eg sock.connect(addr) . 结果是一行代码,例如sock.connect(addr) Not exactly what I wanted, but close. 不完全是我想要的,但是很接近。

In this way you can retrieve the function name and the module name where the function is. 这样,您可以检索函数名称和函数所在的模块名称。

import traceback

def func():
    try:
        # My code
    except Exception as e:
        stack = traceback.extract_stack()
        (filename, line, procname, text) = stack[-1]
        print procname # function name
        print filename # module name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM