?
handle_key javascript . . .
Coroutines -: yield from await coroutine , , :
async def a():
await asyncio.sleep(1)
async def main():
await a()
await b()
asyncio.sleep(0.5) - , , handle_key finsihed.
task, " ". ( , clearTimeout(this.timeout)), , .
Python, javascript:
import asyncio
from contextlib import suppress
global_state = ''
timeout = None
async def handle_key(key):
global global_state, timeout
global_state += key
if timeout:
timeout.cancel()
with suppress(asyncio.CancelledError):
await timeout
async def callback():
await asyncio.sleep(0.5)
print(global_state)
timeout = asyncio.ensure_future(callback())
async def main():
await handle_key('a')
await handle_key('b')
if timeout:
await timeout
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()
?
, asyncio. javascript , asyncio .
, , ( - ) . , async.
async/await javascript ( Python async/await) , callbacks/promises. .
, Python.
Upd:
buttons.check driver.get_buttons(), . .
- button_handler(callback) ( , ), , asyncio.Future .
GUI- asyncio . , , .
,
asyncio / :
.
import asyncio
from contextlib import suppress
async def main():
while True:
print('We at main window, popup closed')
key = await key_pressed
if key == 'Enter':
print('Enter - open some popup')
await popup()
print('Popup was closed')
elif key == 'Esc':
print('Esc - exit program')
return
async def popup():
while True:
key = await key_pressed
if key == 'Esc':
print('Esc inside popup, let us close it')
return
else:
print('Non escape key inside popup, play sound')
async def button_check():
while True:
global key_pressed
for key in get_buttons():
key_pressed.set_result(key)
key_pressed = asyncio.Future()
await asyncio.sleep(0.01)
def run_my_loop(coro):
loop = asyncio.get_event_loop()
buttons_task = asyncio.ensure_future(button_check())
try:
loop.run_until_complete(main())
finally:
buttons_task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(buttons_task)
loop.close()
if __name__ == '__main__':
run_my_loop(main())