diff --git a/bin/make-new-etg-file.py b/bin/make-new-etg-file.py index 41d2db95..4e0428d2 100755 --- a/bin/make-new-etg-file.py +++ b/bin/make-new-etg-file.py @@ -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() diff --git a/bin/make-new-unittest-file.py b/bin/make-new-unittest-file.py index 509d3934..1c366103 100755 --- a/bin/make-new-unittest-file.py +++ b/bin/make-new-unittest-file.py @@ -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) diff --git a/bin/mymd5.py b/bin/mymd5.py index f67adc3c..a91cc953 100644 --- a/bin/mymd5.py +++ b/bin/mymd5.py @@ -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())) diff --git a/build.py b/build.py index 86b68f71..26ade93f 100755 --- a/build.py +++ b/build.py @@ -576,7 +576,8 @@ def getTool(cmdName, version, MD5, envVar, platformBinary, linuxBits=False): # 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)) @@ -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) @@ -1303,9 +1303,8 @@ def cmd_sip(options, args): 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) @@ -1316,15 +1315,13 @@ def cmd_sip(options, args): 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()) @@ -2020,11 +2017,12 @@ def cmd_sdist(options, args): 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)) @@ -2075,11 +2073,11 @@ def cmd_sdist(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) @@ -2127,11 +2125,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) @@ -2170,23 +2168,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)) + 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))) + 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) @@ -2209,10 +2207,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() diff --git a/buildtools/build_wxwidgets.py b/buildtools/build_wxwidgets.py index 0cc32f77..2a1c2f55 100644 --- a/buildtools/build_wxwidgets.py +++ b/buildtools/build_wxwidgets.py @@ -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) @@ -592,9 +592,8 @@ def main(wxDir, args): for include in glob.glob(header_dir + "/*.h"): headers += "#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) diff --git a/buildtools/config.py b/buildtools/config.py index 009edaa1..c837e5d3 100644 --- a/buildtools/config.py +++ b/buildtools/config.py @@ -349,10 +349,9 @@ class Configuration(object): # 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: @@ -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): @@ -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... diff --git a/buildtools/sipdistutils.py b/buildtools/sipdistutils.py index c1cf9418..37b2bb50 100644 --- a/buildtools/sipdistutils.py +++ b/buildtools/sipdistutils.py @@ -72,7 +72,8 @@ class build_ext (build_ext_base): 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") @@ -90,7 +91,8 @@ class build_ext (build_ext_base): 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 @@ -136,7 +138,8 @@ class build_ext (build_ext_base): 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) diff --git a/demo/FloatCanvas.py b/demo/FloatCanvas.py index 25be050a..be7e9d30 100644 --- a/demo/FloatCanvas.py +++ b/demo/FloatCanvas.py @@ -1720,9 +1720,8 @@ def BuildDrawFrame(): # this gets called when needed, rather than on import 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 = [] diff --git a/demo/ImageFromStream.py b/demo/ImageFromStream.py index d71c9e4d..f428265e 100644 --- a/demo/ImageFromStream.py +++ b/demo/ImageFromStream.py @@ -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)) diff --git a/demo/Main.py b/demo/Main.py index e766c932..8117efff 100644 --- a/demo/Main.py +++ b/demo/Main.py @@ -423,6 +423,7 @@ class InternetThread(Thread): originalText = fid.read() else: originalText = fid.read().decode("utf-8") + text = RemoveHTMLTags(originalText).split("\n") data = FindWindowStyles(text, originalText, self.selectedClass) diff --git a/demo/ScrolledMessageDialog.py b/demo/ScrolledMessageDialog.py index 42ab0386..f1addfe4 100644 --- a/demo/ScrolledMessageDialog.py +++ b/demo/ScrolledMessageDialog.py @@ -15,9 +15,8 @@ class TestPanel(wx.Panel): 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() diff --git a/demo/Sound.py b/demo/Sound.py index 0d21f29c..1212019a 100644 --- a/demo/Sound.py +++ b/demo/Sound.py @@ -37,7 +37,8 @@ class TestPanel(wx.Panel): 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") diff --git a/demo/StyledTextCtrl_2.py b/demo/StyledTextCtrl_2.py index 6e897f9b..d7e739a0 100644 --- a/demo/StyledTextCtrl_2.py +++ b/demo/StyledTextCtrl_2.py @@ -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) diff --git a/demo/TablePrint.py b/demo/TablePrint.py index de8b45ef..a1436dbe 100644 --- a/demo/TablePrint.py +++ b/demo/TablePrint.py @@ -42,19 +42,16 @@ class TablePanel(wx.Panel): 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 + 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) - file.close() + list_val = text.split('\t') + data.append(list_val) self.header = data[0] self.data = data[1:] diff --git a/demo/agw/RulerCtrl.py b/demo/agw/RulerCtrl.py index 071e6311..afd114f0 100644 --- a/demo/agw/RulerCtrl.py +++ b/demo/agw/RulerCtrl.py @@ -157,12 +157,12 @@ class RulerCtrlDemo(wx.Frame): self.stc = PythonSTC(self.panel, -1) try: - fid = open("RulerCtrl.py", "rt") + with open("RulerCtrl.py", "rt") as fid: + text = fid.read() except: - fid = open("agw/RulerCtrl.py", "rt") + with open("agw/RulerCtrl.py", "rt") as fid: + text = fid.read() - text = fid.read() - fid.close() self.stc.SetValue(text) self.ruler1 = RC.RulerCtrl(self.panel, -1, orient=wx.HORIZONTAL, style=wx.SUNKEN_BORDER) diff --git a/demo/agw/ShortcutEditor.py b/demo/agw/ShortcutEditor.py index df124e3b..64f1d631 100644 --- a/demo/agw/ShortcutEditor.py +++ b/demo/agw/ShortcutEditor.py @@ -387,8 +387,8 @@ def runTest(frame, nb, log): #---------------------------------------------------------------------- - -overview = open(HTML_HELP, 'rt').read() +with open(HTML_HELP, 'rt') as fid: + overview = fid.read() if __name__ == '__main__': diff --git a/etgtools/pi_generator.py b/etgtools/pi_generator.py index 3f09f7c7..eb7c6207 100644 --- a/etgtools/pi_generator.py +++ b/etgtools/pi_generator.py @@ -105,11 +105,10 @@ class PiWrapperGenerator(generators.WrapperGeneratorBase, FixWxPrefix): def _checkAndWriteHeader(destFile, header, docstring): if not os.path.exists(destFile): # create the file and write the header - f = textfile_open(destFile, 'wt') - f.write(header) - if docstring: - f.write('\n"""\n%s"""\n' % docstring) - f.close() + with textfile_open(destFile, 'wt') as f: + f.write(header) + if docstring: + f.write('\n"""\n%s"""\n' % docstring) if not SKIP_PI_FILE: _checkAndWriteHeader(destFile_pi, header_pi, module.docstring) diff --git a/etgtools/sip_generator.py b/etgtools/sip_generator.py index 62a2ad11..f6865c36 100644 --- a/etgtools/sip_generator.py +++ b/etgtools/sip_generator.py @@ -48,10 +48,8 @@ class SipWrapperGenerator(generators.WrapperGeneratorBase): # Write the contents of the stream to the destination file if not destFile: destFile = os.path.join(phoenixRoot, 'sip/gen', module.name + '.sip') - f = textfile_open(destFile, 'wt') - f.write(stream.getvalue()) - f.close() - + with textfile_open(destFile, 'wt') as f: + f.write(stream.getvalue()) #----------------------------------------------------------------------- def generateModule(self, module, stream): diff --git a/etgtools/sphinx_generator.py b/etgtools/sphinx_generator.py index ddc11dac..51f35fdc 100644 --- a/etgtools/sphinx_generator.py +++ b/etgtools/sphinx_generator.py @@ -1416,9 +1416,8 @@ class Snippet(Node): if not os.path.exists(os.path.dirname(self.cpp_file)): os.makedirs(os.path.dirname(self.cpp_file)) - fid = open(self.cpp_file, 'wt') - fid.write(self.snippet) - fid.close() + with open(self.cpp_file, 'wt') as fid: + fid.write(self.snippet) if not os.path.isfile(self.converted_py): @@ -1443,10 +1442,8 @@ class Snippet(Node): for code in py_code.splitlines(): new_py_code += spacer + code + '\n' - fid = open(self.python_file, 'wt') - fid.write(new_py_code) - fid.close() - + with open(self.python_file, 'wt') as fid: + fid.write(new_py_code) else: fid = open(self.converted_py, 'rt') diff --git a/packaging/setup.py b/packaging/setup.py index e23269a1..6df4be60 100644 --- a/packaging/setup.py +++ b/packaging/setup.py @@ -42,8 +42,7 @@ for wc in ['wxWidgets/configure', if sys.version_info < (3,): execfile('setup.py') else: - f = open('setup.py', 'r') - source = f.read() - f.close() + with open('setup.py', 'r') as f: + source = f.read() exec(source) diff --git a/samples/doodle/superdoodle.py b/samples/doodle/superdoodle.py index d6bcad69..0a5a211e 100644 --- a/samples/doodle/superdoodle.py +++ b/samples/doodle/superdoodle.py @@ -76,21 +76,17 @@ class DoodleFrame(wx.Frame): # size events using this sizer. self.SetSizer(box) - def SaveFile(self): if self.filename: data = self.doodle.GetLinesData() - f = open(self.filename, 'wb') - pickle.dump(data, f) - f.close() - + with open(self.filename, 'wb') as f: + pickle.dump(data, f) def ReadFile(self): if self.filename: try: - f = open(self.filename, 'rb') - data = pickle.load(f) - f.close() + with open(self.filename, 'rb') as f: + data = pickle.load(f) self.doodle.SetLinesData(data) except pickle.UnpicklingError: wx.MessageBox("%s is not a doodle file." % self.filename, diff --git a/samples/floatcanvas/Animation.py b/samples/floatcanvas/Animation.py index c046c673..d6f63c3c 100644 --- a/samples/floatcanvas/Animation.py +++ b/samples/floatcanvas/Animation.py @@ -258,9 +258,8 @@ def Read_MapGen(filename,stats = False): """ from numpy import array - 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_.readlines()] Shorelines = [] segment = [] @@ -279,21 +278,11 @@ def Read_MapGen(filename,stats = False): NumPoints = NumPoints + len(segment) AvgPoints = NumPoints / NumSegments print("Number of Segments: ", NumSegments) - print("Average Number of Points per segment: ",AvgPoints) + print("Average Number of Points per segment: ", AvgPoints) return Shorelines -if __name__ == "__main__": +if __name__ == "__main__": app = DemoApp(0) app.MainLoop() - - - - - - - - - - diff --git a/samples/floatcanvas/BNAEditor.py b/samples/floatcanvas/BNAEditor.py index f1826136..fdc73a18 100644 --- a/samples/floatcanvas/BNAEditor.py +++ b/samples/floatcanvas/BNAEditor.py @@ -50,37 +50,36 @@ class BNAData: def Save(self, filename = None): if not filename: filename = self.filename - file = open(filename, 'w') - for i, points in enumerate(self.PointsData): - file.write('"%s","%s", %i\n'%(self.Names[i],self.Types[i],len(points) ) ) - for p in points: - file.write("%.12f,%.12f\n"%(tuple(p))) + with open(filename, 'w') as file: + for i, points in enumerate(self.PointsData): + file.write('"%s","%s", %i\n'%(self.Names[i],self.Types[i],len(points) ) ) + for p in points: + file.write("%.12f,%.12f\n"%(tuple(p))) def Load(self, filename): #print("Loading:", filename) - file = open(filename,'rU') self.Filename = filename self.PointsData = [] self.Names = [] self.Types = [] - while 1: - line = file.readline() - if not line: - break - line = line.strip() - Name, line = line.split('","') - Name = Name[1:] - Type,line = line.split('",') - num_points = int(line) - self.Types.append(Type) - self.Names.append(Name) - polygon = N.zeros((num_points,2),N.float) - for i in range(num_points): - polygon[i,:] = map(float, file.readline().split(',')) - self.PointsData.append(polygon) - file.close() + with open(filename,'rU') as file_: + for line in file_: + if not line: + break + line = line.strip() + Name, line = line.split('","') + Name = Name[1:] + Type,line = line.split('",') + num_points = int(line) + self.Types.append(Type) + self.Names.append(Name) + polygon = N.zeros((num_points,2),N.float) + for i in range(num_points): + polygon[i,:] = map(float, file_.readline().split(',')) + self.PointsData.append(polygon) + return None class DrawFrame(wx.Frame): diff --git a/samples/printing/printing.py b/samples/printing/printing.py index 24eb0e9c..638d5cde 100644 --- a/samples/printing/printing.py +++ b/samples/printing/printing.py @@ -115,7 +115,8 @@ class PrintFrameworkSample(wx.Frame): self.tc.SetFont(wx.Font(FONTSIZE, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)) filename = os.path.join(os.path.dirname(__file__), "sample-text.txt") - self.tc.SetValue(open(filename).read()) + with open(filename) as fid: + self.tc.SetValue(fid.read()) self.tc.Bind(wx.EVT_SET_FOCUS, self.OnClearSelection) wx.CallAfter(self.tc.SetInsertionPoint, 0) diff --git a/setup.py b/setup.py index ef9dedb1..6b78355a 100644 --- a/setup.py +++ b/setup.py @@ -89,9 +89,10 @@ Programming Language :: Python :: Implementation :: CPython Topic :: Software Development :: User Interfaces """ -INSTALL_REQUIRES = [line.strip() - for line in open('requirements/install.txt').readlines() - if not line.startswith('#')] +with open('requirements/install.txt') as fid: + INSTALL_REQUIRES = [line.strip() + for line in fid.readlines() + if not line.startswith('#')] isWindows = sys.platform.startswith('win') isDarwin = sys.platform == "darwin" diff --git a/sphinxtools/inheritance.py b/sphinxtools/inheritance.py index be7c8bdc..7a1793bf 100644 --- a/sphinxtools/inheritance.py +++ b/sphinxtools/inheritance.py @@ -232,9 +232,8 @@ class InheritanceDiagram(object): mapfile = outfn + '.map' if os.path.isfile(outfn) and os.path.isfile(mapfile): - fid = open(mapfile, 'rt') - map = fid.read() - fid.close() + with open(mapfile, 'rt') as fid: + map = fid.read() return os.path.split(outfn)[1], map.replace('\n', ' ') code = self.generate_dot(class_summary) @@ -288,8 +287,7 @@ class InheritanceDiagram(object): if p.returncode != 0: print(('\nERROR: Graphviz `dot` command exited with error:\n[stderr]\n%s\n[stdout]\n%s\n\n' % (stderr, stdout))) - fid = open(mapfile, 'rt') - map = fid.read() - fid.close() + with open(mapfile, 'rt') as fid: + map = fid.read() return os.path.split(outfn)[1], map.replace('\n', ' ') diff --git a/sphinxtools/modulehunter.py b/sphinxtools/modulehunter.py index 4e336248..6224c896 100644 --- a/sphinxtools/modulehunter.py +++ b/sphinxtools/modulehunter.py @@ -621,7 +621,8 @@ def ModuleHunter(init_name, import_name, version): print('Message: %s' % message) module_name = os.path.splitext(getfile(mainmod))[0] + '.py' - contents = open(module_name, 'rt').read() + with open(module_name, 'rt') as fid: + contents = fid.read() constants = CONSTANT_RE.findall(contents) library_class, count = describe_module(mainmod, kind=object_types.LIBRARY, constants=constants) diff --git a/sphinxtools/postprocess.py b/sphinxtools/postprocess.py index 6dc849e8..0c72ab97 100644 --- a/sphinxtools/postprocess.py +++ b/sphinxtools/postprocess.py @@ -122,9 +122,8 @@ def buildEnumsAndMethods(sphinxDir): for input in textfiles: - fid = textfile_open(input, 'rt') - orig_text = text = fid.read() - fid.close() + with textfile_open(input, 'rt') as fid: + orig_text = text = fid.read() for old, new in list(enum_dict.items()): text = text.replace(old, new) @@ -191,9 +190,8 @@ def buildEnumsAndMethods(sphinxDir): text = addSpacesToLinks(text) if text != orig_text: - fid = textfile_open(input, 'wt') - fid.write(text) - fid.close() + with textfile_open(input, 'wt') as fid: + fid.write(text) if not unreferenced_classes: return @@ -208,17 +206,17 @@ def buildEnumsAndMethods(sphinxDir): 'appear.\n\n' - fid = textfile_open(os.path.join(SPHINXROOT, 'unreferenced_classes.inc'), 'wt') - fid.write('\n') - fid.write('='*50 + ' ' + '='*50 + '\n') - fid.write('%-50s %-50s\n'%('Reference', 'File Name(s)')) - fid.write('='*50 + ' ' + '='*50 + '\n') + with textfile_open(os.path.join(SPHINXROOT, 'unreferenced_classes.inc'), 'wt') as fid: + fid.write('\n') + fid.write('='*50 + ' ' + '='*50 + '\n') + fid.write('%-50s %-50s\n'%('Reference', 'File Name(s)')) + fid.write('='*50 + ' ' + '='*50 + '\n') - for key in sorted(unreferenced_classes): - fid.write('%-50s %-50s\n'%(key, ', '.join(unreferenced_classes[key]))) + for key in sorted(unreferenced_classes): + fid.write('%-50s %-50s\n'%(key, ', '.join(unreferenced_classes[key]))) + + fid.write('='*50 + ' ' + '='*50 + '\n') - fid.write('='*50 + ' ' + '='*50 + '\n') - fid.close() print((warn%(len(unreferenced_classes)))) diff --git a/unittests/test_lib_pubsub_provider.py b/unittests/test_lib_pubsub_provider.py index 3e6268c9..aef14beb 100644 --- a/unittests/test_lib_pubsub_provider.py +++ b/unittests/test_lib_pubsub_provider.py @@ -89,9 +89,8 @@ class lib_pubsub_Except(wtc.PubsubTestCase): pass """ - myTopicTree = open('myTopicTree.py', 'w') - myTopicTree.write(dedent(provFile)) - myTopicTree.close() + with open('myTopicTree.py', 'w') as myTopicTree: + myTopicTree.write(dedent(provFile)) self.pub.addTopicDefnProvider('myTopicTree', format=self.pub.TOPIC_TREE_FROM_MODULE) import os diff --git a/wx/lib/agw/thumbnailctrl.py b/wx/lib/agw/thumbnailctrl.py index fa38a760..65c76631 100644 --- a/wx/lib/agw/thumbnailctrl.py +++ b/wx/lib/agw/thumbnailctrl.py @@ -2455,9 +2455,10 @@ class ScrolledThumbnail(wx.ScrolledWindow): if TN_USE_PIL: newangle = thumb.GetRotation()*180/pi + angle fil = opj(thumb.GetFullFileName()) - pil = Image.open(fil).rotate(newangle) - img = wx.Image(pil.size[0], pil.size[1]) - img.SetData(pil.convert('RGB').tobytes()) + with Image.open(fil) as fid: + pil = fid.rotate(newangle) + img = wx.Image(pil.size[0], pil.size[1]) + img.SetData(pil.convert('RGB').tobytes()) thumb.SetRotation(newangle*pi/180) else: img = thumb._threadedimage diff --git a/wx/lib/pubsub/core/topicdefnprovider.py b/wx/lib/pubsub/core/topicdefnprovider.py index a4ae504d..869b83db 100644 --- a/wx/lib/pubsub/core/topicdefnprovider.py +++ b/wx/lib/pubsub/core/topicdefnprovider.py @@ -277,9 +277,8 @@ class TopicDefnDeserialString(ITopicDefnDeserializer): import os, tempfile creationDir = os.getcwd() fileID, path = tempfile.mkstemp('.py', moduleNamePre, dir=creationDir) - stringFile = os.fdopen(fileID, 'w') - stringFile.write( dedent(source) ) - stringFile.close() + with os.fdopen(fileID, 'w') as stringFile: + stringFile.write( dedent(source) ) return path, [creationDir] self.__filename, searchPath = createTmpModule() @@ -443,11 +442,11 @@ def exportTopicTreeSpec(moduleName = None, rootTopic=None, bak='bak', moduleDoc= filename = '%s.py' % moduleName if bak: _backupIfExists(filename, bak) - moduleFile = open(filename, 'w') - try: - TopicTreeSpecPrinter(rootTopic, fileObj=moduleFile, treeDoc=moduleDoc) - finally: - moduleFile.close() + with open(filename, 'w') as moduleFile: + try: + TopicTreeSpecPrinter(rootTopic, fileObj=moduleFile, treeDoc=moduleDoc) + finally: + pass ############################################################## diff --git a/wx/lib/pubsub/utils/xmltopicdefnprovider.py b/wx/lib/pubsub/utils/xmltopicdefnprovider.py index b135e38c..20954cc5 100644 --- a/wx/lib/pubsub/utils/xmltopicdefnprovider.py +++ b/wx/lib/pubsub/utils/xmltopicdefnprovider.py @@ -1,9 +1,9 @@ """ -Contributed by Joshua R English, adapted by Oliver Schoenborn to be -consistent with pubsub API. +Contributed by Joshua R English, adapted by Oliver Schoenborn to be +consistent with pubsub API. -An extension for pubsub (http://pubsub.sourceforge.net) so topic tree -specification can be encoded in XML format rather than pubsub's default +An extension for pubsub (http://pubsub.sourceforge.net) so topic tree +specification can be encoded in XML format rather than pubsub's default Python nested class format. To use: @@ -32,7 +32,7 @@ These topic definitions are loaded through an XmlTopicDefnProvider: pub.addTopicDefnProvider( XmlTopicDefnProvider(xml) ) -The XmlTopicDefnProvider also accepts a filename instead of XML string: +The XmlTopicDefnProvider also accepts a filename instead of XML string: provider = XmlTopicDefnProvider("path/to/XMLfile.xml", TOPIC_TREE_FROM_FILE) pub.addTopicDefnProvider( provider ) @@ -72,7 +72,7 @@ __all__ = [ 'TOPIC_TREE_FROM_FILE' ] - + def _get_elem(elem): """Assume an ETree.Element object or a string representation. Return the ETree.Element object""" @@ -84,7 +84,7 @@ def _get_elem(elem): raise ValueError("Cannot convert to element") return elem - + TOPIC_TREE_FROM_FILE = 'file' @@ -93,12 +93,13 @@ class XmlTopicDefnProvider(ITopicDefnProvider): class XmlParserError(RuntimeError): pass class UnrecognizedSourceFormatError(ValueError): pass - + def __init__(self, xml, format=TOPIC_TREE_FROM_STRING): self._topics = {} self._treeDoc = '' if format == TOPIC_TREE_FROM_FILE: - self._parse_tree(_get_elem(open(xml,mode="r").read())) + with open(xml, mode="r") as fid: + self._parse_tree(_get_elem(fid.read())) elif format == TOPIC_TREE_FROM_STRING: self._parse_tree(_get_elem(xml)) else: @@ -164,7 +165,7 @@ class XmlTopicDefnProvider(ITopicDefnProvider): def getTreeDoc(self): return self._treeDoc - + class XmlVisitor(ITopicTreeVisitor): def __init__(self, elem): self.tree = elem @@ -188,7 +189,7 @@ class XmlVisitor(ITopicTreeVisitor): desc_elem = ET.SubElement(this_elem, 'description') topicDesc = topicObj.getDescription() if topicDesc: - desc_elem.text = ' '.join(topicDesc.split()) + desc_elem.text = ' '.join(topicDesc.split()) else: desc_elem.text = "UNDOCUMENTED" argDescriptions = topicObj.getArgDescriptions() @@ -228,7 +229,7 @@ class XmlVisitor(ITopicTreeVisitor): def _endChildren(self): self.roots.pop() - + ## http://infix.se/2007/02/06/gentlemen-indent-your-xml def indent(elem, level=0): i = "\n" + level*" " diff --git a/wx/lib/softwareupdate.py b/wx/lib/softwareupdate.py index 36cec255..30218231 100644 --- a/wx/lib/softwareupdate.py +++ b/wx/lib/softwareupdate.py @@ -156,9 +156,8 @@ class SoftwareUpdate(object): newest = self._esky.find_update() chLogTxt = '' if newest is not None and self._changelogURL: - req = urlopen(self._changelogURL, timeout=4) - chLogTxt = req.read() - req.close() + with urlopen(self._changelogURL, timeout=4) as req: + chLogTxt = req.read() return (newest, chLogTxt) except URLError: diff --git a/wx/py/crustslices.py b/wx/py/crustslices.py index 7039350e..e51cbbbd 100644 --- a/wx/py/crustslices.py +++ b/wx/py/crustslices.py @@ -287,9 +287,8 @@ class CrustSlicesFrame(crust.CrustFrame): wildcard='*.pyslices', default_path=self.currentDirectory) if file!=None and file!=u'': - fid=open(file,'r') - self.sliceshell.LoadPySlicesFile(fid) - fid.close() + with open(file,'r') as fid: + self.sliceshell.LoadPySlicesFile(fid) self.currentDirectory = os.path.split(file)[0] self.SetTitle( os.path.split(file)[1] + ' - PySlices') self.sliceshell.NeedsCheckForSave=False @@ -320,11 +319,10 @@ class CrustSlicesFrame(crust.CrustFrame): self.buffer.confirmed = self.buffer.overwriteConfirm(filepath) if self.buffer.confirmed: try: - fid = open(filepath, 'wb') - self.sliceshell.SavePySlicesFile(fid) + with open(filepath, 'wb') as fid: + self.sliceshell.SavePySlicesFile(fid) finally: - if fid: - fid.close() + pass self.sliceshell.SetSavePoint() self.SetTitle( os.path.split(filepath)[1] + ' - PySlices') self.sliceshell.NeedsCheckForSave=False @@ -377,11 +375,10 @@ class CrustSlicesFrame(crust.CrustFrame): # if not os.path.exists(result.path): try: # Allow overwrite... - fid = open(result.path, 'wb') - self.sliceshell.SavePySlicesFile(fid) + with open(result.path, 'wb') as fid: + self.sliceshell.SavePySlicesFile(fid) finally: - if fid: - fid.close() + pass cancel = False else: diff --git a/wx/py/document.py b/wx/py/document.py index c706e08d..8d15097b 100644 --- a/wx/py/document.py +++ b/wx/py/document.py @@ -23,24 +23,20 @@ class Document: def read(self): """Return contents of file.""" if self.filepath and os.path.exists(self.filepath): - f = open(self.filepath, 'rb') - try: - return f.read().decode('utf-8') - finally: - f.close() + with open(self.filepath, 'rb') as f: + try: + return f.read().decode('utf-8') + finally: + pass else: return '' def write(self, text): """Write text to file.""" - try: - f = open(self.filepath, 'wb') + with open(self.filepath, 'wb') as f: try: # Convert from unicode to bytes text = text.encode('utf-8') + f.write(text) except AttributeError: pass - f.write(text) - finally: - if f: - f.close() diff --git a/wx/tools/img2py.py b/wx/tools/img2py.py index b2637cc9..0b68a9a0 100644 --- a/wx/tools/img2py.py +++ b/wx/tools/img2py.py @@ -117,7 +117,9 @@ def convert(fileName, maskClr, outputDir, outputName, outType, outExt): else: newname = os.path.join(outputDir, os.path.basename(os.path.splitext(fileName)[0]) + outExt) - open(newname, "wb").write(open(fileName, "rb").read()) + with open(newname, "wb") as f_out: + with open(fileName, "rb") as f_in: + f_out.write(f_in.read()) return 1, "ok" else: @@ -158,7 +160,8 @@ def img2py(image_file, python_file, return lines = [] - data = b64encode(open(tfname, "rb").read()) + with open(tfname, "rb") as fid: + data = b64encode(fid.read()) while data: part = data[:72] data = data[72:] @@ -182,27 +185,27 @@ def img2py(image_file, python_file, append_catalog = True - sourcePy = open(python_file, "r") - try: - for line in sourcePy: + with open(python_file, "r") as sourcePy: + try: + for line in sourcePy: - if line == "catalog = {}\n": - append_catalog = False - else: - lineMatcher = indexPattern.match(line) - if lineMatcher: - old_index.append(lineMatcher.groups()[0]) - finally: - sourcePy.close() + if line == "catalog = {}\n": + append_catalog = False + else: + lineMatcher = indexPattern.match(line) + if lineMatcher: + old_index.append(lineMatcher.groups()[0]) + finally: + pass if append_catalog: - out = open(python_file, "a") - try: - out.write("\n# ***************** Catalog starts here *******************") - out.write("\n\ncatalog = {}\n") - out.write("index = []\n\n") - finally: - out.close() + with open(python_file, "a") as out: + try: + out.write("\n# ***************** Catalog starts here *******************") + out.write("\n\ncatalog = {}\n") + out.write("index = []\n\n") + finally: + pass if python_file == '-': out = sys.stdout diff --git a/wx/tools/pywxrc.py b/wx/tools/pywxrc.py index 79caaf65..489c7ea6 100644 --- a/wx/tools/pywxrc.py +++ b/wx/tools/pywxrc.py @@ -626,12 +626,12 @@ class XmlResourceCompiler: def FileToString(self, filename): outputList = [] - - buffer = open(filename, "rb").read() + with open(filename, "rb") as fid: + buffer = fid.read() fileLen = len(buffer) linelng = 0 - for i in range(len(buffer)): + for i in range(fileLen): s = buffer[i:i+1] c = byte2int(s) if s == b'\n': diff --git a/wx/tools/wxget_docs_demo.py b/wx/tools/wxget_docs_demo.py index e9468918..d1d64123 100644 --- a/wx/tools/wxget_docs_demo.py +++ b/wx/tools/wxget_docs_demo.py @@ -83,8 +83,8 @@ def get_paths_dict(): def unpack_cached(cached, dest_dir): """ Unpack from the cache.""" print('Unpack', cached, 'to', dest_dir) - tf = tarfile.open(cached, "r:*") - tf.extractall(dest_dir) + with tarfile.open(cached, "r:*") as tf: + tf.extractall(dest_dir) dest_dir = os.listdir(dest_dir)[0] return dest_dir