Skip to content

Commit 3b2b8dd

Browse files
pi-anldpgeorge
authored andcommitted
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 <andrew.leech@planetinnovation.com.au>
1 parent 5b3c928 commit 3b2b8dd

File tree

3 files changed

+11
-0
lines changed

3 files changed

+11
-0
lines changed

shared/runtime/pyexec.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,11 @@ static int parse_compile_execute(const void *source, mp_parse_input_kind_t input
103103
}
104104
// source is a lexer, parse and compile the script
105105
qstr source_name = lex->source_name;
106+
#if MICROPY_MODULE___FILE__
107+
if (input_kind == MP_PARSE_FILE_INPUT) {
108+
mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
109+
}
110+
#endif
106111
mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
107112
#if defined(MICROPY_UNIX_COVERAGE)
108113
// allow to print the parse tree in the coverage build

tests/cmdline/cmd_file_variable.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Test that __file__ is set correctly for script execution
2+
try:
3+
print("__file__ =", __file__)
4+
except NameError:
5+
print("__file__ not defined")
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__file__ = cmdline/cmd_file_variable.py

0 commit comments

Comments
 (0)