Home > database >  How to run a coroutine in async.run_until_completed in an async function
How to run a coroutine in async.run_until_completed in an async function

Time:04-25

here is the problem:

async def init():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(sessions, message))

async def main(sessions, message):
    # some code to execute...

i'am trying to run the function main(sessions, message) in run_until_complete, but the problem is that I cannot get the coroutine in an async function, because is it throws an error that: RuntimeWarning: coroutine 'main' was never awaited

can you tell me please how should i run a function like that correctly?

CodePudding user response:

You don’t need to use run_until_complete inside a coroutine. The way you wait for something to finish inside a coroutine is to await it.

async def init():
    await main(sessions, message)

CodePudding user response:

Just do

import asyncio

async def init():
    await main(...)

async def main(sessions, message):
    ...

loop = asyncio.get_event_loop()
loop.run_until_complete(init())
  • Related