| Total Complexity | 5 |
| Total Lines | 49 |
| Duplicated Lines | 55.1 % |
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | import time |
||
| 2 | from multiprocessing import Process, Queue |
||
| 3 | |||
| 4 | import psutil |
||
| 5 | |||
| 6 | |||
| 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 | |||
| 35 | |||
| 36 | class Issue3290: |
||
| 37 | @exit_after(1, default=None) |
||
| 38 | def blocking_io_call(self, fs): |
||
| 39 | try: |
||
| 40 | return psutil.disk_usage(fs) |
||
| 41 | except OSError: |
||
| 42 | return None |
||
| 43 | |||
| 44 | |||
| 45 | issue = Issue3290() |
||
| 46 | while True: |
||
| 47 | print(f"{time.time()} {issue.blocking_io_call('/home/nicolargo/tmp/hang')}") |
||
| 48 | time.sleep(1) |
||
| 49 |