I want to wrap a function that dynamically executes a file as code on Python 3. exec
has optional arguments globals
, locals
, whose default values are globals()
and locals()
of the current context, respectively. How can I achieve this effect with my own wrapped functions?
- have tried
def file(filepath,globals=globals(),locals=locals())
with no effect. - Checking the implementation of
exec
, I found it defined indef exec(__object: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ... , __locals: Optional[Mapping[str, Any]] = ...) -> Any: ...
, using this argument list directly will result in a syntax error.
The current function is defined like this
def file(filepath,globals,locals):
with open(filepath, 'r', encoding='utf8') as textFileObj:
return exec(compile(textFileObj.read(), filepath, 'exec'),globals,locals)
only be passed in manually in this way, and although this process can be simplified by methods such as snippet to achieve similar experience, it is always more convenient to have the default values.
Exe.file(Path.here(__file__,'HelloWorld.py'),globals(),locals())