how do I fix this error with async functions `sys:1: RuntimeWarning: coroutine 'finish_process' was never awaited`

The goal of this code is to make it run the main function, called main_process(), until the async function of ending, called finish_process(), sets the variable finish_state to True and the loop doesn't repeat itself.

import asyncio
import time

condition = True
finish_state = False
x = 0

async def finish_process(finish_state):
    finish_state = True
    time.sleep(5)
    return finish_state

async def main_process(condition,finish_state,x):
    while condition == True:
        finish_state = await asyncio.run(finish_process(finish_state))
        
        x = x + 1
        print(x)

        #if(x > 10):
        if(finish_state == True):
            print("Termina!")
            condition = False


asyncio.run(main_process(condition,finish_state,x))

I have already put the await to the asynchronous function call inside another asynchronous function, I don't understand why it keeps giving the error with the await.

I thought that indicating with await or with the old yield from should fix the simultaneous waiting for the results of the other function.

raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'finish_process' was never awaited

Solution 1:

Your program has the following issues:

  1. You should use asyncio.create_task or asyncio.gather to run asynchronous tasks, not asyncio.run.
  2. Can replace time.sleep(5) with await asyncio.sleep(5)
import asyncio
import time

condition = True
finish_state = False
x = 0

async def finish_process(finish_state):
    finish_state = True
    await asyncio.sleep(5)
    return finish_state

async def main_process(condition,finish_state,x):
    while condition == True:
        finish_state = await asyncio.create_task(finish_process(finish_state))
        
        x = x + 1
        print(x)

        #if(x > 10):
        if(finish_state == True):
            print("Termina!")
            condition = False


asyncio.run(main_process(condition,finish_state,x))

Output:

1
Termina!