Stack trace of Python application

Asked 2 years ago, Updated 2 years ago, 107 views

The program keeps dying, but I can't find where it dies. How do I signal my Python interpreter to find out which code it runs?

python debugging stack-trace traceback

2022-09-21 18:59

1 Answers

Usually, it runs well, but sometimes the program ends for some reason I'll tell you the method I used then. It's a code that I personally made, so it's not universal, but it can only be used in a unix environment.

import code, traceback, signal

def debug(sig, frame):
    """Interrupt running process, and provide a python prompt for
    interactive debugging."""
    d={'_frame':frame}         # Allow access to frame object.
    d.update(frame.f_globals)  # Unless shadowed by global
    d.update(frame.f_locals)

    i = code.InteractiveConsole(d)
    message  = "Signal received : entering python shell.\nTraceback:\n"
    message += ''.join(traceback.format_stack(frame))
    i.interact(message)

def listen():
    signal.signal(signal.SIGUSR1, debug)  # Register handler

When writing, you must call the listen() function at the beginning of the program. os.kill(pid, signal.If you send a SIGUSR1 signal using kill, like SIGUSR1), Python console stops and shows stack trace results.

Press ctrl-d(EOF) to continue running on stack trace.


2022-09-21 18:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.