In [2]:
Collapse Code
import asyncio
# This creates an event loop and indefinitely cycles through
# its collection of jobs.
# event_loop = asyncio.new_event_loop()
# event_loop.run_forever()
# jupyter notebook has already event loop running which will through error
In [4]:
Collapse Code
def hello_printer():
print("hello")
In [5]:
Collapse Code
hello_printer()
In [6]:
Collapse Code
async def hello_async_printer():
print("hello async ")
In [7]:
Collapse Code
hello_async_printer()
Out[7]:
In [18]:
Collapse Code
coroutine =hello_async_printer()
# This creates a Task object and schedules its execution via the event loop.
task = asyncio.create_task(coroutine)
In [20]:
Collapse Code
await task
In [23]:
Collapse Code
import asyncio
async def coro_a():
print("I am coro_a(). Hi!")
async def coro_b():
print("I am coro_b(). I sure hope no one hogs the event loop...")
async def main():
task_b = asyncio.create_task(coro_b())
num_repeats = 3
for _ in range(num_repeats):
await coro_a()
await task_b
await main() # should be asyncio.run(main())
In [24]:
Collapse Code
async def main():
task_b = asyncio.create_task(coro_b())
num_repeats = 3
for _ in range(num_repeats):
await asyncio.create_task(coro_a())
await task_b
await main() # should be asyncio.run(main())
In [35]:
Collapse Code
async def main():
task_b = asyncio.create_task(coro_b())
num_repeats = 3
for _ in range(num_repeats):
print("Hello")
await asyncio.create_task(coro_a())
await task_b
await main() # should be asyncio.run(main())
In [36]:
Collapse Code
class Rock:
def __await__(self):
value_sent_in = yield 7
print(f"Rock.__await__ resuming with value: {value_sent_in}.")
return value_sent_in
async def main():
print("Beginning coroutine main().")
rock = Rock()
print("Awaiting rock...")
value_from_rock = await rock
print(f"Coroutine received value: {value_from_rock} from rock.")
return 23
coroutine = main()
intermediate_result = coroutine.send(None)
print(f"Coroutine paused and returned intermediate value: {intermediate_result}.")
print(f"Resuming coroutine and sending in value: 42.")
try:
coroutine.send(42)
except StopIteration as e:
returned_value = e.value
print(f"Coroutine main() finished and provided value: {returned_value}.")
In [45]:
Collapse Code
import datetime, time
async def other_work():
print("I like work. Work work.")
async def main():
# Add a few other tasks to the event loop, so there's something
# to do while asynchronously sleeping.
work_tasks = [
asyncio.create_task(other_work()),
asyncio.create_task(other_work()),
asyncio.create_task(other_work())
]
print(
"Beginning asynchronous sleep at time: "
f"{datetime.datetime.now().strftime("%H:%M:%S")}."
)
await asyncio.create_task(async_sleep(3))
print(
"Done asynchronous sleep at time: "
f"{datetime.datetime.now().strftime("%H:%M:%S")}."
)
# asyncio.gather effectively awaits each task in the collection.
await asyncio.gather(*work_tasks)
await main()
In [46]:
Collapse Code
async def async_sleep(seconds: float):
future = asyncio.Future()
time_to_wake = time.time() + seconds
# Add the watcher-task to the event loop.
watcher_task = asyncio.create_task(_sleep_watcher(future, time_to_wake))
# Block until the future is marked as done.
await future
await main()
In [47]:
Collapse Code
class YieldToEventLoop:
def __await__(self):
yield
async def _sleep_watcher(future, time_to_wake):
while True:
if time.time() >= time_to_wake:
# This marks the future as done.
future.set_result(None)
break
else:
await YieldToEventLoop()