Guest User

asyncio.create_task

a guest
Mar 30th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.92 KB | None | 0 0
  1. import asyncio
  2. import time
  3.  
  4.  
  5. async def do_some_prints_with_sleeps(coro_id):
  6.     print(f"[{coro_id}] Hello, i am coro with asyncio.sleeps")
  7.     print(f"[{coro_id}] Will sleep right now for 1 second")
  8.     await asyncio.sleep(1)
  9.     print(f"[{coro_id}] I woke up, but feel sleepy, will sleep 1 second more")
  10.     await asyncio.sleep(1)
  11.     print(f"[{coro_id}] Aaah, that was a great day with a lot of actions")
  12.  
  13.     return f"lol u fag, and i am coro {coro_id}"
  14.  
  15.  
  16. async def some_client_code_coro():
  17.     print("Creating tasks")
  18.     task_1 = asyncio.create_task(do_some_prints_with_sleeps(1))
  19.     task_2 = asyncio.create_task(do_some_prints_with_sleeps(2))
  20.  
  21.     print("Tasks are created")
  22.     print(f"Here this guys: \n\ttask_1: {task_1}, \n\ttask_2: {task_2}")
  23.     print("As you can see, there is no output from them")
  24.     print("That's because they are only _scheduled_, and they are waiting for some attention from loop")
  25.  
  26.     print("We can even freeze this coro for 2 seconds by sync sleep without passing control to the loop, lets do that")
  27.     print("...")
  28.     time.sleep(2)
  29.     print("...")
  30.     print("See? After 2 secs there is no any print calls from our scheduled tasks")
  31.  
  32.     print("But if we pass the control to the loop by calling async sleep")
  33.     print("...")
  34.     await asyncio.sleep(1.5)
  35.     print("...")
  36.  
  37.     print('As you can see, 1.5 seconds is not enough to complete our scheduled tasks')
  38.  
  39.     print(f"Let's take a peek again: \n\ttask_1: {task_1}, \n\ttask_2: {task_2}")
  40.     print("You can see that they are still running and waiting for something (it's internal)")
  41.  
  42.     print("Let's do that trick with sync sleep again")
  43.     print('...')
  44.     time.sleep(2)
  45.     print('...')
  46.     print('You see? Still no result. Last print calls in our tasks are waiting for their time')
  47.  
  48.     print("We will pass the control to the async loop one more time, again, by asyncio.sleep()")
  49.     print("...")
  50.     await asyncio.sleep(0.5)
  51.     print("...")
  52.  
  53.     print("So here they are, last words of our tasks")
  54.     print(f"Let's look at them last time: \n\ttask_1: {task_1}, \n\ttask_2: {task_2}")
  55.     print("Now, they are finished, also you can mention the result field in reprs of this tasks")
  56.  
  57.     print("The last thing is - how to get their results?")
  58.     print("There are two ways, first is awaiting them")
  59.     result_1 = await task_1
  60.     print(f"await task_1 > {result_1!r}")
  61.  
  62.     print("But as we now, these Tasks are finished, so we can call the .result() method directly")
  63.     result_2 = task_2.result()
  64.     print(f"task_2.result() > {result_2!r}")
  65.  
  66.     print("So, that's all, thank you for your attention!")
  67.  
  68.     print(f"\n!! Be aware !!")
  69.     print("If you will call .result method on running task, the exception like that will be raised:")
  70.     print("'asyncio.base_futures.InvalidStateError: Result is not set.'")
  71.  
  72.  
  73. if __name__ == "__main__":
  74.     asyncio.get_event_loop().run_until_complete(some_client_code_coro())
Advertisement
Add Comment
Please, Sign In to add comment