Python etc / faulthandler part 2

faulthandler part 2

Now, let's see how to dump stack trace when a specific signal is received. We will use SIGUSR1 but you can do the same for any signal.

import faulthandler
from signal import SIGUSR1
from time import sleep


Now, in a new terminal, find out the PID of the interpreter. If the file is named, this is how you can do it (we add [] in grep to exclude the grep itself from the output):

ps -ax | grep '[t]'

The first number in the output is the PID. Now, use it to send the signal for PID 12345:

kill -SIGUSR1 12345

And back in the terminal with the running script. You will see the stack trace:

Current thread 0x00007f22edb29740 (most recent call first):
  File "", line 6 in <module>

This trick can help you to see where your program has frozen without adding logs to every line. However, a better alternative can be something like py-spy which allows you to dump the current stack trace without any changes in the code.