Skip to content

Commit

Permalink
Forward exceptions from thread executor
Browse files Browse the repository at this point in the history
  • Loading branch information
arkq committed Dec 19, 2024
1 parent ca740af commit 2098793
Showing 1 changed file with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import argparse
import asyncio
import builtins
import contextlib
import inspect
import json
import logging
Expand Down Expand Up @@ -101,11 +102,24 @@ class TestRunnerHooks:


def asyncio_thread_executor(f):
"""Run an async function in an event loop in a separate thread.
This decorator function blocks the current thread until the async function
completes. Also, it forwards any exceptions that occurred in that thread.
"""
@wraps(f)
def wrapper(*args, **kwargs):
thread = threading.Thread(target=asyncio.run, args=(f(*args, **kwargs),))
def run(coroutine, q: queue.Queue):
try:
asyncio.run(coroutine)
except Exception as e:
q.put(e)
q = queue.Queue()
thread = threading.Thread(target=run, args=(f(*args, **kwargs), q))
thread.start()
thread.join()
with contextlib.suppress(queue.Empty):
raise q.get(block=False)
return wrapper


Expand Down

0 comments on commit 2098793

Please sign in to comment.