私信  •  关注

ideasman42

ideasman42 最近创建的主题
ideasman42 最近回复了
5 年前
回复了 ideasman42 创建的主题 » ipython评估本地目录中的文件[重复]

同时 exec(open("filename").read()) 通常作为 execfile("filename") ,它忽略了重要的细节 execfile 支持。

python3.x的以下函数与直接执行文件的行为非常接近。与跑步相匹配 python /path/to/somefile.py .

def execfile(filepath, globals=None, locals=None):
    if globals is None:
        globals = {}
    globals.update({
        "__file__": filepath,
        "__name__": "__main__",
    })
    with open(filepath, 'rb') as file:
        exec(compile(file.read(), filepath, 'exec'), globals, locals)

# execute the file
execfile("/path/to/somefile.py")

笔记:

  • 使用二进制读取来避免编码问题
  • 保证关闭文件 (python3.x对此发出警告)
  • 定义 __main__ ,一些脚本依赖于此来检查它们是否作为模块加载。 if __name__ == "__main__"
  • 设置 __file__ 对于异常消息和一些脚本使用 _文件__ 获取其他文件相对于它们的路径。
  • 接受可选的全局参数和局部参数,将它们修改为 执行文件 这样您就可以在运行后通过读取变量来访问任何定义的变量。

  • 不像蟒蛇 执行文件 这是真的 默认情况下修改当前命名空间。为此,你必须明确地传递 globals() 和; locals()