0

As in this question, I'd also like to run some code for a limited amount of time. However, I'd like to recover the value of some variables when the code is interrupted, which the answers in the question do not allow. A dummy example would be:

import time

limit = 10
counter = 0
start = time.time()
while(time.time() - start < limit):
    counter += 1

and this way I can recover counter after running the code for limit seconds. But I do not want to use this approach, because if the operation in the while loop takes a long time (e.g. > limit), it is still executed once - which I don't want.

How could I avoid this, but still get the value of some variables when the process is interrupted?

Community
  • 1
  • 1
P. Camilleri
  • 12,664
  • 7
  • 41
  • 76

1 Answers1

0

You can use SIGALRM and have a signal sent to your program each time. Because the argument is the stack frame, it's possible to read any variable from there.

#!/usr/bin/python

import signal
import time

def alarm_handler (signo, frame):
    print ("SIGALRM: counter = %s" % frame.f_locals ["counter"])
    signal.alarm (2)

signal.signal (signal.SIGALRM, alarm_handler)
signal.alarm (2)

counter = 0
while True:
    time.sleep (.5)
    counter += 1