From 3b2b8dd53826ef3b7ef755013e1ecdccd368cb8c Mon Sep 17 00:00:00 2001 From: Andrew Leech Date: Mon, 26 May 2025 19:28:40 +1000 Subject: [PATCH] shared/runtime/pyexec: Set __file__ for file input when enabled. When `MICROPY_MODULE___FILE__` is enabled and parsing file input, set the global `__file__` variable to the source filename. This matches the behavior of the unix port and provides the current filename to the executing script. Signed-off-by: Andrew Leech --- shared/runtime/pyexec.c | 5 +++++ tests/cmdline/cmd_file_variable.py | 5 +++++ tests/cmdline/cmd_file_variable.py.exp | 1 + 3 files changed, 11 insertions(+) create mode 100644 tests/cmdline/cmd_file_variable.py create mode 100644 tests/cmdline/cmd_file_variable.py.exp diff --git a/shared/runtime/pyexec.c b/shared/runtime/pyexec.c index 237a6f9df1..6196367834 100644 --- a/shared/runtime/pyexec.c +++ b/shared/runtime/pyexec.c @@ -103,6 +103,11 @@ static int parse_compile_execute(const void *source, mp_parse_input_kind_t input } // source is a lexer, parse and compile the script qstr source_name = lex->source_name; + #if MICROPY_MODULE___FILE__ + if (input_kind == MP_PARSE_FILE_INPUT) { + mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); + } + #endif mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); #if defined(MICROPY_UNIX_COVERAGE) // allow to print the parse tree in the coverage build diff --git a/tests/cmdline/cmd_file_variable.py b/tests/cmdline/cmd_file_variable.py new file mode 100644 index 0000000000..6cac6744d9 --- /dev/null +++ b/tests/cmdline/cmd_file_variable.py @@ -0,0 +1,5 @@ +# Test that __file__ is set correctly for script execution +try: + print("__file__ =", __file__) +except NameError: + print("__file__ not defined") diff --git a/tests/cmdline/cmd_file_variable.py.exp b/tests/cmdline/cmd_file_variable.py.exp new file mode 100644 index 0000000000..6807569f66 --- /dev/null +++ b/tests/cmdline/cmd_file_variable.py.exp @@ -0,0 +1 @@ +__file__ = cmdline/cmd_file_variable.py