Skip to content

Instantly share code, notes, and snippets.

@fralau
Created September 17, 2018 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fralau/63cef71b2609f3592166399fa2b24040 to your computer and use it in GitHub Desktop.
Save fralau/63cef71b2609f3592166399fa2b24040 to your computer and use it in GitHub Desktop.
How to get a "traceback" without exiting Python

Issue

Find which "path" the stack has used to call a procedure (this may be useful in frameworks with callbacks)

Solution

Use the inspect function

import inspect

def show_stack():
    """
    Provides a kind of traceback, without stopping the program
    (the traceback includes the line of code that called this function)
    """
    for i in range(1, len(inspect.stack())):
        frame = inspect.stack()[i]
        print("Frame %s: File %s:%s, line: %s" % 
                (i, frame.filename, frame.function, frame.lineno))

Here is the result, e.g.

Frame 1: File traceback.py:hello, line: 17
Frame 2: File traceback.py:<module>, line: 19

A higher frame number means an earlier position in the stack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment