Created
December 4, 2017 20:49
-
-
Save Netherdrake/083243172863c38f32823bc7705d4d8c to your computer and use it in GitHub Desktop.
a little async helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import queue | |
import threading | |
from box import Box | |
q = queue.Queue() | |
def get_queue_items(limit = 10): | |
results = [] | |
for _ in range(limit): | |
try: | |
results.append(q.get_nowait()) | |
except queue.Empty: | |
break | |
return results | |
def results(limit = 10): | |
items = get_queue_items(limit) | |
res = { | |
'done': [x for x in items if x.get('result')], | |
'failed': [x for x in items if x.get('error')], | |
} | |
return Box(res) | |
def wrapped(fn, *args, **kwargs): | |
try: | |
res = fn(*args, **kwargs) | |
q.put({'result': res}) | |
except Exception as e: | |
q.put({'error': f'{fn.__name__}() raised {e.__class__.__name__}: `{e}`'}) | |
def go(fn, *args, **kwargs): | |
t = threading.Thread( | |
name='Foo', | |
target=wrapped, | |
args=(fn, *args), | |
kwargs=kwargs, | |
) | |
t.start() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment