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

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


当前回答

你可以写自己的函数:

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

如果你真的需要…

其他回答

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

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

    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

这是我所拥有的(在两个例子中,file已经被分配到带有源代码的文件的路径):

execfile(file)

下面是我用它替换的:

exec(compile(open(file).read(), file, 'exec'))

我最喜欢的部分是:第二个版本在Python 2和3中都工作得很好,这意味着不需要添加版本相关的逻辑。

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

如果你真的需要…

注意,如果使用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)