Why does this Python async script never finish? -
i created mcve example of larger code base working on, things funky way of doing things, minimal versions, not makes sense far why doing way. know work-arounds, , @ point curious why seeing behaviour.
i have following script has async function waits future. script intercepts signal set future result:
import asyncio import time import signal f = asyncio.future() loop = asyncio.get_event_loop() async def wait_till_signal(): await f def send_stop(): print('stopping', time.time()) f.set_result(true) print('sent') print(f.result()) def handle_signal(s, a): print('sending stop', time.time()) send_stop() signal.signal(signal.sigint, handle_signal) loop.run_until_complete(wait_till_signal()) this script correctly gets interrupt, , appears set future correctly, reason script never terminates.
to reproduce you, run script, hit ctrl+c. reason never stops.
now here gets weird. if add following top of script (after defining loop), script stops fine.
async def do_nothing_useful(): in range(30): await asyncio.sleep(1) loop.create_task(do_nothing_useful()) why coroutine not getting future in first case, gets correctly in second case?
also, weird thing if set send_stop function async, , add task, never gets called. (this follows same behaviour above. if do_nothing_useful() function on loop, works fine, without it, doesnt)
here version send_stop never called:
import asyncio import time import signal f = asyncio.future() async def wait_till_signal(): await f async def send_stop(): # async because trying try out crazy things print('stopping', time.time()) f.set_result(true) print('sent') print(f.result()) def handle_signal(s, a): print('sending stop', time.time()) loop.create_task(send_stop()) signal.signal(signal.sigint, handle_signal) loop = asyncio.get_event_loop() loop.run_until_complete(wait_till_signal()) print('done') and script never prints stopping.
i have tried on python 3.5.3 , 3.6 on linux
the correct method add signal handler wakes loop using loop.add_signal_handler. make sure select() wakes handle signal.
Comments
Post a Comment