| 1 |
""" |
| 2 |
Usage: |
| 3 |
|
| 4 |
python alarm.py <timeout> <scriptname> <args...> |
| 5 |
|
| 6 |
Run the given script. If the timeout elapses, trying interrupting it by |
| 7 |
sending KeyboardInterrupts. |
| 8 |
""" |
| 9 |
|
| 10 |
def _main_with_alarm(finished): |
| 11 |
import sys, os |
| 12 |
import time |
| 13 |
import thread |
| 14 |
|
| 15 |
|
| 16 |
def timeout_thread(timeout, finished): |
| 17 |
stderr = sys.stderr |
| 18 |
interrupt_main = thread.interrupt_main |
| 19 |
sleep = time.sleep |
| 20 |
now = time.time |
| 21 |
while now() < timeout and not finished: |
| 22 |
sleep(1.65123) |
| 23 |
if not finished: |
| 24 |
stderr.write("="*26 + "timedout" + "="*26 + "\n") |
| 25 |
while not finished: |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
interrupt_main() |
| 30 |
sleep(0.031416) |
| 31 |
|
| 32 |
|
| 33 |
timeout = time.time() + float(sys.argv[1]) |
| 34 |
thread.start_new_thread(timeout_thread, (timeout, finished)) |
| 35 |
del sys.argv[:2] |
| 36 |
sys.path.insert(0, os.path.dirname(sys.argv[0])) |
| 37 |
return sys.argv[0] |
| 38 |
|
| 39 |
if __name__ == '__main__': |
| 40 |
finished = [] |
| 41 |
try: |
| 42 |
execfile(_main_with_alarm(finished)) |
| 43 |
finally: |
| 44 |
finished.append(True) |