Adding run_in_executor task to already existing loop.

Zachary Ware zachary.ware+pylist at gmail.com
Fri Mar 25 17:00:16 EDT 2016


On Fri, Mar 25, 2016 at 3:24 PM, Ray Cote
<rgacote at appropriatesolutions.com> wrote:
> Hello:
>
> I’m trying to perform an synchronous task while using asyncio.
> I understand the solution is to use run_in_executor.
> I’m not clear on how to add this into an already running event loop.
>
> I’ve found lots of examples showing how to set up a loop and run this, but
> I’m blocked in regards to doing this when the loop is already established.
>
>
> Example code:
>
> def blocking_func(param1):
>     # call the blocking call here.
>     return results
>
> async def process_request():
>     loop = asyncio.get_event_loop()
>     block = loop.run_in_executor(None, blocking_func, “hello”)
>     results = await loop.run_until_complete(asyncio.gather(*[block, ])
>
> The above code says “loop already running.” because we’re already in an
> async ask that has been awaited. What is the proper method of adding in
> this new synchronous task?

I'm assuming you're doing `await process_request()` elsewhere, which
is what's producing your error: you're trying to start the loop within
a coroutine running on that loop.  loop.run_in_executor() returns a
Future just like any other coroutine, so process_request just needs
this:

   async def process_request():
       loop = asyncio.get_event_loop()
       results = await loop.run_in_executor(None, blocking_func, 'hello')

-- 
Zach



More information about the Python-list mailing list