← index #6440PR #18107
Off-topic · high · value 0.891
QUERY · ISSUE

Implement exit() to exit for ./micropython shell

openby nanjekyejoannahopened 2020-09-13updated 2024-09-29
enhancementport-unix

I know that currently CTRL-D exits the shell.

For consistency with other python shells i.e CPython, let us implement exit() as an option to also exit the shell.

If this sounds good, i will track this for myself so that I can implement this as part of google season of docs.

CANDIDATE · PULL REQUEST

unix/main: Ensure atexit function is called on sys.exit() with -m <module>.

mergedby MikeWang000000opened 2025-09-20updated 2025-10-01
port-unix

<!-- Thanks for submitting a Pull Request! We appreciate you spending the
time to improve MicroPython. Please provide enough information so that
others can review your Pull Request.

 Before submitting, please read:
 https://github.com/micropython/micropython/blob/master/CODEOFCONDUCT.md
 https://github.com/micropython/micropython/wiki/ContributorGuidelines

 Please check any CI failures that appear after your Pull Request is opened.

-->

Summary

<!-- Explain the reason for making this change. What problem does the pull request
solve, or what improvement does it add? Add links if relevant. -->

Fixes #18103.

Previously, when running micropython -m <module> and the module called sys.exit(), the registered atexit function was not executed. This was due to sys.exit() raising a SystemExit exception, which bypassed the atexit handler. This change fixes the issue so that the atexit function is properly invoked when exiting via sys.exit().

Additionally, following the pattern in execute_from_lexer, mp_hal_set_interrupt_char() and mp_handle_pending() handling were added to ensure that the atexit function is also executed when the user exits via Ctrl-C.

Testing

<!-- Explain what testing you did, and on which boards/ports. If there are
boards or ports that you couldn't test, please mention this here as well.

 If you leave this empty then your Pull Request may be closed. -->

Tested on Linux.

a.py:

import sys, time

def onexit():
    print('Exiting...')

sys.atexit(onexit)
sys.exit(0)  # or time.sleep(1000) and press Ctrl-C
micropython -m a

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied