替代Python 3中的execfile?
 Python 2具有内置的函数execfile ,它在Python 3.0中被删除。  这个问题讨论了Python 3.0的替代方法,但自从Python 3.0以来,已经做了一些相当大的改变 。 
  Python 3.2的execfile和未来的Python 3.x版本的最佳select是什么? 
  2to3脚本(也是Python 3.2中的脚本)将被replace 
 execfile(filename, globals, locals) 
通过
 exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals) 
这似乎是官方的build议。
 execfile(filename) 
可以换成
 exec(open(filename).read()) 
它适用于所有版本的Python
 在Python3.x中,这是我能够直接执行一个文件的最接近的东西,它匹配正在运行的python /path/to/somefile.py 。 
笔记:
- 使用二进制读取来避免编码问题
- Garenteedclosures文件(Python3.x警告这个)
-  定义__main__,一些脚本依赖于这个来检查它们是否被加载为一个模块,或者不是。if __name__ == "__main__"
-  设置__file__对于exception消息更好,一些脚本使用__file__来获取其他文件相对于它们的path。
 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") 
标准的runpy.run_path是一个select。