Python 2 有内置函数execfile,在 Python 3.0 中被删除。这个问题讨论了 Python 3.0 的替代方案,但自 Python 3.0 以来已经进行了一些相当大的更改。
execfilePython 3.2 和未来的 Python 3.x 版本的最佳替代方案是什么?
Python 2 有内置函数execfile,在 Python 3.0 中被删除。这个问题讨论了 Python 3.0 的替代方案,但自 Python 3.0 以来已经进行了一些相当大的更改。
execfilePython 3.2 和未来的 Python 3.x 版本的最佳替代方案是什么?
脚本2to3替换
execfile(filename, globals, locals)
经过
exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)
这似乎是官方的建议。您可能希望使用with块来确保文件立即再次关闭:
with open(filename, "rb") as source_file:
code = compile(source_file.read(), filename, "exec")
exec(code, globals, locals)
您可以省略globalsandlocals参数以在当前范围内执行文件,或者使用exec(code, {})新的临时字典作为全局和本地字典,从而在新的临时范围内有效地执行文件。
execfile(filename)
可以替换为
exec(open(filename).read())
它适用于所有版本的 Python
较新版本的 Python 会警告您没有关闭该文件,因此您可以这样做,如果您想摆脱该警告:
with open(filename) as infile:
exec(infile.read())
但实际上,如果您关心关闭文件,那么您应该一开始就不要使用exec它。
在 Python3.x 中,这是我能想到的最接近直接执行文件的方法,它与 running 匹配python /path/to/somefile.py。
笔记:
__main__,一些脚本依赖于此来检查它们是否作为模块加载,例如。if __name__ == "__main__"__file__对于异常消息更好,一些脚本用于__file__获取其他文件相对于它们的路径。def exec_full(filepath):
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")
标准runpy.run_path是另一种选择。