Python 3中execfile的替代方案?

Mat*_*ner 51 python import execfile python-3.x

Python 2有内置函数execfile,在Python 3.0中删除了.这个问题讨论了Python 3.0的替代方案,但自Python 3.0以来已经做了一些重大的改变.

execfilePython 3.2和未来的Python 3.x版本的最佳替代方案是什么?

Sve*_*ach 59

2to3脚本(也是Python 3.2中的脚本)取代了

execfile(filename, globals, locals)
Run Code Online (Sandbox Code Playgroud)

通过

exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)
Run Code Online (Sandbox Code Playgroud)

这似乎是官方的建议.

  • 为什么这比 Lennart 的版本好? (3认同)

Len*_*bro 49

execfile(filename)
Run Code Online (Sandbox Code Playgroud)

可以替换为

exec(open(filename).read())
Run Code Online (Sandbox Code Playgroud)

适用于所有版本的Python

  • @Matt:这比较简单? (14认同)
  • @VPeric:这里的所有内容都有效,如果您有特定问题,请提出问题. (2认同)

ide*_*n42 7

在Python3.x中,这是我能够直接执行文件,匹配运行的最接近的东西python /path/to/somefile.py.

笔记:

  • 使用二进制读取来避免编码问题
  • Garenteed关闭文件(Python3.x警告这个)
  • 定义__main__,一些脚本依赖于此来检查它们是否作为模块加载,例如.if __name__ == "__main__"
  • 设置__file__对于异常消息更好,一些脚本用于__file__获取相对于它们的其他文件的路径.
def exec_full(filepath):
    import os
    global_namespace = {
        "__file__": filepath,
        "__name__": "__main__",
    }
    with open(filepath, 'rb') as file:
        exec(compile(file.read(), filepath, 'exec'), global_namespace)

# execute the file
exec_full("/path/to/somefile.py")
Run Code Online (Sandbox Code Playgroud)