似乎他们取消了在Python 3中通过删除execfile()快速加载脚本的所有简单方法
我是否错过了一个明显的选择?
似乎他们取消了在Python 3中通过删除execfile()快速加载脚本的所有简单方法
我是否错过了一个明显的选择?
当前回答
您只需读取文件并自己执行代码。2to3电流替换
execfile("somefile.py", global_vars, local_vars)
as
with open("somefile.py") as f:
code = compile(f.read(), "somefile.py", 'exec')
exec(code, global_vars, local_vars)
(并不严格需要compile调用,但它将文件名与code对象关联起来,使调试更容易一些。)
See:
http://docs.python.org/release/2.7.3/library/functions.html#execfile http://docs.python.org/release/3.2.3/library/functions.html#compile http://docs.python.org/release/3.2.3/library/functions.html#exec
其他回答
你可以写自己的函数:
def xfile(afile, globalz=None, localz=None):
with open(afile, "r") as fh:
exec(fh.read(), globalz, localz)
如果你真的需要…
正如python-dev邮件列表最近建议的那样,runpy模块可能是一个可行的替代方案。引用这条信息:
https://docs.python.org/3/library/runpy.html#runpy.run_path 进口runpy File_globals = runpy.run_path("file.py")
execfile有一些细微的区别:
Run_path总是创建一个新的名称空间。它将代码作为模块执行,因此全局变量和局部变量之间没有区别(这就是为什么只有init_globals参数)。返回全局变量。 在当前命名空间或给定命名空间中执行的Execfile。局部变量和全局变量的语义与类定义中的局部变量和全局变量相似。 Run_path不仅可以执行文件,还可以执行eggs和目录(详细信息请参阅其文档)。
虽然exec(open("filename").read())通常作为execfile("filename")的替代,但它忽略了execfile支持的重要细节。
下面是Python3的函数。x是我能得到的与直接执行文件相同的行为。匹配运行python /path/到/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")
注:
Uses binary file reading to avoid encoding issues. Guaranteed to close the file (Python3.x warns about this). Defines __main__, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__". Setting __file__ is nicer for exception messages and some scripts use __file__ to get the paths of other files relative to them. Takes optional globals & locals arguments, modifying them in-place as execfile does - so you can access any variables defined by reading back the variables after running. Unlike Python2's execfile this does not modify the current namespace by default. For that you have to explicitly pass in globals() & locals().
根据文档,而不是
execfile("./filename")
Use
exec(open("./filename").read())
See:
Python 3.0有什么新特性
这个更好,因为它从调用者那里获取全局变量和局部变量:
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)