example-code-2e/19-concurrency/spinner_async_experiment.py

40 lines
1.0 KiB
Python
Raw Normal View History

2021-01-21 02:32:36 +01:00
# spinner_async_experiment.py
# credits: Example by Luciano Ramalho inspired by
# Michele Simionato's multiprocessing example in the python-list:
# https://mail.python.org/pipermail/python-list/2009-February/675659.html
import asyncio
import itertools
2021-02-13 03:41:11 +01:00
import time
2021-01-21 02:32:36 +01:00
async def spin(msg: str) -> None:
for char in itertools.cycle(r'\|/-'):
status = f'\r{char} {msg}'
print(status, flush=True, end='')
try:
await asyncio.sleep(.1)
except asyncio.CancelledError:
break
print('THIS WILL NEVER BE OUTPUT')
# tag::SPINNER_ASYNC_EXPERIMENT[]
async def slow() -> int:
2021-02-13 03:41:11 +01:00
time.sleep(3) # <4>
2021-01-21 02:32:36 +01:00
return 42
async def supervisor() -> int:
spinner = asyncio.create_task(spin('thinking!')) # <1>
2021-02-13 19:35:34 +01:00
print(f'spinner object: {spinner}') # <2>
2021-01-21 02:32:36 +01:00
result = await slow() # <3>
spinner.cancel() # <5>
return result
# end::SPINNER_ASYNC_EXPERIMENT[]
def main() -> None:
result = asyncio.run(supervisor())
2021-02-13 19:35:34 +01:00
print(f'Answer: {result}')
2021-01-21 02:32:36 +01:00
if __name__ == '__main__':
main()