asyncio try/except/finally handling skipped if `asyncio.run()` catches KeyboardInterrupt - asyncio.start_server() keeps running
Port, board and/or hardware
probably all, at least posix and esp32
MicroPython version
MicroPython v1.24.0-preview.276.g1897fe622 on 2024-09-02; linux [GCC 11.4.0] version
also tried with
v1.23.0-preview.57.ge111793d8 on 2024-08-30; linux [GCC 11.4.0] version
Reproduction
demo.py:
import asyncio
async def async_func():
try:
while True:
print("step")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("async_foo:CancelledError")
except KeyboardInterrupt:
print("async_foo:KeyboardInterrupt")
finally:
print("async_foo:finally")
try:
asyncio.run(async_func())
except KeyboardInterrupt:
print("run:KeyboardInterrupt")
finally:
print("run:finally")
Running the provided snippet on either micropython built for Linux or on an ESP32 via mpremote and aborting the script using CTRL-C terminates the program, but the finally block inside async_func() won't be called:
$ path/to/micropython demo.py
step
...
step
^Crun:KeyboardInterrupt
run:finally
Expected behaviour
CPython executing the same snippet gives
$ python demo.py
step
step
^Casync_foo:CancelledError
async_foo:finally
run:finally
indicating that the finally block is being executed.
Observed behaviour
It looks like MicroPythons asyncio.run() catches KeyboardInterrupt and instantly kills the event loop, skipping all code that might handle exceptions or doing unconditional stuff in finally.
While this might be desired behavior on IoT devices in general, the task created with asyncio.start_server wont be terminated, resulting in OSError: [Errno 112] EADDRINUSE error, if you started an asynchronous Micropython web server, terminated it, and tried to restart it.
See https://stackoverflow.com/questions/78886486/in-micropython-how-can-i-guarantee-asynchronous-tasks-being-shut-down
Additional Information
StackOverflow: In Micropython, how can I guarantee asynchronous tasks being shut down?](https://stackoverflow.com/questions/78886486/in-micropython-how-can-i-guarantee-asynchronous-tasks-being-shut-down)
Code of Conduct
Yes, I agree
uasyncio: Behaviour differs from CPython.
Consider this script:
try:
import uasyncio as asyncio
except ImportError:
import asyncio
evt = asyncio.Event()
async def foo():
try:
await evt.wait()
finally:
print('Finally')
async def main():
t = asyncio.create_task(foo())
await asyncio.sleep(1)
t. cancel()
# Can be fixed with .sleep(0) here
print('canned')
await asyncio.sleep(1)
asyncio.run(main())
On MP the outcome is:
MicroPython v1.19.1-617-g43dd3ea74 on 2022-11-08; linux [GCC 9.4.0] version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import rats
canned
Finally
>>>
On CPython:
$ python3
Python 3.8.10 (default, Jun 22 2022, 20:18:18)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import rats
Finally
canned
>>>
MP behaviour also confirmed on Pyboard.