-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_processors.py
57 lines (47 loc) · 1.67 KB
/
queue_processors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from logging import getLogger
from queue import Queue
from typing import Callable
def processor(source: Queue, process: Callable, destination: Queue=None):
"""Calls `process` on the `source` queue items.
Results are put in `destination,` if specified
"""
logger = getLogger()
while True:
item = source.get()
try:
logger.debug(f'Processing {item}.')
processed_item = process(item)
except:
logger.error(f'Exception caught processing {item}.', exc_info=True)
if destination is not None:
destination.put(processed_item)
logger.debug(f'Done processing {item}.')
source.task_done()
logger.info("Terminating processor.")
def fork_processor(source: Queue, process: Callable, predicate: Callable, left_destination: Queue, right_destination: Queue):
"""Calls `process` on the `source` queue items.
`predicate` is called on each result; `True` results are put in the
`left_destination` queue, `False` are put in the `right_destination` queue.
"""
logger = getLogger()
while True:
item = source.get()
logger.debug(f'Processing {item}.')
try:
processed_item = process(item)
except:
logger.error(f'Exception caught processing {item}.', exc_info=True)
if type(processed_item) is list:
for processed in processed_item:
if predicate(processed):
left_destination.put(processed)
else:
right_destination.put(processed)
else:
if predicate(processed_item):
left_destination.put(processed_item)
else:
right_destination.put(processed_item)
logger.debug(f'Done processing {item}.')
source.task_done()
logger.info("Terminating processor.")