似乎他们取消了在Python 3中通过删除execfile()快速加载脚本的所有简单方法

我是否错过了一个明显的选择?


当前回答

这个更好,因为它从调用者那里获取全局变量和局部变量:

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)

其他回答

此外,虽然不是纯Python解决方案,但如果你正在使用IPython(无论如何你可能应该这样做),你可以:

%run /path/to/filename.py

这同样简单。

我在这里只是个新手,所以如果我发现这个,可能纯粹是运气:

尝试运行脚本后,从解释器提示>>>与命令

    execfile('filename.py')

为此我得到了一个“NameError: name 'execfile' is not defined”,我尝试了一个非常基本的

    import filename

它工作得很好:-)

我希望这能对你有所帮助,感谢大家提供的提示、示例和所有那些对新手有很大启发的注释代码!

我使用Ubuntu 16.014 LTS x64。Python 3.5.2(默认,2016年11月17日17:05:23) [GCC 5.4.0 20160609

你可以写自己的函数:

def xfile(afile, globalz=None, localz=None):
    with open(afile, "r") as fh:
        exec(fh.read(), globalz, localz)

如果你真的需要…

这个更好,因为它从调用者那里获取全局变量和局部变量:

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)

如果你想要加载的脚本和你运行的脚本在同一个目录中,也许“import”就可以了?

如果你需要动态导入代码,内置函数__ import__和模块imp值得一看。

>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'

test.py:

def run():
        return "Hello world!"

如果您使用的是Python 3.1或更高版本,还应该看一看importlib。