Alternative to execfile in Python 3? [duplicate]

牧云@^-^@ 提交于 2019-11-26 08:09:22

问题


This question already has an answer here:

  • What is an alternative to execfile in Python 3? 11 answers

Python 2 had the builtin function execfile, which was removed in Python 3.0. This question discusses alternatives for Python 3.0, but some considerable changes have been made since Python 3.0.

What is the best alternative to execfile for Python 3.2, and future Python 3.x versions?


回答1:


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.




回答2:


execfile(filename)

can be replaced with

exec(open(filename).read())

which works in all versions of Python

Newer versions of Python will warn you that you didn't close that file, so then you can do this is you want to get rid of that warning:

with open(filename) as infile:
    exec(infile.read())

But really, if you care about closing files, you should care enough to not use exec in the first place.




回答3:


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")



回答4:


Standard runpy.run_path is an alternative.



来源:https://stackoverflow.com/questions/6357361/alternative-to-execfile-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!