Created
October 8, 2016 20:53
-
-
Save mattrasband/4ca946f4618389fbc337912c0477de4e to your computer and use it in GitHub Desktop.
Naive Asyncio Play
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Naive implementation of an iterable queue in asyncio | |
""" | |
#!/usr/bin/env python3 | |
import asyncio | |
class Queue(asyncio.Queue): | |
async def __aiter__(self): | |
return self | |
async def __anext__(self): | |
try: | |
return await self.get() | |
except asyncio.CancelledError: | |
raise StopAsyncIteration | |
q = Queue() | |
async def iterate_it(q): | |
async for elem in q: | |
print(elem) | |
q.task_done() | |
async def generate_it(q): | |
for i in range(10): | |
await q.put("foobar {}".format(i)) | |
await asyncio.sleep(2) | |
loop = asyncio.get_event_loop() | |
task = loop.create_task(iterate_it(q)) | |
try: | |
loop.run_until_complete(generate_it(q)) | |
except KeyboardInterrupt: | |
pass | |
finally: | |
task.cancel() | |
loop.run_until_complete(asyncio.gather(*asyncio.Task.all_tasks())) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment