Created
March 13, 2018 15:36
Star
You must be signed in to star a gist
Play with asyncio cancelleration
This file contains 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
import asyncio | |
from contextlib import suppress | |
def describe(t: asyncio.Future): | |
return 'Done: %s, Cancel: %s' % (t.done(), t.cancelled()) | |
async def raise_exception(n): | |
await asyncio.sleep(n) | |
raise Exception('Hello!') | |
async def counter(n): | |
for i in range(n): | |
print(i + 1) | |
await asyncio.sleep(1) | |
return n | |
async def main(loop: asyncio.AbstractEventLoop): | |
t1 = asyncio.ensure_future(counter(4)) | |
t2 = asyncio.ensure_future(counter(8)) | |
t3 = asyncio.ensure_future(raise_exception(3)) | |
# t3 = asyncio.ensure_future(counter(3)) | |
print('t1:', describe(t1)) | |
print('t2:', describe(t2)) | |
print('t3:', describe(t3)) | |
try: | |
# done, pending = await asyncio.wait([t1, t2, t3]) | |
# done, pending = await asyncio.wait([t1, t2, t3], return_when=asyncio.FIRST_COMPLETED) | |
# done, pending = await asyncio.wait([t1, t2, t3], return_when=asyncio.FIRST_EXCEPTION) | |
for f in asyncio.as_completed([t1, t2, t3]): | |
print(f) | |
try: | |
r = await f | |
print('Result:', r) | |
break | |
except Exception as e: | |
print('What:', str(e)) | |
except Exception as e: | |
print('Wow:', e) | |
else: | |
t1.cancel() | |
t2.cancel() | |
t3.cancel() | |
print('t1:', describe(t1)) | |
print('t2:', describe(t2)) | |
print('t3:', describe(t3)) | |
await asyncio.wait([t2]) | |
# for f in pending: | |
# f.cancel() | |
# if pending: | |
# await asyncio.wait(pending) | |
# for f in done: | |
# print('Done:', f.result()) | |
finally: | |
print('t1:', describe(t1)) | |
print('t2:', describe(t2)) | |
print('t3:', describe(t3)) | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main(loop)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment