mirror of
https://github.com/wxWidgets/Phoenix.git
synced 2026-03-18 14:40:07 +01:00
Fixes issue 1571:
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/
This commit is contained in:
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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()))
|
||||
|
||||
|
||||
|
||||
83
build.py
83
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())
|
||||
@@ -2018,11 +2015,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))
|
||||
|
||||
@@ -2073,11 +2071,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)
|
||||
@@ -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)
|
||||
@@ -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))
|
||||
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)
|
||||
@@ -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()
|
||||
|
||||
@@ -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 <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)
|
||||
|
||||
@@ -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...
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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 = []
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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:]
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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__':
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
7
setup.py
7
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"
|
||||
|
||||
@@ -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', ' ')
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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))))
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
##############################################################
|
||||
|
||||
|
||||
@@ -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*" "
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -86,8 +86,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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user