1

We're using tornadoweb which already runs an event loop single-threaded, and we want to use asyncio.run to run other coroutines, but it show error 'Event loop already running', found this library nest-asyncio that allows event loop to be nested, sorry not expert on threading or event loop, does nest-asyncio runs coroutines on separated thread?or no connection on threading?

1 Answers1

0

If the event loop is already running, you can't call asyncio.run.

You have a few options:

1. Tornado's IOLoop.add_callback:

This will run the coroutine in the background (that means you won't be able to get it's result).

from tornado import ioloop

loop = ioloop.IOLoop.current() # get the current running event loop

loop.add_callback(coro_func) # coro_func is the coroutine you want to run

2. Use asyncio.create_task:

This will also allow you to get the coroutine's result.

xyres
  • 20,487
  • 3
  • 56
  • 85
  • Using nest-asyncio..i was able to run asyncio.run since it allows nested event loop...question is..is it running on the same thread? – user18960204 May 03 '22 at 05:05
  • @user18960204 It will be a good idea to ask this directly to the project author. Perhaps in github issues – xyres May 03 '22 at 06:38