看来他们在Python 3中取消了全部简单的方法,即经过删除execfile()
快速加载脚本 html
我是否有明显的替代品? python
根据文档 ,而不是 ide
execfile("./filename")
采用 编码
exec(open("./filename").read())
看到: spa
正如最近在python-dev邮件列表上建议的那样 , runpy模块多是一个可行的替代方案。 引用该消息: code
https://docs.python.org/3/library/runpy.html#runpy.run_path htm
import runpy file_globals = runpy.run_path("file.py")
execfile
有细微的差异: ip
run_path
始终建立一个新的名称空间。 它做为模块执行代码,所以全局变量和init_globals
变量之间没有区别(这就是为何只有init_globals
参数的缘由)。 返回全局变量。 文档
在当前名称空间或给定名称空间中执行的execfile
。 若是给出了locals
和globals
的语义,则它们与类定义中的locals和globals类似。 get
run_path
不只能够执行文件,还能够执行蛋和目录(有关详细信息,请参阅其文档)。
这就是我所拥有的(两个示例中的文件都已使用源代码将文件分配到file
的路径):
execfile(file)
这是我替换为的内容:
exec(compile(open(file).read(), file, 'exec'))
我最喜欢的部分:第二个版本在Python 2和3中均可以正常工做,这意味着没必要添加依赖于版本的逻辑。
这是更好的方法,由于它从调用者那里获取了全局变量和本地变量:
import sys def execfile(filename, globals=None, locals=None): if globals is None: globals = sys._getframe(1).f_globals if locals is None: locals = sys._getframe(1).f_locals with open(filename, "r") as fh: exec(fh.read()+"\n", globals, locals)
尽管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 file execfile("/path/to/somefile.py")
笔记:
__main__
,某些脚本依赖于此来检查它们是否做为模块加载,例如。 if __name__ == "__main__"
__file__
更好,某些脚本使用__file__
来获取其余文件相对于它们的路径。 接受可选的globals和locals参数,就像execfile
同样就地对其进行修改-所以,您能够经过在运行后回读变量来访问定义的任何变量。
与Python2的execfile
不一样,这默认状况下不会修改当前名称空间。 为此,您必须显式传递globals()
和locals()
。