Guest User

Untitled

a guest
Nov 23rd, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. asyncio.wait([a sequence of futures])
  2.  
  3. asyncio.wait_for(a single future)
  4.  
  5. import asyncio
  6. from itertools import count
  7.  
  8. async def counter1():
  9. cnt = count(1)
  10. try:
  11. while True:
  12. print('From 1:', next(cnt))
  13. await asyncio.sleep(1)
  14. except asyncio.CancelledError:
  15. print('counter1 cancelled')
  16.  
  17. async def counter2():
  18. cnt = count(1)
  19. for i in range(5):
  20. print('From 2:', next(cnt))
  21. await asyncio.sleep(1)
  22. cnt1.cancel()
  23. # await asyncio.wait([cnt1]) # works
  24. # await asyncio.wait_for(cnt1) # hangs
  25. await asyncio.wait_for(cnt1, 1) # works
  26. loop.stop()
  27.  
  28. loop = asyncio.get_event_loop()
  29. cnt1 = asyncio.ensure_future(counter1())
  30. cnt2 = asyncio.ensure_future(counter2())
  31. loop.run_forever()
Add Comment
Please, Sign In to add comment