You could use winpdb to attach to your running program and allow you to break, inspect, and resume it at various points.
Or, you could define a signal handler, although this may not be a completely robust solution especially if you are using threads:
import signal
import traceback
def sigint_handler(signal, frame):
# ctrl-c generates SIGINT
traceback.print_stack()
print('-'*80)
def foo():
total = 0
for i in range(10**8):
total += i
return total
if __name__=='__main__':
signal.signal(signal.SIGINT, sigint_handler)
print(foo())
Running test.py
, and pressing C-c
at various moments yields:
C-c C-c File "/home/unutbu/pybin/test.py", line 20, in <module>
print(foo())
File "/home/unutbu/pybin/test.py", line 14, in foo
for i in range(10**8):
File "/home/unutbu/pybin/test.py", line 9, in sigint_handler
traceback.print_stack()
--------------------------------------------------------------------------------
C-c C-c File "/home/unutbu/pybin/test.py", line 20, in <module>
print(foo())
File "/home/unutbu/pybin/test.py", line 15, in foo
total += i
File "/home/unutbu/pybin/test.py", line 9, in sigint_handler
traceback.print_stack()
--------------------------------------------------------------------------------
4999999950000000
References:
- The signal module (be sure to read the caveats)
- The traceback module
- Doug Hellman's Python Module of the Week tutorial on using
signal