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