| Total Complexity | 5 |
| Total Lines | 58 |
| Duplicated Lines | 46.55 % |
| 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 | #################################################################################### |
||
| 2 | # |
||
| 3 | # Migration of the code issue3290.py to use multiprocessing with 'fork' start method |
||
| 4 | # |
||
| 5 | #################################################################################### |
||
| 6 | |||
| 7 | import multiprocessing |
||
| 8 | import time |
||
| 9 | |||
| 10 | import psutil |
||
| 11 | |||
| 12 | # multiprocessing.set_start_method("fork") |
||
| 13 | ctx_mp_fork = multiprocessing.get_context('fork') |
||
| 14 | |||
| 15 | |||
| 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 | |||
| 44 | |||
| 45 | class Issue3290: |
||
| 46 | @exit_after(1, default=None) |
||
| 47 | def blocking_io_call(self, fs): |
||
| 48 | try: |
||
| 49 | return psutil.disk_usage(fs) |
||
| 50 | except OSError: |
||
| 51 | return None |
||
| 52 | |||
| 53 | |||
| 54 | issue = Issue3290() |
||
| 55 | while True: |
||
| 56 | print(f"{time.time()} {issue.blocking_io_call('/home/nicolargo/tmp/hang')}") |
||
| 57 | time.sleep(1) |
||
| 58 |