|
| 1 | +# spinner_async.py |
| 2 | + |
| 3 | +# credits: Example by Luciano Ramalho inspired by |
| 4 | +# Michele Simionato's multiprocessing example in the python-list: |
| 5 | +# https://mail.python.org/pipermail/python-list/2009-February/675659.html |
| 6 | + |
| 7 | +# tag::SPINNER_ASYNC_TOP[] |
| 8 | +import asyncio |
| 9 | +import itertools |
| 10 | + |
| 11 | +async def spin(msg: str) -> None: # <1> |
| 12 | + for char in itertools.cycle(r'\|/-'): |
| 13 | + status = f'\r{char} {msg}' |
| 14 | + print(status, flush=True, end='') |
| 15 | + try: |
| 16 | + await asyncio.sleep(.1) # <2> |
| 17 | + except asyncio.CancelledError: # <3> |
| 18 | + break |
| 19 | + blanks = ' ' * len(status) |
| 20 | + print(f'\r{blanks}\r', end='') |
| 21 | + |
| 22 | +async def slow() -> int: |
| 23 | + await asyncio.sleep(3) # <4> |
| 24 | + return 42 |
| 25 | +# end::SPINNER_ASYNC_TOP[] |
| 26 | + |
| 27 | +# tag::SPINNER_ASYNC_START[] |
| 28 | +def main() -> None: # <1> |
| 29 | + result = asyncio.run(supervisor()) # <2> |
| 30 | + print('Answer:', result) |
| 31 | + |
| 32 | +async def supervisor() -> int: # <3> |
| 33 | + spinner = asyncio.create_task(spin('thinking!')) # <4> |
| 34 | + print('spinner object:', spinner) # <5> |
| 35 | + result = await slow() # <6> |
| 36 | + spinner.cancel() # <7> |
| 37 | + return result |
| 38 | + |
| 39 | +if __name__ == '__main__': |
| 40 | + main() |
| 41 | +# end::SPINNER_ASYNC_START[] |
0 commit comments