2017-06-29 20:56:25 +02:00
|
|
|
import sys
|
|
|
|
import multiprocessing
|
|
|
|
|
|
|
|
|
|
|
|
_current = None
|
|
|
|
_total = None
|
|
|
|
|
|
|
|
|
|
|
|
def _init(current, total):
|
|
|
|
global _current
|
|
|
|
global _total
|
|
|
|
_current = current
|
|
|
|
_total = total
|
|
|
|
|
|
|
|
|
|
|
|
def _wrapped_func(func_and_args):
|
2019-02-06 19:43:37 +01:00
|
|
|
func, argument, should_print_progress, filter_ = func_and_args
|
2017-06-29 20:56:25 +02:00
|
|
|
|
|
|
|
if should_print_progress:
|
|
|
|
with _current.get_lock():
|
|
|
|
_current.value += 1
|
|
|
|
sys.stdout.write('\r\t{} of {}'.format(_current.value, _total.value))
|
2017-07-14 06:54:26 +02:00
|
|
|
sys.stdout.flush()
|
2017-06-29 20:56:25 +02:00
|
|
|
|
2019-02-06 19:43:37 +01:00
|
|
|
return func(argument, filter_)
|
2017-06-29 20:56:25 +02:00
|
|
|
|
|
|
|
|
2019-02-06 19:43:37 +01:00
|
|
|
def pmap(func, iterable, processes, should_print_progress, filter_=None, *args, **kwargs):
|
2017-06-29 20:56:25 +02:00
|
|
|
"""
|
|
|
|
A parallel map function that reports on its progress.
|
|
|
|
|
|
|
|
Applies `func` to every item of `iterable` and return a list of the
|
|
|
|
results. If `processes` is greater than one, a process pool is used to run
|
|
|
|
the functions in parallel. `should_print_progress` is a boolean value that
|
|
|
|
indicates whether a string 'N of M' should be printed to indicate how many
|
|
|
|
of the functions have finished being run.
|
|
|
|
"""
|
|
|
|
global _current
|
|
|
|
global _total
|
|
|
|
_current = multiprocessing.Value('i', 0)
|
|
|
|
_total = multiprocessing.Value('i', len(iterable))
|
|
|
|
|
2019-02-06 19:43:37 +01:00
|
|
|
func_and_args = [(func, arg, should_print_progress, filter_) for arg in iterable]
|
2018-01-05 23:05:13 +01:00
|
|
|
if processes == 1:
|
2019-01-03 15:12:30 +01:00
|
|
|
result = list(map(_wrapped_func, func_and_args, *args, **kwargs))
|
2017-06-29 20:56:25 +02:00
|
|
|
else:
|
|
|
|
pool = multiprocessing.Pool(initializer=_init,
|
|
|
|
initargs=(_current, _total,),
|
|
|
|
processes=processes)
|
|
|
|
result = pool.map(_wrapped_func, func_and_args, *args, **kwargs)
|
2018-02-26 22:15:51 +01:00
|
|
|
pool.close()
|
|
|
|
pool.join()
|
2017-06-29 20:56:25 +02:00
|
|
|
|
|
|
|
if should_print_progress:
|
|
|
|
sys.stdout.write('\r')
|
|
|
|
return result
|