From ca1fb3eb426466310efd1599a0d801fa6ed3645e Mon Sep 17 00:00:00 2001 From: Benjamin Peterson Date: Tue, 10 Mar 2015 19:06:18 -0500 Subject: [PATCH] close files explicit (closes #21610) Patch by mattip. --- Lib/modulefinder.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Lib/modulefinder.py b/Lib/modulefinder.py index f6f84f3fdea..f16b2c7b5fe 100644 --- a/Lib/modulefinder.py +++ b/Lib/modulefinder.py @@ -109,16 +109,16 @@ class ModuleFinder: def run_script(self, pathname): self.msg(2, "run_script", pathname) - fp = open(pathname, READ_MODE) - stuff = ("", "r", imp.PY_SOURCE) - self.load_module('__main__', fp, pathname, stuff) + with open(pathname, READ_MODE) as fp: + stuff = ("", "r", imp.PY_SOURCE) + self.load_module('__main__', fp, pathname, stuff) def load_file(self, pathname): dir, name = os.path.split(pathname) name, ext = os.path.splitext(name) - fp = open(pathname, READ_MODE) - stuff = (ext, "r", imp.PY_SOURCE) - self.load_module(name, fp, pathname, stuff) + with open(pathname, READ_MODE) as fp: + stuff = (ext, "r", imp.PY_SOURCE) + self.load_module(name, fp, pathname, stuff) def import_hook(self, name, caller=None, fromlist=None, level=-1): self.msg(3, "import_hook", name, caller, fromlist, level) @@ -461,6 +461,8 @@ class ModuleFinder: fp, buf, stuff = self.find_module("__init__", m.__path__) self.load_module(fqname, fp, buf, stuff) self.msgout(2, "load_package ->", m) + if fp: + fp.close() return m def add_module(self, fqname):