问题描述
|
这个问题已经在这里有了答案:
解决方法
2to3
脚本(也是Python 3.2中的脚本)替换了
execfile(filename,globals,locals)
通过
exec(compile(open(filename,\"rb\").read(),filename,\'exec\'),locals)
这似乎是官方建议。
, execfile(filename)
可以替换为
exec(open(filename).read())
适用于所有版本的Python
较新版本的Python会警告您您尚未关闭该文件,因此您可以这样做,因为您想摆脱该警告:
with open(filename) as infile:
exec(infile.read())
但是,实际上,如果您关心关闭文件,则首先应该不要使用exec
。
, 在Python3.x中,这是我直接执行与运行python /path/to/somefile.py
相匹配的文件所能想到的最接近的东西。
笔记:
使用二进制读取以避免编码问题
Garenteed关闭文件(Python3.x对此发出警告)
定义“ 8”,某些脚本依赖于此检查它们是否作为模块加载,例如。 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,global_namespace)
# execute the file
exec_full(\"/path/to/somefile.py\")
, 标准runpy.run_path是替代方法。