Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105702
| From | Zachary Ware <zachary.ware+pylist@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Adding run_in_executor task to already existing loop. |
| Date | 2016-03-25 16:00 -0500 |
| Message-ID | <mailman.8.1458939638.28225.python-list@python.org> (permalink) |
| References | <CAG5tnzpKOXfo4tz4tvF2aBsx0p5awGN4GhYN6wYn3kfY_ZQ0Bg@mail.gmail.com> |
On Fri, Mar 25, 2016 at 3:24 PM, Ray Cote
<rgacote@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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Adding run_in_executor task to already existing loop. Zachary Ware <zachary.ware+pylist@gmail.com> - 2016-03-25 16:00 -0500
csiph-web