似乎他们取消了在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
其他回答
您只需读取文件并自己执行代码。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
此外,虽然不是纯Python解决方案,但如果你正在使用IPython(无论如何你可能应该这样做),你可以:
%run /path/to/filename.py
这同样简单。
根据文档,而不是
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)
你可以写自己的函数:
def xfile(afile, globalz=None, localz=None):
with open(afile, "r") as fh:
exec(fh.read(), globalz, localz)
如果你真的需要…