The docs page for asyncio.run_coroutine_threadsafe offers this example code:
future = asyncio.run_coroutine_threadsafe(coro, loop)
[...more code...]
try:
result = future.result(timeout)
except concurrent.futures.TimeoutError:
print('The coroutine took too long, cancelling the task...')
future.cancel()
except Exception as exc:
print(f'The coroutine raised an exception: {exc!r}')
else:
print(f'The coroutine returned: {result!r}')
I’ve tried this and it works.
There is another part of the docs which seem to be saying this won’t work. Firstly, it says you can’t use a timeout.
On the page for the Future Object I can see Future.result()
with no parameters. There is a note marked Important at the foot of the page which says, “asyncio.Future.result()
and asyncio.Future.exception()
do not accept the timeout argument”.
Secondly, in that same Important footnote it says the exception raised by an unfinished Future is not
concurrent. futures.TimeoutError
but asyncio. InvalidStateError
.
So either the docs are contradictory or — more likely — I’m missing something. Which and what is it?