How can you programmatically inspect the stack trace of an exception in Python?

前端 未结 5 1398
一个人的身影
一个人的身影 2021-02-02 12:19

When an exception occurs in Python, can you inspect the stack? Can you determine its depth? I\'ve looked at the traceback module, but I can\'t figure out how to use it.

<
5条回答
  •  无人及你
    2021-02-02 13:20

    You define such a function (doc here):

    def raiseErr():
       for f in inspect.stack(): print '-', inspect.getframeinfo(f[0])
    

    and call it from your modules so:

    raiseErr()
    

    The function raiseErr will print info about the place you called it.

    More elaborate, you can do so:

    import inspect, traceback
    A = [inspect.getframeinfo(f[0]) for f in inspect.stack()]
    print "traceback structure fields:", filter(lambda s: s[0] != '_', dir(A[0]))
    print A[0].filename, A[0].lineno
    for f in inspect.stack():
        F = inspect.getframeinfo(f[0])
        print '-', F.filename, F.lineno, '\t', F.code_context[0].strip()
    

    Other possibility is to define this function:

    def tr():
        print '* - '*10,
        print sys._getframe(1).f_code.co_name
    

    And call it in the place where you want the trace. If you want all the trace, make an iterator from 1 up in _getframe(1).

提交回复
热议问题