Skip to content

Instantly share code, notes, and snippets.

@fralau fralau/traceback.md
Created Sep 17, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.