mirror of
https://github.com/micropython/micropython.git
synced 2025-12-16 09:50:15 +01:00
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>
This commit is contained in:
committed by
Damien George
parent
5b3c928f53
commit
3b2b8dd538
@@ -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
|
// source is a lexer, parse and compile the script
|
||||||
qstr source_name = lex->source_name;
|
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);
|
mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
|
||||||
#if defined(MICROPY_UNIX_COVERAGE)
|
#if defined(MICROPY_UNIX_COVERAGE)
|
||||||
// allow to print the parse tree in the coverage build
|
// allow to print the parse tree in the coverage build
|
||||||
|
|||||||
5
tests/cmdline/cmd_file_variable.py
Normal file
5
tests/cmdline/cmd_file_variable.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
# Test that __file__ is set correctly for script execution
|
||||||
|
try:
|
||||||
|
print("__file__ =", __file__)
|
||||||
|
except NameError:
|
||||||
|
print("__file__ not defined")
|
||||||
1
tests/cmdline/cmd_file_variable.py.exp
Normal file
1
tests/cmdline/cmd_file_variable.py.exp
Normal file
@@ -0,0 +1 @@
|
|||||||
|
__file__ = cmdline/cmd_file_variable.py
|
||||||
Reference in New Issue
Block a user