Skip to content

Commit

Permalink
Use the with context manager instead of open/close.
Browse files Browse the repository at this point in the history
  • Loading branch information
BoboTiG authored and htgoebel committed Sep 9, 2018
1 parent 238694d commit 18ef90c
Show file tree
Hide file tree
Showing 13 changed files with 53 additions and 71 deletions.
6 changes: 3 additions & 3 deletions PyInstaller/archive/writers.py
Expand Up @@ -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):
"""
Expand Down
23 changes: 11 additions & 12 deletions PyInstaller/building/makespec.py
Expand Up @@ -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
10 changes: 4 additions & 6 deletions PyInstaller/depend/bindepend.py
Expand Up @@ -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)]
Expand All @@ -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:
Expand Down
13 changes: 6 additions & 7 deletions PyInstaller/depend/dylib.py
Expand Up @@ -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
6 changes: 2 additions & 4 deletions PyInstaller/loader/pyimod03_importers.py
Expand Up @@ -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):
"""
Expand Down
5 changes: 2 additions & 3 deletions PyInstaller/utils/cliutils/grab_version.py
Expand Up @@ -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.")
Expand Down
5 changes: 2 additions & 3 deletions PyInstaller/utils/osx.py
Expand Up @@ -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)
5 changes: 2 additions & 3 deletions PyInstaller/utils/win32/versioninfo.py
Expand Up @@ -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())
Expand Down
13 changes: 6 additions & 7 deletions PyInstaller/utils/win32/winmanifest.py
Expand Up @@ -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()
Expand Down Expand Up @@ -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"):
Expand All @@ -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):
Expand Down
5 changes: 2 additions & 3 deletions PyInstaller/utils/win32/winresource.py
Expand Up @@ -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)


Expand Down
7 changes: 3 additions & 4 deletions tests/old_suite/runtests.py
Expand Up @@ -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
Expand Down
6 changes: 2 additions & 4 deletions tests/unit/test_altgraph/test_dot.py
Expand Up @@ -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):
Expand Down
20 changes: 8 additions & 12 deletions tests/unit/test_modulegraph/test_zipio.py
Expand Up @@ -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
Expand Down

0 comments on commit 18ef90c

Please sign in to comment.