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

42 lines
1.1 KiB
Python
Raw Normal View History

2021-02-13 03:41:11 +01:00
# spinner_async.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
# tag::SPINNER_ASYNC_TOP[]
import asyncio
import itertools
async def spin(msg: str) -> None: # <1>
for char in itertools.cycle(r'\|/-'):
status = f'\r{char} {msg}'
print(status, flush=True, end='')
try:
await asyncio.sleep(.1) # <2>
except asyncio.CancelledError: # <3>
break
blanks = ' ' * len(status)
print(f'\r{blanks}\r', end='')
async def slow() -> int:
await asyncio.sleep(3) # <4>
return 42
# end::SPINNER_ASYNC_TOP[]
# tag::SPINNER_ASYNC_START[]
def main() -> None: # <1>
result = asyncio.run(supervisor()) # <2>
2021-02-13 19:35:34 +01:00
print(f'Answer: {result}')
2021-02-13 03:41:11 +01:00
async def supervisor() -> int: # <3>
spinner = asyncio.create_task(spin('thinking!')) # <4>
2021-02-13 19:35:34 +01:00
print(f'spinner object: {spinner}') # <5>
2021-02-13 03:41:11 +01:00
result = await slow() # <6>
spinner.cancel() # <7>
return result
if __name__ == '__main__':
main()
# end::SPINNER_ASYNC_START[]