Last active
May 5, 2022 11:59
-
-
Save travishen/770b837642f3f9b23a79c3a7d2bdbe91 to your computer and use it in GitHub Desktop.
Spinner asyncio
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import asyncio | |
@asyncio.coroutine | |
def spin(): | |
write, flush = sys.stdout.write, sys.stdout.flush | |
for char in itertools.cycle('|/-\\'): | |
msg = char + ' loading ...' | |
write(msg) | |
flush() | |
write('\x08' * len(msg)) | |
try: | |
yield from asyncio.sleep(.1) | |
except asyncio.CancelledError: | |
break | |
write(' ' * len(msg) + '\x08' * len(msg)) | |
@asyncio.coroutine | |
def slow_func(): | |
yield from asyncio.sleep(5) | |
return True | |
@asyncio.coroutine | |
def supervisor(): | |
signal = Signal() | |
spinner = asyncio.async(spin()) | |
result = yield from slow_func() | |
spinner.cancel() | |
return result | |
loop = asyncio.get_event_loop() | |
result = loop.run_until_complete(supervisor()) | |
loop.close() | |
print(f'Result: {result}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment