| @@ 590-616 (lines=27) @@ | ||
| 587 | return [atoi(c) for c in re.split(r'(\d+)', text)] |
|
| 588 | ||
| 589 | ||
| 590 | def exit_after(seconds, default=None): |
|
| 591 | """Exit the function if it takes more than 'seconds' seconds to complete. |
|
| 592 | In this case, return the value of 'default' (default: None).""" |
|
| 593 | ||
| 594 | def handler(q, func, args, kwargs): |
|
| 595 | q.put(func(*args, **kwargs)) |
|
| 596 | ||
| 597 | def decorator(func): |
|
| 598 | def wraps(*args, **kwargs): |
|
| 599 | q = Queue() |
|
| 600 | p = Process(target=handler, args=(q, func, args, kwargs)) |
|
| 601 | p.start() |
|
| 602 | p.join(timeout=seconds) |
|
| 603 | if not p.is_alive(): |
|
| 604 | return q.get() |
|
| 605 | ||
| 606 | p.terminate() |
|
| 607 | p.join(timeout=0.1) |
|
| 608 | if p.is_alive(): |
|
| 609 | # Kill in case processes doesn't terminate |
|
| 610 | # Happens with cases like broken NFS connections |
|
| 611 | p.kill() |
|
| 612 | return default |
|
| 613 | ||
| 614 | return wraps |
|
| 615 | ||
| 616 | return decorator |
|
| 617 | ||
| @@ 7-33 (lines=27) @@ | ||
| 4 | import psutil |
|
| 5 | ||
| 6 | ||
| 7 | 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 | ||
| 35 | ||
| 36 | class Issue3290: |
|