Skip to content

USB disconnects with asyncio program that has exception in task #6706

Closed
@jepler

Description

@jepler

CircuitPython version

Adafruit CircuitPython 8.0.0-alpha.1-96-g3bff36685-dirty on 2022-08-06; Raspberry Pi Pico with rp2040

Code/REPL

# SPDX-FileCopyrightText: 2022 Dan Halbert for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import asyncio
import board
import digitalio

async def blink(pin, interval, count):  # Don't forget the async!
    with digitalio.DigitalInOut(pin) as led:
        led.switch_to_output(value=False)
        for _ in range(count):
            led.value = True
            await asyncio.sleep(interval)  # Don't forget the await!
            led.value = False
            await asyncio.sleep(interval)  # Don't forget the await!

async def crash():
    1/0

async def main():  # Don't forget the async!
    led_task = asyncio.create_task(blink(board.LED, 0.25, 10))
    crash_task = asyncio.create_task(crash())
    await asyncio.gather(led_task, crash_task)  # Don't forget the await!
    print("done")


asyncio.run(main())

Behavior

A traceback is printed, the LED blinks 10 times beause the led_task keeps running, and then the device becomes unresponsive (eventual USB disconnect):

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Traceback (most recent call last):
  File "/lib/asyncio/core.py", line 214, in run_until_complete
  File "code.py", line 19, in crash
ZeroDivisionError: division by zero

[tio 11:47:17] Disconnected

Note that before the 10 blinks have completed, it's possible to ctrl-c and get to a working repl.

Take care when using this code; you may need to know how to start your device in safe mode so that it doesn't just end up in a cycle of freezing.

Description

Situations like this frequently occur during the development of asyncio programs, so it'd be nice if the whole device didn't crash.

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions