简体   繁体   中英

Async Function calling async generator calling async function

How do I get around the chicken and egg issue here?

One function will return the first result of a generator, this generator must gather data from the function that called it. This works in general code, but as soon as you throw async in the loop (I don't want to return a coroutine) it errors out. How do I not return a coroutine from function_one ?

Code:

import asyncio

async def second_iterator(number):
    for x in range(number):
        yield await function_one(x)

async def function_one(number):
    if number > 2:
        return asyncio.run(second_iterator(number))

    await asyncio.sleep(1)
    return number

def main(number):
    print(asyncio.run(function_one(number)))

main(3)

Error:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    main(3)
  File "main.py", line 15, in main
    print(asyncio.run(function_one(number)))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\Owner\Anaconda3\lib\asyncio\base_events.py", line 579, in run_until_complete
    return future.result()
  File "main.py", line 9, in function_one
    return asyncio.run(second_iterator(number))
  File "C:\Users\Owner\Anaconda3\lib\asyncio\runners.py", line 34, in run
    "asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop

You should have only single asyncio.run() in your script. It's sort of entry point of a program:

import asyncio


async def main():
    # all your code is here


if __name__ == "__main__":
    asyncio.run(main())

asyncio.run() is the only blocking operation that starts event loop that manages execution of all of your coroutines and tasks.

Please consider reading some tutorial on asyncio , it may help you to achieve your goal faster:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM