Python 2中有内置函数execfile
,但在Python 3.0中已被移除。这个问题讨论了Python 3.0的替代方案,但是自Python 3.0以来已经进行了一些相当大的更改。
execfile
的最佳替代方案是什么,适用于Python 3.2和未来版本的Python 3.x?
Python 2中有内置函数execfile
,但在Python 3.0中已被移除。这个问题讨论了Python 3.0的替代方案,但是自Python 3.0以来已经进行了一些相当大的更改。
execfile
的最佳替代方案是什么,适用于Python 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)
你可以省略globals
和locals
参数以在当前作用域中执行文件,或者使用exec(code,{})
来使用新的临时字典作为全局和局部字典,有效地在新的临时作用域中执行文件。execfile(filename)
可以被替换为
exec(open(filename).read())
这适用于所有版本的Python。
较新版本的Python将会警告您没有关闭该文件,所以如果您想消除那个警告,可以执行以下操作:
with open(filename) as infile:
exec(infile.read())
但实际上,如果你关心关闭文件,就应该足够关注,不要在首次使用exec
。
exec ... in ...
的形式来执行这种情况下的exec
。例如,exec code in globals()
将会在模块的全局命名空间中执行代码。请注意,被执行的代码无法可靠地改变嵌套函数中可见的局部变量。 - Sven Marnachpython /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")
execfile(join(dirname(__file__), 'ExcelLibrary', 'version.py'))
,那么在新版本中应该怎么写呢? exec(open(filename).read())
。 - tijnnexec_full
。 - ideasman42
execfile()
调用的方式。 - Sven Marnachexec(..., {})
在新的临时范围内执行文件。 - Sven Marnachglobals
和locals
作为变量名;我也可以使用x
和y
或其他任何变量名。通常情况下,你不会使用exec(code, globals(), locals())
,因为这与仅使用exec(code)
是相同的。 - Sven Marnach