Answer the question
In order to leave comments, you need to log in
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()
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
Asynchronous tasks are executed by an event loop that cannot be stopped, and your infinite while does just that.
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 questionAsk a Question
731 491 924 answers to any question