G
G
Grandma Luda2021-10-25 18:58:19
Python
Grandma Luda, 2021-10-25 18:58:19

Why can't I create a task?

I recently started learning asynchronous programming, and I ran into such a problem, task is not created in the loop

import asyncio

async def cola():
    for i in range(100):
        await asyncio.sleep(0.01)
    print("cola")

async def burger():
    for i in range(1000):
        await asyncio.sleep(0.01)    
    print("burger")

async def kassa():
    while True:
        command = input("закас: ")
        if command == "cola":
            asyncio.create_task(cola())
            
        elif command == "burger":
            asyncio.create_task(burger())
            

async def main():
    asyncio.create_task(kassa())

loop = asyncio.new_event_loop()
loop.run_until_complete(main())
loop.run_forever()


but if you remove the loop, then everything works correctly
import asyncio

async def cola():
    for i in range(100):
        await asyncio.sleep(0.01)
    print("cola")

async def burger():
    for i in range(1000):
        await asyncio.sleep(0.01)    
    print("burger")

async def kassa():
        command = input("закас: ")
        if command == "cola":
            asyncio.create_task(cola())
            
        elif command == "burger":
            asyncio.create_task(burger())
            

async def main():
    asyncio.create_task(kassa())

loop = asyncio.new_event_loop()
loop.run_until_complete(main())
loop.run_forever()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-10-25
@KirasiH

Asynchronous tasks are executed by an event loop that cannot be stopped, and your infinite while does just that.

V
Vindicar, 2021-10-25
@Vindicar

I suspect it's the synchronous input(). While the code is in it, other coroutines are not executed.
In principle, you can cheat and use run_in_executor() .
Roughly speaking, it allows you to move long synchronous code to a separate thread and wrap it in a regular task. So from the point of view of the rest of the program, the code becomes kind of asynchronous.
EDIT: There is also aioconsole package for just such things.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question