unix/main: Ensure atexit function is called with -m <module>.

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.

Signed-off-by: Mike Wang <mikewang000000@gmail.com>
This commit is contained in:
Mike Wang
2025-09-21 00:09:17 +08:00
committed by Damien George
parent cf097932a2
commit 8c389db6ea

View File

@@ -669,12 +669,18 @@ MP_NOINLINE int main_(int argc, char **argv) {
subpkg_tried = false;
reimport:
mp_hal_set_interrupt_char(CHAR_CTRL_C);
if (nlr_push(&nlr) == 0) {
mod = mp_builtin___import__(MP_ARRAY_SIZE(import_args), import_args);
mp_hal_set_interrupt_char(-1);
mp_handle_pending(true);
nlr_pop();
} else {
// uncaught exception
return handle_uncaught_exception(nlr.ret_val) & 0xff;
mp_hal_set_interrupt_char(-1);
mp_handle_pending(false);
ret = handle_uncaught_exception(nlr.ret_val) & 0xff;
break;
}
// If this module is a package, see if it has a `__main__.py`.