Skip to content

Commit

Permalink
Fixes issue 1571:
Browse files Browse the repository at this point in the history
Adding missing close for open.
If the "close()" call is missing after a "open(filename)" call, the filename isn't guaranteed to be closed before the interpreter exits.
This is generally a bad practice as explained here: https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important

Also replaced "fid=open(filename) fid.close()" statements for files with the safer
"with open(filename) as fid:" blocks. See https://www.python.org/dev/peps/pep-0343/
  • Loading branch information
pbrod committed Mar 23, 2020
1 parent 8e2627e commit e4e8bf8
Show file tree
Hide file tree
Showing 38 changed files with 234 additions and 270 deletions.
7 changes: 2 additions & 5 deletions bin/make-new-etg-file.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,10 @@ def writeFile(filename, stub, values):
if os.path.exists(filename):
print("'%s' already exists. Exiting." % filename)
sys.exit(1)
output = open(filename, 'w')
output.write(stub % values)
output.close()
with open(filename, 'w') as output:
output.write(stub % values)
print("Wrote %s" % filename)




if __name__ == '__main__':
main()
6 changes: 3 additions & 3 deletions bin/make-new-unittest-file.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ def writeFile(filename, stub, values):
if os.path.exists(filename):
print("'%s' already exists. Exiting." % filename)
sys.exit(1)
output = open(filename, 'w')
output.write(stub % values)
output.close()
with open(filename, 'w') as output:
output.write(stub % values)

print("Wrote %s" % filename)


Expand Down
3 changes: 2 additions & 1 deletion bin/mymd5.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ def main():
for arg in sys.argv[1:]:
for name in glob.glob(arg):
m = hashlib.md5()
m.update(open(name, 'rb').read())
with open(name, 'rb') as fid:
m.update(fid.read())
print('%-45s %s' % (name, m.hexdigest()))


Expand Down
85 changes: 41 additions & 44 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,8 @@ def _error_msg(txt):
# now check the MD5 if not in dev mode and it's set to None
if not (devMode and md5 is None):
m = hashlib.md5()
m.update(open(cmd, 'rb').read())
with open(cmd, 'rb') as fid:
m.update(fid.read())
if m.hexdigest() != md5:
_error_msg('MD5 mismatch, got "%s"\n '
'expected "%s"' % (m.hexdigest(), md5))
Expand Down Expand Up @@ -1019,9 +1020,8 @@ def cmd_docset_py(options, args):
tarfilename = "dist/{}.tar.gz".format(rootname)
if os.path.exists(tarfilename):
os.remove(tarfilename)
tarball = tarfile.open(name=tarfilename, mode="w:gz")
tarball.add(opj('dist', name+'.docset'), name+'.docset', filter=_setTarItemPerms)
tarball.close()
with tarfile.open(name=tarfilename, mode="w:gz") as tarball:
tarball.add(opj('dist', name+'.docset'), name+'.docset', filter=_setTarItemPerms)

if options.upload:
uploadPackage(tarfilename, options)
Expand Down Expand Up @@ -1303,9 +1303,8 @@ def injectClassInfo(className, srcTxt):
if not os.path.exists(dest):
msg('%s is a new file, copying...' % os.path.basename(src))
srcTxt = processSrc(src, options.keep_hash_lines)
f = textfile_open(dest, 'wt')
f.write(srcTxt)
f.close()
with textfile_open(dest, 'wt') as f:
f.write(srcTxt)
continue

srcTxt = processSrc(src, options.keep_hash_lines)
Expand All @@ -1316,15 +1315,13 @@ def injectClassInfo(className, srcTxt):
pass
else:
msg('%s is changed, copying...' % os.path.basename(src))
f = textfile_open(dest, 'wt')
f.write(srcTxt)
f.close()
with textfile_open(dest, 'wt') as f:
f.write(srcTxt)

# Remove tmpdir and its contents
shutil.rmtree(tmpdir)



def cmd_touch(options, args):
cmdTimer = CommandTimer('touch')
pwd = pushDir(phoenixDir())
Expand Down Expand Up @@ -2018,11 +2015,12 @@ def _archive_submodules(root, dest):
runcmd('git archive HEAD | tar -x -C %s' % dest, echoCmd=False)

if os.path.exists('.gitmodules'):
for line in open('.gitmodules', 'rt').readlines():
line = line.strip()
if line.startswith('path = '):
sub = line[7:]
_archive_submodules(sub, opj(dest, sub))
with open('.gitmodules', 'rt') as fid:
for line in fid:
line = line.strip()
if line.startswith('path = '):
sub = line[7:]
_archive_submodules(sub, opj(dest, sub))

_archive_submodules('.', os.path.abspath(PDEST))

Expand Down Expand Up @@ -2073,11 +2071,11 @@ def _archive_submodules(root, dest):
tarfilename = "dist/%s.tar.gz" % rootname
if os.path.exists(tarfilename):
os.remove(tarfilename)
tarball = tarfile.open(name=tarfilename, mode="w:gz")
pwd = pushDir(PDEST)
for name in glob.glob('*'):
tarball.add(name, os.path.join(rootname, name), filter=_setTarItemPerms)
tarball.close()
with tarfile.open(name=tarfilename, mode="w:gz") as tarball:
for name in glob.glob('*'):
tarball.add(name, os.path.join(rootname, name), filter=_setTarItemPerms)

msg('Cleaning up...')
del pwd
shutil.rmtree(PDEST)
Expand Down Expand Up @@ -2125,11 +2123,11 @@ def cmd_sdist_demo(options, args):
tarfilename = "dist/%s.tar.gz" % rootname
if os.path.exists(tarfilename):
os.remove(tarfilename)
tarball = tarfile.open(name=tarfilename, mode="w:gz")
pwd = pushDir(PDEST)
for name in glob.glob('*'):
tarball.add(name, os.path.join(rootname, name), filter=_setTarItemPerms)
tarball.close()
with tarfile.open(name=tarfilename, mode="w:gz") as tarball:
for name in glob.glob('*'):
tarball.add(name, os.path.join(rootname, name), filter=_setTarItemPerms)

msg('Cleaning up...')
del pwd
shutil.rmtree(PDEST)
Expand Down Expand Up @@ -2168,23 +2166,23 @@ def cmd_bdist(options, args):
if os.path.exists(tarfilename):
os.remove(tarfilename)
msg("Archiving Phoenix binaries to %s..." % tarfilename)
tarball = tarfile.open(name=tarfilename, mode="w:gz")
tarball.add('wx', opj(rootname, 'wx'),
filter=lambda info: None if '.svn' in info.name \
or info.name.endswith('.pyc') \
or '__pycache__' in info.name else info)
tarball.add(eggInfoName, opj(rootname, eggInfoName))

if not isDarwin and not isWindows and not options.no_magic and not options.use_syswx:
# If the DLLs are not already in the wx package folder then go fetch
# them now.
msg("Archiving wxWidgets shared libraries...")
dlls = glob.glob(os.path.join(wxlibdir, "*%s" % dllext))
for dll in dlls:
tarball.add(dll, os.path.join(rootname, 'wx', os.path.basename(dll)))
with tarfile.open(name=tarfilename, mode="w:gz") as tarball:
tarball.add('wx', opj(rootname, 'wx'),
filter=lambda info: None if '.svn' in info.name \
or info.name.endswith('.pyc') \
or '__pycache__' in info.name else info)
tarball.add(eggInfoName, opj(rootname, eggInfoName))

if not isDarwin and not isWindows and not options.no_magic and not options.use_syswx:
# If the DLLs are not already in the wx package folder then go fetch
# them now.
msg("Archiving wxWidgets shared libraries...")
dlls = glob.glob(os.path.join(wxlibdir, "*%s" % dllext))
for dll in dlls:
tarball.add(dll, os.path.join(rootname, 'wx', os.path.basename(dll)))

tarball.add('packaging/README-bdist.txt', os.path.join(rootname, 'README.txt'))

tarball.add('packaging/README-bdist.txt', os.path.join(rootname, 'README.txt'))
tarball.close()

if options.upload:
uploadPackage(tarfilename, options)
Expand All @@ -2207,10 +2205,9 @@ def cmd_setrev(options, args):

else:
svnrev = getVcsRev()
f = open('REV.txt', 'w')
svnrev = '.dev'+svnrev
f.write(svnrev)
f.close()
with open('REV.txt', 'w') as f:
svnrev = '.dev'+svnrev
f.write(svnrev)
msg('REV.txt set to "%s"' % svnrev)

cfg = Config()
Expand Down
9 changes: 4 additions & 5 deletions buildtools/build_wxwidgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ def getWxRelease(wxRoot=None):
if not wxRoot:
global wxRootDir
wxRoot = wxRootDir

configureText = open(os.path.join(wxRoot, "configure.in"), "r").read()
with open(os.path.join(wxRoot, "configure.in"), "r") as fid:
configureText = fid.read()
majorVersion = re.search("wx_major_version_number=(\d+)", configureText).group(1)
minorVersion = re.search("wx_minor_version_number=(\d+)", configureText).group(1)

Expand Down Expand Up @@ -592,9 +592,8 @@ def renameLibrary(libname, frameworkname):
for include in glob.glob(header_dir + "/*.h"):
headers += "#include <wx/" + os.path.basename(include) + ">\n"

framework_header = open("%s.h" % fwname, "w")
framework_header.write(header_template % headers)
framework_header.close()
with open("%s.h" % fwname, "w") as framework_header:
framework_header.write(header_template % headers)

run("ln -s -f %s wx" % header_dir)
os.chdir("wx-%s/wx" % version)
Expand Down
24 changes: 11 additions & 13 deletions buildtools/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,10 +349,9 @@ def resetVersion(self):
# then the version number is built without a revision number. IOW, it
# is a release build. (In theory)
if os.path.exists('REV.txt'):
f = open('REV.txt')
self.VER_FLAGS += f.read().strip()
with open('REV.txt') as f:
self.VER_FLAGS += f.read().strip()
self.BUILD_TYPE = 'snapshot'
f.close()
elif os.environ.get('WXPYTHON_RELEASE') == 'yes':
self.BUILD_TYPE = 'release'
else:
Expand Down Expand Up @@ -676,10 +675,11 @@ def _getSbfValue(etg, keyName):
cfg = Config()
sbf = opj(cfg.SIPOUT, etg.NAME + '.sbf')
out = list()
for line in open(sbf):
key, value = line.split('=')
if key.strip() == keyName:
return sorted([opj(cfg.SIPOUT, v) for v in value.strip().split()])
with open(sbf) as fid:
for line in fid:
key, value = line.split('=')
if key.strip() == keyName:
return sorted([opj(cfg.SIPOUT, v) for v in value.strip().split()])
return None

def getEtgSipCppFiles(etg):
Expand Down Expand Up @@ -748,16 +748,14 @@ def writeIfChanged(filename, text):
"""

if os.path.exists(filename):
f = textfile_open(filename, 'rt')
current = f.read()
f.close()
with textfile_open(filename, 'rt') as f:
current = f.read()

if current == text:
return

f = textfile_open(filename, 'wt')
f.write(text)
f.close()
with textfile_open(filename, 'wt') as f:
f.write(text)


# TODO: we might be able to get rid of this when the install code is updated...
Expand Down
9 changes: 6 additions & 3 deletions buildtools/sipdistutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ def _sip_sipfiles_dir(self):

def _sip_calc_signature(self):
sip_bin = self._find_sip()
return sha1(open(sip_bin, "rb").read()).hexdigest()
with open(sip_bin, "rb") as fid:
return sha1(fid.read()).hexdigest()

def _sip_signature_file(self):
return os.path.join(self._sip_output_dir(), "sip.signature")
Expand All @@ -90,7 +91,8 @@ def build_extension (self, ext):
if not os.path.isfile(sigfile):
self.force = True
else:
old_sig = open(sigfile).read()
with open(sigfile) as fid:
old_sig = fid.read()
new_sig = self._sip_calc_signature()
if old_sig != new_sig:
self.force = True
Expand Down Expand Up @@ -136,7 +138,8 @@ def swig_sources (self, sources, extension=None):
sbf = os.path.join(self._sip_output_dir(), replace_suffix(sipbasename, ".sbf"))
if newer_group([sip]+depends, sbf) or self.force:
self._sip_compile(sip_bin, sip, sbf)
open(self._sip_signature_file(), "w").write(self._sip_calc_signature())
with open(self._sip_signature_file(), "w") as f_out:
f_out.write(self._sip_calc_signature())
out = self._get_sip_output_list(sbf)
generated_sources.extend(out)

Expand Down
5 changes: 2 additions & 3 deletions demo/FloatCanvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -1720,9 +1720,8 @@ def Read_MapGen(self, filename, stats = 0,AllLines=0):
shorelines of the whole world, in MapGen format.
"""
file = open(filename,'rt')
data = file.readlines()
data = [s.strip() for s in data]
with open(filename,'rt') as file_:
data = [s.strip() for s in file_]

Shorelines = []
segment = []
Expand Down
3 changes: 2 additions & 1 deletion demo/ImageFromStream.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ class TestPanel(wx.Panel):
def __init__(self, parent, log):
wx.Panel.__init__(self, parent, -1)

data = open(opj('bitmaps/image.png'), "rb").read()
with open(opj('bitmaps/image.png'), "rb") as fid:
data = fid.read()
stream = BytesIO(data)

bmp = wx.Bitmap(wx.Image(stream))
Expand Down
1 change: 1 addition & 0 deletions demo/Main.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,7 @@ def run(self):
originalText = fid.read()
else:
originalText = fid.read().decode("utf-8")

text = RemoveHTMLTags(originalText).split("\n")
data = FindWindowStyles(text, originalText, self.selectedClass)

Expand Down
5 changes: 2 additions & 3 deletions demo/ScrolledMessageDialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ def __init__(self, parent, log):


def OnButton(self, evt):
f = open("Main.py", "r")
msg = f.read()
f.close()
with open("Main.py", "r") as f:
msg = f.read()

dlg = wx.lib.dialogs.ScrolledMessageDialog(self, msg, "message test")
dlg.ShowModal()
Expand Down
3 changes: 2 additions & 1 deletion demo/Sound.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ def OnButton2(self, evt):
sound = wx.adv.Sound(opj('data/plan.wav'))
else:
# sounds can also be loaded from a buffer object
data = open(opj('data/plan.wav'), 'rb').read()
with open(opj('data/plan.wav'), 'rb') as fid:
data = fid.read()
sound = wx.SoundFromData(data)

self.log.write("before Play...\n")
Expand Down
4 changes: 2 additions & 2 deletions demo/StyledTextCtrl_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,8 +371,8 @@ def runTest(frame, nb, log):
p.SetSizer(s)
p.SetAutoLayout(True)


ed.SetText(demoText + open('Main.py').read())
with open('Main.py') as fid:
ed.SetText(demoText + fid.read())
ed.EmptyUndoBuffer()
ed.Colourise(0, -1)

Expand Down
21 changes: 9 additions & 12 deletions demo/TablePrint.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,16 @@ def OnButton(self, evt):

def ReadData(self):
test_file = "./data/testtable.txt"
file = open(test_file,'r',1)
i = 0

data = []
while 1:
text = file.readline()
text = text.strip()
if not text:
break

list_val = text.split('\t')
data.append(list_val)
file.close()
with open(test_file,'r', 1) as file_:
data = []
for text in file_:
text = text.strip()
if not text:
break

list_val = text.split('\t')
data.append(list_val)

self.header = data[0]
self.data = data[1:]
Expand Down
Loading

0 comments on commit e4e8bf8

Please sign in to comment.