-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.py
42 lines (33 loc) · 915 Bytes
/
timeout.py
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
import errno
import os
import signal
import functools
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
@functools.wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wrapper
return decorator
import re
@timeout()
def match_pattern():
match = re.findall(r'A(B|C+)+D', "ACCCCCCCCCCCCCCCCCCCCCCCCCCABD")
if match:
print("Match found:", match.group())
else:
print("No match found")
def main():
match_pattern()
if __name__ == "__main__":
main()