Skip to content

Instantly share code, notes, and snippets.

@chriscz
Last active December 27, 2016 13:17
Show Gist options
  • Save chriscz/ed27271c4c70f0f2f2e41b67aae3bb10 to your computer and use it in GitHub Desktop.
Save chriscz/ed27271c4c70f0f2f2e41b67aae3bb10 to your computer and use it in GitHub Desktop.
Snippet for signal handling in Python (useful for monitoring)
import signal
import os
import readline
from pprint import pprint
def handle_shell(signal, frame):
frames = []
while frame:
frames.append({'locals':frame.f_locals, 'globals': frame.f_globals})
frame = frame.f_back
print("You can acess the frames via the `frames` local variable")
try:
import IPython; IPython.embed()
except:
import code
code.interact(local=dict(globals(), **locals()))
def handle(signal, frame):
i = 0
while frame:
print()
print('-'*80)
print("frame {}".format(i).center(80))
print('-'*80)
print('--- locals')
pprint(frame.f_locals)
print('--- globals')
pprint(frame.f_globals)
# walk up the call frame
frame = frame.f_back
i -= 1
signal.signal(signal.SIGUSR1, handle)
signal.signal(signal.SIGUSR2, handle_shell)
# --- code
g = 'i am global'
def process():
a = 1
b = 2
c = 3
l = 'i am local'
while True:
a += b + 2*(c - b)
c = a - a/2
b = b+2
if __name__ == '__main__':
pid = os.getpid()
print("PID: %d" % pid)
print("kill -USR1 %d # to print out stack frames" % pid)
print("kill -USR2 %d # to open an interactive Python shell" % pid)
process()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment