VPfB
VPfB

Reputation: 17247

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. 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):

stack = traceback.extract_stack(err.__traceback__)

or (Python2 and Python3)

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

but got:

AttributeError: 'traceback' object has no attribute 'f_lineno'


Edit1:

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, e.g. sock.connect(addr). Not exactly what I wanted, but close.

Upvotes: 4

Views: 2852

Answers (1)

k4ppa
k4ppa

Reputation: 4667

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

Upvotes: 5

Related Questions