[Python] Why does asyncio.run() or loop.run_until_complete() run task that is created but not...

Discussão em 'Python' iniciado por Stack, Janeiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    Here is the code.

    import asyncio

    async def run_test():
    print("run1")
    await asyncio.sleep(1)
    print("run2")

    async def main():
    print("main1")
    loop = asyncio.get_event_loop()
    task = loop.create_task(run_test())
    #task = asyncio.create_task(run_test())
    #task = asyncio.ensure_future(run_test())
    print("main2")

    print("________________")
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    print("________________")


    I'm expecting an output like

    ________________
    main1
    main2
    ________________


    as the task is not awaited. But the output is actully

    ________________
    main1
    main2
    run1
    ________________


    And if I remove async.sleep() in run_test(), it becomes like this:

    ________________
    main1
    main2
    run1
    run2
    ________________


    I've also tried

    #task = asyncio.create_task(run_test())
    #task = asyncio.ensure_future(run_test())


    The result is the same. 3 questions:

    1. Why is run_test() running without being awaited?
    2. Is there anyway to create a task without putting it into the event loop?
    3. Shouldn't run_until_complete() return immediately after main() completes? My guess is that the event loop keeps running runnable tasks after main() completes and return when there were no more runnable tasks. But that conflict with the name "run_until_complete". What is actually happening after main() completes?

    Continue reading...

Compartilhe esta Página