RuntimeError: This event loop is already running in python

前端 未结 5 1191
攒了一身酷
攒了一身酷 2020-12-04 18:59

I think I\'m getting this error because my code calls asyncio.get_event_loop().run_until_complete(foo()) twice. Once from foo() and second time fr

5条回答
  •  忘掉有多难
    2020-12-04 19:34

    I'm writing this down not to patronize, but to explain how we can handle the situation where simply queueing async functions and awaiting their results synchronously while the event loop is running, doesn't work.

    run_until_complete is not for running any number of arbitrary async functions synchronously, it is for running the main entry point of your entire async program. This constraint is not immediately apparent from the docs.

    Since libraries like aiohttp will queue it's own entry point to run as a server and block the loop's synchronous operations using run_until_complete or run_forever, the event loop will already be running and you won't be able to run independent synchronous operations on that event loop and wait for it's result within that thread.

    That being said, if you have to queue an async operation into a running event loop from within a sync context and get it's result like a regular function, that may not be possible. Your best bet is to pass in a synchronous callback to be called once the async operation finishes. That will of course slow down your event loop.

    Another way of handling the situation is to execute your code within startup and cleanup callbacks of the async http library you're using. Here's a sample of how you may accomplish this.

提交回复
热议问题