1

When I execute a python script on linux and interrupt the process, it gives me the " most recent call last":

Traceback (most recent call last):
  File "clustermptest.py", line 38, in <module>
    if sequences[i][x:x+3]==CAI[cailength][1]:
KeyboardInterrupt

Is there a way to see what the most recent call last is ie the line it is currently processing while the script is still running/without stopping the script?

1 Answers1

0

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:

  1. The signal module (be sure to read the caveats)
  2. The traceback module
  3. Doug Hellman's Python Module of the Week tutorial on using signal
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677