| Conditions | 3 |
| Total Lines | 27 |
| Code Lines | 18 |
| Lines | 27 |
| Ratio | 100 % |
| Changes | 0 | ||
| 1 | import time |
||
| 7 | View Code Duplication | def exit_after(seconds, default=None): |
|
|
|
|||
| 8 | """Exit the function if it takes more than 'second' seconds to complete. |
||
| 9 | In this case, return the value of 'default' (default: None).""" |
||
| 10 | |||
| 11 | def handler(q, func, args, kwargs): |
||
| 12 | q.put(func(*args, **kwargs)) |
||
| 13 | |||
| 14 | def decorator(func): |
||
| 15 | def wraps(*args, **kwargs): |
||
| 16 | q = Queue() |
||
| 17 | p = Process(target=handler, args=(q, func, args, kwargs)) |
||
| 18 | p.start() |
||
| 19 | p.join(timeout=seconds) |
||
| 20 | if not p.is_alive(): |
||
| 21 | return q.get() |
||
| 22 | |||
| 23 | p.terminate() |
||
| 24 | p.join(timeout=0.1) |
||
| 25 | if p.is_alive(): |
||
| 26 | # Kill in case processes doesn't terminate |
||
| 27 | # Happens with cases like broken NFS connections |
||
| 28 | p.kill() |
||
| 29 | return default |
||
| 30 | |||
| 31 | return wraps |
||
| 32 | |||
| 33 | return decorator |
||
| 34 | |||
| 49 |