Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 24 20:15:09 2021
@author: oem
"""
#!/usr/bin/python
# file: watchdog.py
# license: MIT License
import signal
import time
import random
class Watchdog(Exception):
def __init__(self, time=5):
self.time = time
def __enter__(self):
signal.signal(signal.SIGALRM, self.handler)
signal.alarm(self.time)
def __exit__(self, type, value, traceback):
signal.alarm(0)
def handler(self, signum, frame):
raise self
def __str__(self):
return "The code you executed took more than %ds to complete" % self.time
# import the class
#from watchdog import Watchdog
def long_function():
r = random.random()
print(f'random: {r}')
t_rand = 2*r
time.sleep(t_rand)
return t_rand
# don't allow long_function to take more than 5 seconds to complete
tiempos = []
for i in range(10):
try:
with Watchdog(1):
t0 = long_function()
print(t0)
tiempos.append(t0)
except Watchdog:
print("long_function() took too long to complete")
tiempos.append(0)