Skip to content

Instantly share code, notes, and snippets.

@lambdalisue
Created March 13, 2018 15:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lambdalisue/652dd1166ceb9b500666a38d5a7ab873 to your computer and use it in GitHub Desktop.
Play with asyncio cancelleration
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