Created
July 17, 2019 18:31
-
-
Save dvmn-tasks/93b4152b5810ae2cdf9a49d720a93b6a to your computer and use it in GitHub Desktop.
Async code example
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 asyncio | |
import itertools | |
import aionursery | |
PRELOADER_SYMBOLS = [ | |
'|', | |
'/', | |
'—', | |
'\\', | |
] | |
async def countdown(count, prefix=''): | |
for secs_left in range(count, 0, -1): | |
print(f'{prefix}Осталось {secs_left} секунд') | |
raise Exception('fixme') | |
await asyncio.sleep(1) | |
return 'result' | |
async def show_preloader(prefix=''): | |
for symbol in itertools.cycle(PRELOADER_SYMBOLS): | |
print(f'{prefix}{symbol}', '\u001b[1A') | |
try: | |
await asyncio.sleep(0.1) | |
except asyncio.CancelledError as exc: | |
print('got it', type(exc)) | |
print('stopping... 3') | |
await asyncio.sleep(1) | |
print('stopping... 2') | |
await asyncio.sleep(1) | |
print('stopping... 1') | |
await asyncio.sleep(1) | |
raise exc | |
async def run_timer(prefix=''): | |
async with aionursery.Nursery() as nursery: | |
nursery.start_soon(countdown(10, prefix=prefix)) | |
nursery.start_soon(show_preloader(prefix=prefix)) | |
async def async_main(): | |
try: | |
async with aionursery.Nursery() as nursery: | |
nursery.start_soon(run_timer()) | |
nursery.start_soon(run_timer(prefix=' ' * 30)) | |
except aionursery.MultiError as exc: | |
print('Got error', type(exc)) | |
print('Done') | |
if __name__ == '__main__': | |
try: | |
asyncio.run(async_main()) | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment