execfile
,在 Python 3.0 中被删除。 这个问题讨论了 Python 3.0 的替代方案,但是自 Python 3.0 以来已经进行了一些相当大的更改。
对于 Python 3.2 和未来的 Python 3.x 版本,
execfile
的最佳替代方案是什么?
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)
您可以省略
globals
和
locals
参数来在当前作用域中执行文件,或者使用
exec(code, {})
使用新的临时字典作为全局和本地字典,从而有效地在新的临时作用域中执行文件.
execfile(filename)
可以替换为
exec(open(filename).read())
适用于所有版本的Python
较新版本的 Python 会警告你没有关闭该文件,因此如果你想摆脱该警告,你可以这样做:
with open(filename) as infile:
exec(infile.read())
但实际上,如果您关心关闭文件,那么您应该首先注意不要使用
exec
。
python /path/to/somefile.py
。备注:
__main__
,一些脚本依赖于此来检查它们是否作为模块加载,例如。
if __name__ == "__main__"
__file__
对于异常消息来说更好,并且某些脚本使用
__file__
来获取其他文件相对于它们的路径。
def exec_file(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_file("/path/to/somefile.py")
runpy.run_path 是一种替代方案。