Answer the question
In order to leave comments, you need to log in
Why is an asyncio error thrown?
Good afternoon!
I understand asynchronous programming and now I can’t understand why the error occurs:
Task was destroyed but it is pending!
task: <Task pending coro=<TestAsync._consume() running at test_async.py:19> wait_for=<Future cancelled>>
import asyncio
class TestAsync:
def __init__(self):
self._loop = asyncio.get_event_loop()
self._queue = asyncio.Queue(loop=self._loop)
self.result = []
async def _consume(self):
while True:
item = await self._queue.get()
self.result.append(item)
self._queue.task_done()
await asyncio.sleep(0.1)
async def _produce(self):
for i in range(10):
await self._queue.put(i ** 2)
self._queue.task_done()
await asyncio.sleep(0.2)
def run(self):
consumer = asyncio.ensure_future(self._consume(), loop=self._loop)
self._loop.run_until_complete(self._produce())
self._loop.run_until_complete(self._queue.join())
consumer.cancel()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._loop.close()
return exc_type is None
with TestAsync() as obj:
obj.run()
print(obj.result)
[0, 1, 4, 9, 16, 25, 36, 49, 64]
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question