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

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


当前回答

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

%run /path/to/filename.py

这同样简单。

其他回答

如果你想要加载的脚本和你运行的脚本在同一个目录中,也许“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。

你可以写自己的函数:

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

如果你真的需要…

注意,如果使用PEP-263编码声明,上述模式将失败 不是ASCII或utf-8。您需要找到数据的编码,并对其进行编码 在将其交给exec()之前。

class python3Execfile(object):
    def _get_file_encoding(self, filename):
        with open(filename, 'rb') as fp:
            try:
                return tokenize.detect_encoding(fp.readline)[0]
            except SyntaxError:
                return "utf-8"

    def my_execfile(filename):
        globals['__file__'] = filename
        with open(filename, 'r', encoding=self._get_file_encoding(filename)) as fp:
            contents = fp.read()
        if not contents.endswith("\n"):
            # http://bugs.python.org/issue10204
            contents += "\n"
        exec(contents, globals, globals)

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

%run /path/to/filename.py

这同样简单。

您只需读取文件并自己执行代码。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