Alternative à execfile en Python 3? [dupliquer]
-
28-10-2019 - |
Question
Cette question a déjà une réponse ici:
python 2 avait la fonction de commande interne execfile
, qui a été retiré dans le python 3.0 . Discute alternatives de cette question pour Python 3.0, mais certains changements considérables ont été faites depuis Python 3.0 .
Quelle est la meilleure alternative à la execfile
pour Python 3.2 et futur Python 3.x versions ?
La solution
The 2to3
script (also the one in Python 3.2) replaces
execfile(filename, globals, locals)
by
exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)
This seems to be the official recommendation.
Autres conseils
execfile(filename)
can be replaced with
exec(open(filename).read())
which works in all versions of Python
In Python3.x this is the closest thing I could come up with to executing a file directly, that matches running python /path/to/somefile.py
.
Notes:
- Uses binary reading to avoid encoding issues
- Garenteed to close the file (Python3.x warns about this)
- defines
__main__
, some scripts depend on this to check if they are loading as a module or not for eg.if __name__ == "__main__"
- setting
__file__
is nicer for exception messages and some scripts use__file__
to get the paths of other files relative to them.
def exec_full(filepath):
import os
global_namespace = {
"__file__": filepath,
"__name__": "__main__",
}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
# execute the file
exec_full("/path/to/somefile.py")
Standard runpy.run_path is an alternative.