From 18ef90c8ca658e5d2ebb1a6b75dabf7ac9cdea5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Schoentgen?= Date: Tue, 28 Aug 2018 13:57:35 +0200 Subject: [PATCH] Use the with context manager instead of open/close. --- PyInstaller/archive/writers.py | 6 +++--- PyInstaller/building/makespec.py | 23 +++++++++++----------- PyInstaller/depend/bindepend.py | 10 ++++------ PyInstaller/depend/dylib.py | 13 ++++++------ PyInstaller/loader/pyimod03_importers.py | 6 ++---- PyInstaller/utils/cliutils/grab_version.py | 5 ++--- PyInstaller/utils/osx.py | 5 ++--- PyInstaller/utils/win32/versioninfo.py | 5 ++--- PyInstaller/utils/win32/winmanifest.py | 13 ++++++------ PyInstaller/utils/win32/winresource.py | 5 ++--- tests/old_suite/runtests.py | 7 +++---- tests/unit/test_altgraph/test_dot.py | 6 ++---- tests/unit/test_modulegraph/test_zipio.py | 20 ++++++++----------- 13 files changed, 53 insertions(+), 71 deletions(-) diff --git a/PyInstaller/archive/writers.py b/PyInstaller/archive/writers.py index a14034d905..df0d577358 100644 --- a/PyInstaller/archive/writers.py +++ b/PyInstaller/archive/writers.py @@ -112,9 +112,9 @@ def add(self, entry): ispkg = pynm == '__init__' assert ext in ('.pyc', '.pyo') self.toc.append((nm, (ispkg, self.lib.tell()))) - f = open(entry[1], 'rb') - f.seek(8) # skip magic and timestamp - self.lib.write(f.read()) + with open(entry[1], 'rb') as f: + f.seek(8) # skip magic and timestamp + self.lib.write(f.read()) def save_trailer(self, tocpos): """ diff --git a/PyInstaller/building/makespec.py b/PyInstaller/building/makespec.py index 648beecf98..c2cc285040 100644 --- a/PyInstaller/building/makespec.py +++ b/PyInstaller/building/makespec.py @@ -437,17 +437,16 @@ def main(scripts, name=None, onefile=None, # Write down .spec file to filesystem. specfnm = os.path.join(specpath, name + '.spec') - specfile = open(specfnm, 'w') - if onefile: - specfile.write(onefiletmplt % d) - # For OSX create .app bundle. - if is_darwin and not console: - specfile.write(bundleexetmplt % d) - else: - specfile.write(onedirtmplt % d) - # For OSX create .app bundle. - if is_darwin and not console: - specfile.write(bundletmplt % d) - specfile.close() + with open(specfnm, 'w') as specfile: + if onefile: + specfile.write(onefiletmplt % d) + # For OSX create .app bundle. + if is_darwin and not console: + specfile.write(bundleexetmplt % d) + else: + specfile.write(onedirtmplt % d) + # For OSX create .app bundle. + if is_darwin and not console: + specfile.write(bundletmplt % d) return specfnm diff --git a/PyInstaller/depend/bindepend.py b/PyInstaller/depend/bindepend.py index 03350370cd..cde0bd8809 100644 --- a/PyInstaller/depend/bindepend.py +++ b/PyInstaller/depend/bindepend.py @@ -319,9 +319,8 @@ def check_extract_from_egg(pth, todir=None): dirname = os.path.dirname(pth) if not os.path.isdir(dirname): os.makedirs(dirname) - f = open(pth, "wb") - f.write(egg.read(member)) - f.close() + with open(pth, "wb") as f: + f.write(egg.read(member)) rv.append((pth, eggpth, member)) return rv return [(pth, None, None)] @@ -343,9 +342,8 @@ def getAssemblies(pth): # check for manifest file manifestnm = pth + ".manifest" if os.path.isfile(manifestnm): - fd = open(manifestnm, "rb") - res = {RT_MANIFEST: {1: {0: fd.read()}}} - fd.close() + with open(manifestnm, "rb") as fd: + res = {RT_MANIFEST: {1: {0: fd.read()}}} else: # check the binary for embedded manifest try: diff --git a/PyInstaller/depend/dylib.py b/PyInstaller/depend/dylib.py index ef089644aa..da2c4460ec 100644 --- a/PyInstaller/depend/dylib.py +++ b/PyInstaller/depend/dylib.py @@ -311,12 +311,11 @@ def match_func(pth): # Write changes into file. # Write code is based on macholib example. try: - f = open(dll.filename, 'rb+') - for header in dll.headers: - f.seek(0) - dll.write(f) - f.seek(0, 2) - f.flush() - f.close() + with open(dll.filename, 'rb+') as f: + for header in dll.headers: + f.seek(0) + dll.write(f) + f.seek(0, 2) + f.flush() except Exception: pass diff --git a/PyInstaller/loader/pyimod03_importers.py b/PyInstaller/loader/pyimod03_importers.py index db7b63a869..2a2120dbff 100644 --- a/PyInstaller/loader/pyimod03_importers.py +++ b/PyInstaller/loader/pyimod03_importers.py @@ -760,10 +760,8 @@ def get_data(self, path): module.__file__ (or pkg.__path__ items) """ # Since __file__ attribute works properly just try to open and read it. - fp = open(path, 'rb') - content = fp.read() - fp.close() - return content + with open(path, 'rb') as fp: + return fp.read() def get_filename(self, fullname): """ diff --git a/PyInstaller/utils/cliutils/grab_version.py b/PyInstaller/utils/cliutils/grab_version.py index 50b6f25cea..a9b0fcfbe8 100644 --- a/PyInstaller/utils/cliutils/grab_version.py +++ b/PyInstaller/utils/cliutils/grab_version.py @@ -31,9 +31,8 @@ def run(): vs = PyInstaller.utils.win32.versioninfo.decode(args.exe_file) if not vs: raise SystemExit("Error: VersionInfo resource not found in exe") - fp = codecs.open(args.out_filename, 'w', 'utf-8') - fp.write(u"%s" % (vs,)) - fp.close() + with codecs.open(args.out_filename, 'w', 'utf-8') as fp: + fp.write(u"%s" % (vs,)) print(('Version info written to: %s' % args.out_filename)) except KeyboardInterrupt: raise SystemExit("Aborted by user request.") diff --git a/PyInstaller/utils/osx.py b/PyInstaller/utils/osx.py index c2915247ba..1fb07f8c83 100644 --- a/PyInstaller/utils/osx.py +++ b/PyInstaller/utils/osx.py @@ -101,6 +101,5 @@ def fix_exe_for_code_signing(filename): linkedit.filesize = new_segsize linkedit.vmsize = new_segsize ## Write changes back. - fp = open(exe_data.filename, 'rb+') - exe_data.write(fp) - fp.close() + with open(exe_data.filename, 'rb+') as fp: + exe_data.write(fp) diff --git a/PyInstaller/utils/win32/versioninfo.py b/PyInstaller/utils/win32/versioninfo.py index 723b73be8e..08ac93d610 100644 --- a/PyInstaller/utils/win32/versioninfo.py +++ b/PyInstaller/utils/win32/versioninfo.py @@ -577,9 +577,8 @@ def SetVersion(exenm, versionfile): if isinstance(versionfile, VSVersionInfo): vs = versionfile else: - fp = codecs.open(versionfile, text_read_mode, 'utf-8') - txt = fp.read() - fp.close() + with codecs.open(versionfile, text_read_mode, 'utf-8') as fp: + txt = fp.read() vs = eval(txt) hdst = win32api.BeginUpdateResource(exenm, 0) win32api.UpdateResource(hdst, pefile.RESOURCE_TYPE['RT_VERSION'], 1, vs.toRaw()) diff --git a/PyInstaller/utils/win32/winmanifest.py b/PyInstaller/utils/win32/winmanifest.py index 28a2a499ac..8fa20d7b1e 100644 --- a/PyInstaller/utils/win32/winmanifest.py +++ b/PyInstaller/utils/win32/winmanifest.py @@ -183,9 +183,8 @@ def calc_hash(self, hashalg=None): e.g. to update the hash if the file has changed. """ - fd = open(self.filename, "rb") - buf = fd.read() - fd.close() + with open(self.filename, "rb") as fd: + buf = fd.read() if hashalg: self.hashalg = hashalg.upper() self.hash = getattr(hashlib, self.hashalg.lower())(buf).hexdigest() @@ -947,8 +946,8 @@ def writeprettyxml(self, filename_or_file=None, indent=" ", newl=os.linesep, if isinstance(filename_or_file, string_types): filename_or_file = open(filename_or_file, "wb") xmlstr = self.toprettyxml(indent, newl, encoding) - filename_or_file.write(xmlstr.encode()) - filename_or_file.close() + with filename_or_file: + filename_or_file.write(xmlstr.encode()) def writexml(self, filename_or_file=None, indent=" ", newl=os.linesep, encoding="UTF-8"): @@ -958,8 +957,8 @@ def writexml(self, filename_or_file=None, indent=" ", newl=os.linesep, if isinstance(filename_or_file, string_types): filename_or_file = open(filename_or_file, "wb") xmlstr = self.toxml(encoding) - filename_or_file.write(xmlstr.encode()) - filename_or_file.close() + with filename_or_file: + filename_or_file.write(xmlstr.encode()) def ManifestFromResFile(filename, names=None, languages=None): diff --git a/PyInstaller/utils/win32/winresource.py b/PyInstaller/utils/win32/winresource.py index fb35481636..7361a07d06 100644 --- a/PyInstaller/utils/win32/winresource.py +++ b/PyInstaller/utils/win32/winresource.py @@ -212,9 +212,8 @@ def UpdateResourcesFromDataFile(dstpath, srcpath, type_, names=None, names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ - src = open(srcpath, "rb") - data = src.read() - src.close() + with open(srcpath, "rb") as src: + data = src.read() UpdateResources(dstpath, data, type_, names, languages) diff --git a/tests/old_suite/runtests.py b/tests/old_suite/runtests.py index 2949fc7d0b..4668580576 100755 --- a/tests/old_suite/runtests.py +++ b/tests/old_suite/runtests.py @@ -197,10 +197,9 @@ def _check_modules(self, test_name): for mod_name in self.MODULES[test_name]: # STDOUT and STDERR are discarded (devnull) to hide # import exceptions. - trash = open(os.devnull) - retcode = compat.exec_python_rc('-c', "import %s" % mod_name, - stdout=trash, stderr=trash) - trash.close() + with open(os.devnull) as trash: + retcode = compat.exec_python_rc('-c', "import %s" % mod_name, + stdout=trash, stderr=trash) if retcode != 0: return mod_name return None diff --git a/tests/unit/test_altgraph/test_dot.py b/tests/unit/test_altgraph/test_dot.py index 83993dad54..53292a335e 100644 --- a/tests/unit/test_altgraph/test_dot.py +++ b/tests/unit/test_altgraph/test_dot.py @@ -271,10 +271,8 @@ def test_save(self): try: dot.save_dot(fn) - fp = open(fn, 'r') - data = fp.read() - fp.close() - self.assertEqual(data, ''.join(dot)) + with open(fn, 'r') as fp: + self.assertEqual(fp.read(), ''.join(dot)) finally: if os.path.exists(fn): diff --git a/tests/unit/test_modulegraph/test_zipio.py b/tests/unit/test_modulegraph/test_zipio.py index 812e854e42..7b7c66415f 100644 --- a/tests/unit/test_modulegraph/test_zipio.py +++ b/tests/unit/test_modulegraph/test_zipio.py @@ -36,27 +36,23 @@ def test_locating(self): def test_open(self): # 1. Regular file - fp = zipio.open(os.path.join(TESTDATA, 'test.txt'), 'r') - data = fp.read() - fp.close() + with zipio.open(os.path.join(TESTDATA, 'test.txt'), 'r') as fp: + data = fp.read() self.assertEqual(data, 'This is test.txt\n') if sys.version_info[0] == 3: - fp = zipio.open(os.path.join(TESTDATA, 'test.txt'), 'rb') - data = fp.read() - fp.close() + with zipio.open(os.path.join(TESTDATA, 'test.txt'), 'rb') as fp: + data = fp.read() self.assertEqual(data, b'This is test.txt\n') # 2. File inside zipfile - fp = zipio.open(os.path.join(TESTDATA, 'zipped.egg', 'test.txt'), 'r') - data = fp.read() - fp.close() + with zipio.open(os.path.join(TESTDATA, 'zipped.egg', 'test.txt'), 'r') as fp: + data = fp.read() self.assertEqual(data, 'Zipped up test.txt\n') if sys.version_info[0] == 3: - fp = zipio.open(os.path.join(TESTDATA, 'zipped.egg', 'test.txt'), 'rb') - data = fp.read() - fp.close() + with zipio.open(os.path.join(TESTDATA, 'zipped.egg', 'test.txt'), 'rb') as fp: + data = fp.read() self.assertEqual(data, b'Zipped up test.txt\n') # 3. EXC: Directory inside zipfile