当exec(open("filename").read())通常被认为是替代execfile("filename"),它忽略了一些重要的细节execfile支持。
下面的Python3.x函数与直接执行文件的行为非常接近。与跑步相匹配的python /path/to/somefile.py.def execfile(filepath, globals=None, locals=None):
if globals is None:
globals = {}
globals.update({
"__file__": filepath,
"__name__": "__main__",
})
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), globals, locals)# execute the fileexecfile("/path/to/somefile.py")
注:使用二进制读取以避免编码问题。
保证关闭文件
(Python3.x对此发出警告)
定义
__main__一些脚本依赖于此来检查它们是否作为模块加载。
if __name__ == "__main__"
设置
__file__对于异常消息和一些脚本使用的
__file__获取相对于它们的其他文件的路径。
接受可选的全局参数和局部变量,将它们修改为execfile这样,您就可以在运行后通过读取变量来访问任何定义的变量。
不像Python 2execfile这确实是不默认情况下修改当前命名空间。为此,您必须显式地传递globals() & locals().