Python 3 中 execfile 的替代品? [重复]

问题描述 投票:0回答:4

Python 2 有内置函数

execfile
,在 Python 3.0 中被删除。 这个问题讨论了 Python 3.0 的替代方案,但是自 Python 3.0 以来已经进行了一些相当大的更改

对于 Python 3.2 和

未来的 Python 3.x 版本

execfile 的最佳替代方案是什么?
    

python python-3.x import execfile
4个回答
80
投票

2to3

脚本取代了

execfile(filename, globals, locals)

exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)

这似乎是官方推荐。您可能需要使用

with

 块来确保文件立即再次关闭:

with open(filename, "rb") as source_file: code = compile(source_file.read(), filename, "exec") exec(code, globals, locals)

您可以省略

globals

locals
 参数来在当前作用域中执行文件,或者使用 
exec(code, {})
 使用新的临时字典作为全局和本地字典,从而有效地在新的临时作用域中执行文件.


70
投票
execfile(filename)

可以替换为

exec(open(filename).read())

适用于所有版本的Python

较新版本的 Python 会警告你没有关闭该文件,因此如果你想摆脱该警告,你可以这样做:

with open(filename) as infile: exec(infile.read())

但实际上,如果您关心关闭文件,那么您应该首先注意不要使用

exec


9
投票
在Python3.x中,这是我能想到的最接近直接执行文件的方法,它与运行相匹配

python /path/to/somefile.py

备注:

    使用二进制读取以避免编码问题
  • 确保关闭文件
  • (Python3.x对此发出警告)
  • 定义了
  • __main__
    ,一些脚本依赖于此来检查它们是否作为模块加载,例如。 
    if __name__ == "__main__"
    
    
  • 设置
  • __file__
     对于异常消息来说更好,并且某些脚本使用 
    __file__
     来获取其他文件相对于它们的路径。
def exec_file(filepath): global_namespace = { "__file__": filepath, "__name__": "__main__", } with open(filepath, 'rb') as file: exec(compile(file.read(), filepath, 'exec'), global_namespace) # Execute the file. exec_file("/path/to/somefile.py")
    

4
投票
标准

runpy.run_path 是一种替代方案。

© www.soinside.com 2019 - 2024. All rights reserved.