Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 314
VPfB Avatar asked Oct 28 '25 10:10

VPfB


1 Answers

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
like image 191
k4ppa Avatar answered Oct 30 '25 15:10

k4ppa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!