From 426258b7b7a20edaf65bc7d3f777efe5befae266 Mon Sep 17 00:00:00 2001 From: "Per A. Brodtkorb" Date: Tue, 24 Mar 2020 14:58:24 +0100 Subject: [PATCH] Adding missing close for open and replaced "fid=open(filename) fid.close()" statements with the safer "with open(filename) as fid:" blocks. Also removed unnecessary "try: ... finally: pass" statements and refactored code from img2py function into _write_image and _replace_non_alphanumeric_with_underscore Fixes #1574 --- demo/Main.py | 59 +++----- demo/TablePrint.py | 8 +- docs/sphinx/_downloads/Notebook.1.py | 5 +- .../snippets/python/contrib/Notebook.1.py | 5 +- etgtools/extractors.py | 9 +- etgtools/pi_generator.py | 10 +- etgtools/sphinx_generator.py | 37 +++-- wscript | 26 ++-- wx/lib/agw/thumbnailctrl.py | 18 +-- wx/lib/pdfviewer/viewer.py | 4 +- wx/lib/pubsub/core/topicdefnprovider.py | 5 +- wx/py/crustslices.py | 17 +-- wx/py/document.py | 11 +- wx/py/shell.py | 9 +- wx/py/sliceshell.py | 38 ++--- wx/tools/img2py.py | 139 ++++++++---------- 16 files changed, 169 insertions(+), 231 deletions(-) diff --git a/demo/Main.py b/demo/Main.py index 8117efff..81d234dc 100644 --- a/demo/Main.py +++ b/demo/Main.py @@ -346,8 +346,8 @@ def FindImages(text, widgetName): if "src=" in items: possibleImage = items.replace("src=", "").strip() possibleImage = possibleImage.replace('"', "") - f = urllib.request.urlopen(_trunkURL + possibleImage) - stream = f.read() + with urllib.request.urlopen(_trunkURL + possibleImage) as f: + stream = f.read() elif "alt=" in items: plat = items.replace("alt=", "").replace("'", "").strip() path = os.path.join(imagesDir, plat, widgetName + ".png") @@ -417,12 +417,11 @@ class InternetThread(Thread): try: url = _docsURL % ReplaceCapitals(self.selectedClass) - fid = urllib.request.urlopen(url) - - if six.PY2: - originalText = fid.read() - else: - originalText = fid.read().decode("utf-8") + with urllib.request.urlopen(url) as fid: + if six.PY2: + originalText = fid.read() + else: + originalText = fid.read().decode("utf-8") text = RemoveHTMLTags(originalText).split("\n") data = FindWindowStyles(text, originalText, self.selectedClass) @@ -833,12 +832,9 @@ class DemoCodePanel(wx.Panel): wx.LogMessage("Created directory for modified demos: %s" % GetModifiedDirectory()) # Save - f = open(modifiedFilename, "wt") source = self.editor.GetText() - try: + with open(modifiedFilename, "wt") as f: f.write(source) - finally: - f.close() busy = wx.BusyInfo("Reloading demo module...") self.demoModules.LoadFromFile(modModified, modifiedFilename) @@ -964,9 +960,8 @@ def GetDocImagesDir(): def SearchDemo(name, keyword): """ Returns whether a demo contains the search keyword or not. """ - fid = open(GetOriginalFilename(name), "rt") - fullText = fid.read() - fid.close() + with open(GetOriginalFilename(name), "rt") as fid: + fullText = fid.read() if six.PY2: fullText = fullText.decode("iso-8859-1") @@ -1097,16 +1092,13 @@ class DemoModules(object): def LoadFromFile(self, modID, filename): self.modules[modID][2] = filename - file = open(filename, "rt") - self.LoadFromSource(modID, file.read()) - file.close() - + with open(filename, "rt") as file_: + self.LoadFromSource(modID, file_.read()) def LoadFromSource(self, modID, source): self.modules[modID][1] = source self.LoadDict(modID) - def LoadDict(self, modID): if self.name != __name__: source = self.modules[modID][1] @@ -1173,13 +1165,8 @@ class DemoModules(object): source = self.modules[modID][1] filename = self.modules[modID][2] - - try: - file = open(filename, "wt") - file.write(source) - finally: - file.close() - + with open(filename, "wt") as file_: + file_.write(source) def Delete(self, modID): if self.modActive == modID: @@ -1673,14 +1660,11 @@ class wxPythonDemo(wx.Frame): self.pickledData = {} return - fid = open(pickledFile, "rb") - try: - self.pickledData = cPickle.load(fid) - except: - self.pickledData = {} - - fid.close() - + with open(pickledFile, "rb") as fid: + try: + self.pickledData = cPickle.load(fid) + except: + self.pickledData = {} def BuildMenuBar(self): @@ -2531,9 +2515,8 @@ class wxPythonDemo(wx.Frame): MakeDocDirs() pickledFile = GetDocFile() - fid = open(pickledFile, "wb") - cPickle.dump(self.pickledData, fid, cPickle.HIGHEST_PROTOCOL) - fid.close() + with open(pickledFile, "wb") as fid: + cPickle.dump(self.pickledData, fid, cPickle.HIGHEST_PROTOCOL) self.Destroy() diff --git a/demo/TablePrint.py b/demo/TablePrint.py index a1436dbe..e6b2931c 100644 --- a/demo/TablePrint.py +++ b/demo/TablePrint.py @@ -150,12 +150,8 @@ class TablePanel(wx.Panel): def PreviewText(self): prt = printout.PrintTable(self.frame) prt.SetHeader("PROCLAMATION") - file = open('data/proclamation.txt') - data = [] - for txt in file: - data.append(txt.strip()) - file.close() - prt.data = data + with open('data/proclamation.txt') as file_: + prt.data = [txt.strip() for txt in file_] prt.Preview() def PrintWide(self): diff --git a/docs/sphinx/_downloads/Notebook.1.py b/docs/sphinx/_downloads/Notebook.1.py index 2c96a0c6..dc37b7a6 100644 --- a/docs/sphinx/_downloads/Notebook.1.py +++ b/docs/sphinx/_downloads/Notebook.1.py @@ -53,9 +53,8 @@ class NotebookFrame(wx.Frame): path = dlg.GetPath() # Open the file as read-only and slurp its content - fid = open(path, 'rt') - text = fid.read() - fid.close() + with open(path, 'rt') as fid: + text = fid.read() # Create the notebook page as a wx.TextCtrl and # add it as a page of the wx.Notebook diff --git a/docs/sphinx/rest_substitutions/snippets/python/contrib/Notebook.1.py b/docs/sphinx/rest_substitutions/snippets/python/contrib/Notebook.1.py index 2c96a0c6..dc37b7a6 100644 --- a/docs/sphinx/rest_substitutions/snippets/python/contrib/Notebook.1.py +++ b/docs/sphinx/rest_substitutions/snippets/python/contrib/Notebook.1.py @@ -53,9 +53,8 @@ class NotebookFrame(wx.Frame): path = dlg.GetPath() # Open the file as read-only and slurp its content - fid = open(path, 'rt') - text = fid.read() - fid.close() + with open(path, 'rt') as fid: + text = fid.read() # Create the notebook page as a wx.TextCtrl and # add it as a page of the wx.Notebook diff --git a/etgtools/extractors.py b/etgtools/extractors.py index 78b4a661..c0a3eced 100644 --- a/etgtools/extractors.py +++ b/etgtools/extractors.py @@ -816,7 +816,8 @@ class ClassDef(BaseDef): def includeCppCode(self, filename): - self.addCppCode(textfile_open(filename).read()) + with textfile_open(filename) as fid: + self.addCppCode(fid.read()) def addAutoProperties(self): @@ -1470,7 +1471,8 @@ class ModuleDef(BaseDef): self.cppCode.append(code) def includeCppCode(self, filename): - self.addCppCode(textfile_open(filename).read()) + with textfile_open(filename) as fid: + self.addCppCode(fid.read()) def addInitializerCode(self, code): if isinstance(code, list): @@ -1616,7 +1618,8 @@ class ModuleDef(BaseDef): """ Add a snippet of Python code from a file to the wrapper module. """ - text = textfile_open(filename).read() + with textfile_open(filename) as fid: + text = fid.read() return self.addPyCode( "#" + '-=' * 38 + '\n' + ("# This code block was included from %s\n%s\n" % (filename, text)) + diff --git a/etgtools/pi_generator.py b/etgtools/pi_generator.py index eb7c6207..419a405c 100644 --- a/etgtools/pi_generator.py +++ b/etgtools/pi_generator.py @@ -130,7 +130,8 @@ class PiWrapperGenerator(generators.WrapperGeneratorBase, FixWxPrefix): sectionBeginMarker = '#-- begin-%s --#' % sectionName sectionEndMarker = '#-- end-%s --#' % sectionName - lines = textfile_open(destFile, 'rt').readlines() + with textfile_open(destFile, 'rt') as fid: + lines = fid.readlines() for idx, line in enumerate(lines): if line.startswith(sectionBeginMarker): sectionBeginLine = idx @@ -146,11 +147,8 @@ class PiWrapperGenerator(generators.WrapperGeneratorBase, FixWxPrefix): # replace the existing lines lines[sectionBeginLine+1:sectionEndLine] = [sectionText] - f = textfile_open(destFile, 'wt') - f.writelines(lines) - f.close() - - + with textfile_open(destFile, 'wt') as f: + f.writelines(lines) #----------------------------------------------------------------------- def generateModule(self, module, stream): diff --git a/etgtools/sphinx_generator.py b/etgtools/sphinx_generator.py index 51f35fdc..b8757e00 100644 --- a/etgtools/sphinx_generator.py +++ b/etgtools/sphinx_generator.py @@ -651,9 +651,8 @@ class ParameterList(Node): ## class_name = wx2Sphinx(xml_item.className)[1] + '.' ## ## print '\n ||| %s;%s;%s |||\n'%(class_name[0:-1], signature, param) -## fid = open('mismatched.txt', 'a') -## fid.write('%s;%s;%s\n'%(class_name[0:-1], signature, param)) -## fid.close() +## with open('mismatched.txt', 'a') as fid: +## fid.write('%s;%s;%s\n'%(class_name[0:-1], signature, param)) # ----------------------------------------------------------------------- @@ -1446,28 +1445,26 @@ class Snippet(Node): fid.write(new_py_code) else: - fid = open(self.converted_py, 'rt') highlight = None - while 1: - tline = fid.readline() + with open(self.converted_py, 'rt') as fid: + while True: + tline = fid.readline() - if not tline: # end of file - code = "" - fid.close() + if not tline: # end of file + code = "" + break + + if 'code-block::' in tline: + highlight = tline.replace('#', '').strip() + continue + + if not tline.strip(): + continue + + code = tline + fid.read() break - if 'code-block::' in tline: - highlight = tline.replace('#', '').strip() - continue - - if not tline.strip(): - continue - - code = tline + fid.read() - fid.close() - break - if highlight: docstrings += '\n\n%s\n\n'%highlight else: diff --git a/wscript b/wscript index c9474f16..b28b55ed 100644 --- a/wscript +++ b/wscript @@ -555,20 +555,20 @@ def build(bld): updateLicenseFiles(cfg) # create the package's __version__ module - open(opj(cfg.PKGDIR, '__version__.py'), 'w').write( - "# This file was generated by wxPython's wscript.\n\n" - "VERSION_STRING = '%(VERSION)s'\n" - "MAJOR_VERSION = %(VER_MAJOR)s\n" - "MINOR_VERSION = %(VER_MINOR)s\n" - "RELEASE_NUMBER = %(VER_RELEASE)s\n" - "BUILD_TYPE = '%(BUILD_TYPE)s'\n\n" - "VERSION = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '%(VER_FLAGS)s')\n" - % cfg.__dict__) + with open(opj(cfg.PKGDIR, '__version__.py'), 'w') as fid: + fid.write("# This file was generated by wxPython's wscript.\n\n" + "VERSION_STRING = '%(VERSION)s'\n" + "MAJOR_VERSION = %(VER_MAJOR)s\n" + "MINOR_VERSION = %(VER_MINOR)s\n" + "RELEASE_NUMBER = %(VER_RELEASE)s\n" + "BUILD_TYPE = '%(BUILD_TYPE)s'\n\n" + "VERSION = (MAJOR_VERSION, MINOR_VERSION, RELEASE_NUMBER, '%(VER_FLAGS)s')\n" + % cfg.__dict__) # and one for the demo folder too - open('demo/version.py', 'w').write( - "# This file was generated by wxPython's wscript.\n\n" - "VERSION_STRING = '%(VERSION)s'\n" - % cfg.__dict__) + with open('demo/version.py', 'w') as fid: + fid.write("# This file was generated by wxPython's wscript.\n\n" + "VERSION_STRING = '%(VERSION)s'\n" + % cfg.__dict__) # copy the wx locale message catalogs to the package dir diff --git a/wx/lib/agw/thumbnailctrl.py b/wx/lib/agw/thumbnailctrl.py index 65c76631..f31f4102 100644 --- a/wx/lib/agw/thumbnailctrl.py +++ b/wx/lib/agw/thumbnailctrl.py @@ -478,18 +478,18 @@ class PILImageHandler(object): import PIL.Image as Image - pil = Image.open(filename) - originalsize = pil.size + with Image.open(filename) as pil: + originalsize = pil.size - pil.thumbnail(thumbnailsize) - img = wx.Image(pil.size[0], pil.size[1]) + pil.thumbnail(thumbnailsize) + img = wx.Image(pil.size[0], pil.size[1]) - img.SetData(pil.convert("RGB").tobytes()) + img.SetData(pil.convert("RGB").tobytes()) - alpha = False - if "A" in pil.getbands(): - img.SetAlpha(pil.convert("RGBA").tobytes()[3::4]) - alpha = True + alpha = False + if "A" in pil.getbands(): + img.SetAlpha(pil.convert("RGBA").tobytes()[3::4]) + alpha = True return img, originalsize, alpha diff --git a/wx/lib/pdfviewer/viewer.py b/wx/lib/pdfviewer/viewer.py index 9a924c19..86ec7e61 100644 --- a/wx/lib/pdfviewer/viewer.py +++ b/wx/lib/pdfviewer/viewer.py @@ -194,8 +194,8 @@ class pdfViewer(wx.ScrolledWindow): Create and return a file object with the contents of filename, only used for testing. """ - f = open(filename, 'rb') - stream = f.read() + with open(filename, 'rb') as f: + stream = f.read() return BytesIO(stream) self.pdfpathname = '' diff --git a/wx/lib/pubsub/core/topicdefnprovider.py b/wx/lib/pubsub/core/topicdefnprovider.py index 869b83db..a60015a8 100644 --- a/wx/lib/pubsub/core/topicdefnprovider.py +++ b/wx/lib/pubsub/core/topicdefnprovider.py @@ -443,10 +443,7 @@ def exportTopicTreeSpec(moduleName = None, rootTopic=None, bak='bak', moduleDoc= if bak: _backupIfExists(filename, bak) with open(filename, 'w') as moduleFile: - try: - TopicTreeSpecPrinter(rootTopic, fileObj=moduleFile, treeDoc=moduleDoc) - finally: - pass + TopicTreeSpecPrinter(rootTopic, fileObj=moduleFile, treeDoc=moduleDoc) ############################################################## diff --git a/wx/py/crustslices.py b/wx/py/crustslices.py index e51cbbbd..8626d17b 100644 --- a/wx/py/crustslices.py +++ b/wx/py/crustslices.py @@ -318,11 +318,9 @@ class CrustSlicesFrame(crust.CrustFrame): if not self.buffer.confirmed: self.buffer.confirmed = self.buffer.overwriteConfirm(filepath) if self.buffer.confirmed: - try: - with open(filepath, 'wb') as fid: - self.sliceshell.SavePySlicesFile(fid) - finally: - pass + with open(filepath, 'wb') as fid: + self.sliceshell.SavePySlicesFile(fid) + self.sliceshell.SetSavePoint() self.SetTitle( os.path.split(filepath)[1] + ' - PySlices') self.sliceshell.NeedsCheckForSave=False @@ -374,12 +372,9 @@ class CrustSlicesFrame(crust.CrustFrame): result.path+=".pyslices" # if not os.path.exists(result.path): - try: # Allow overwrite... - with open(result.path, 'wb') as fid: - self.sliceshell.SavePySlicesFile(fid) - finally: - pass - + # Allow overwrite... + with open(result.path, 'wb') as fid: + self.sliceshell.SavePySlicesFile(fid) cancel = False else: cancel = True diff --git a/wx/py/document.py b/wx/py/document.py index 8d15097b..bf6380c6 100644 --- a/wx/py/document.py +++ b/wx/py/document.py @@ -24,18 +24,13 @@ class Document: """Return contents of file.""" if self.filepath and os.path.exists(self.filepath): with open(self.filepath, 'rb') as f: - try: - return f.read().decode('utf-8') - finally: - pass - else: - return '' + return f.read().decode('utf-8') + return '' def write(self, text): """Write text to file.""" with open(self.filepath, 'wb') as f: - try: - # Convert from unicode to bytes + try: # Convert from unicode to bytes text = text.encode('utf-8') f.write(text) except AttributeError: diff --git a/wx/py/shell.py b/wx/py/shell.py index 074fb16e..e94caedf 100755 --- a/wx/py/shell.py +++ b/wx/py/shell.py @@ -1162,17 +1162,14 @@ class Shell(editwindow.EditWindow): def runfile(self, filename): """Execute all commands in file as if they were typed into the shell.""" - file = open(filename) - try: - self.prompt() - for command in file.readlines(): + self.prompt() + with open(filename) as file_: + for command in file_: if command[:6] == 'shell.': # Run shell methods silently. self.run(command, prompt=False, verbose=False) else: self.run(command, prompt=False, verbose=True) - finally: - file.close() def autoCompleteShow(self, command, offset = 0): """Display auto-completion popup list.""" diff --git a/wx/py/sliceshell.py b/wx/py/sliceshell.py index 05418179..5fe49c3a 100755 --- a/wx/py/sliceshell.py +++ b/wx/py/sliceshell.py @@ -354,9 +354,9 @@ class SlicesShellFrame(frame.Frame, frame.ShellFrameMixin): 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 @@ -386,12 +386,9 @@ class SlicesShellFrame(frame.Frame, frame.ShellFrameMixin): if not self.buffer.confirmed: self.buffer.confirmed = self.buffer.overwriteConfirm(filepath) if self.buffer.confirmed: - try: - fid = open(filepath, 'wb') + with open(filepath, 'wb') as fid: self.sliceshell.SavePySlicesFile(fid) - finally: - if fid: - fid.close() + self.sliceshell.SetSavePoint() self.SetTitle( os.path.split(filepath)[1] + ' - PySlices') self.sliceshell.NeedsCheckForSave=False @@ -443,12 +440,9 @@ class SlicesShellFrame(frame.Frame, frame.ShellFrameMixin): result.path+=".pyslices" # if not os.path.exists(result.path): - try: # Allow overwrite... - fid = open(result.path, 'wb') + # Allow overwrite... + with open(result.path, 'wb') as fid: self.sliceshell.SavePySlicesFile(fid) - finally: - if fid: - fid.close() cancel = False else: @@ -1942,11 +1936,10 @@ class SlicesShell(editwindow.EditWindow): #Open and Save now work when using CrustSlicesFrames elif controlDown and key in (ord('L'), ord('l')): #print('Load it') - file=wx.FileSelector("Load File As New Slice") - if file!=u'': - fid=open(file,'r') - self.LoadPyFileAsSlice(fid) - fid.close() + file = wx.FileSelector("Load File As New Slice") + if file != u'': + with open(file,'r') as fid: + self.LoadPyFileAsSlice(fid) elif controlDown and key in (ord('D'), ord('d')): #Disallow line duplication in favor of divide slices @@ -3068,17 +3061,14 @@ class SlicesShell(editwindow.EditWindow): # TODO : Will have to fix this to handle other kinds of errors mentioned before... def runfile(self, filename): """Execute all commands in file as if they were typed into the shell.""" - file = open(filename) - try: - self.prompt() - for command in file.readlines(): + self.prompt() + with open(filename) as file_: + for command in file_: if command[:6] == 'shell.': # Run shell methods silently. self.run(command, prompt=False, verbose=False) else: self.run(command, prompt=False, verbose=True) - finally: - file.close() def autoCompleteShow(self, command, offset = 0): """Display auto-completion popup list.""" diff --git a/wx/tools/img2py.py b/wx/tools/img2py.py index 0b68a9a0..7e363e32 100644 --- a/wx/tools/img2py.py +++ b/wx/tools/img2py.py @@ -126,6 +126,41 @@ def convert(fileName, maskClr, outputDir, outputName, outType, outExt): return img2img.convert(fileName, maskClr, outputDir, outputName, outType, outExt) +def _replace_non_alphanumeric_with_underscore(imgName): + letters = [letter if letter.isalnum() else '_' for letter in imgName] + + if not letters[0].isalpha() and letters[0] != '_': + letters.insert(0, "_") + varName = "".join(letters) + return varName + + +def _write_image(out, imgName, data, append, icon, catalog, functionCompatible, old_index): + out.write("#" + "-" * 70 + "\n") + if not append: + out.write("# This file was generated by %s\n#\n" % sys.argv[0]) + out.write("from wx.lib.embeddedimage import PyEmbeddedImage\n\n") + if catalog: + out.write("catalog = {}\n") + out.write("index = []\n\n") + varName = _replace_non_alphanumeric_with_underscore(imgName) + out.write("%s = PyEmbeddedImage(\n%s\n" % (varName, data)) + if catalog: + if imgName in old_index: + print("Warning: %s already in catalog." % imgName) + print(" Only the last entry will be accessible.\n") + old_index.append(imgName) + out.write("index.append('%s')\n" % imgName) + out.write("catalog['%s'] = %s\n" % (imgName, varName)) + if functionCompatible: + out.write("get%sData = %s.GetData\n" % (varName, varName)) + out.write("get%sImage = %s.GetImage\n" % (varName, varName)) + out.write("get%sBitmap = %s.GetBitmap\n" % (varName, varName)) + if icon: + out.write("get%sIcon = %s.GetIcon\n" % (varName, varName)) + out.write("\n") + + def img2py(image_file, python_file, append=DEFAULT_APPEND, compressed=DEFAULT_COMPRESSED, @@ -186,91 +221,44 @@ def img2py(image_file, python_file, append_catalog = True 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: - pass + for line in sourcePy: + if line == "catalog = {}\n": + append_catalog = False + else: + lineMatcher = indexPattern.match(line) + if lineMatcher: + old_index.append(lineMatcher.groups()[0]) if append_catalog: 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 + out.write("\n# ***************** Catalog starts here *******************") + out.write("\n\ncatalog = {}\n") + out.write("index = []\n\n") + + if not imgName: + imgPath, imgFile = os.path.split(image_file) + imgName = os.path.splitext(imgFile)[0] + print("\nWarning: -n not specified. Using filename (%s) for name of image and/or catalog entry." % imgName) if python_file == '-': out = sys.stdout - elif append: - out = open(python_file, "a") + _write_image(out, imgName, data, append, icon, catalog, functionCompatible, old_index) else: - out = open(python_file, "w") + mode = "a" if append else "w" + with open(python_file, mode) as out: + _write_image(out, imgName, data, append, icon, catalog, functionCompatible, old_index) - try: - imgPath, imgFile = os.path.split(image_file) - if not imgName: - imgName = os.path.splitext(imgFile)[0] - print("\nWarning: -n not specified. Using filename (%s) for name of image and/or catalog entry." % imgName) + if imgName: + n_msg = ' using "%s"' % imgName + else: + n_msg = "" - out.write("#" + "-" * 70 + "\n") - if not append: - out.write("# This file was generated by %s\n#\n" % sys.argv[0]) - out.write("from wx.lib.embeddedimage import PyEmbeddedImage\n\n") - if catalog: - out.write("catalog = {}\n") - out.write("index = []\n\n") - - letters = [] - for letter in imgName: - if not letter.isalnum(): - letter = "_" - letters.append(letter) - if not letters[0].isalpha() and letters[0] != '_': - letters.insert(0, "_") - varName = "".join(letters) - - out.write("%s = PyEmbeddedImage(\n%s\n" % (varName, data)) - - if catalog: - if imgName in old_index: - print("Warning: %s already in catalog." % imgName) - print(" Only the last entry will be accessible.\n") - old_index.append(imgName) - out.write("index.append('%s')\n" % imgName) - out.write("catalog['%s'] = %s\n" % (imgName, varName)) - - if functionCompatible: - out.write("get%sData = %s.GetData\n" % (varName, varName)) - out.write("get%sImage = %s.GetImage\n" % (varName, varName)) - out.write("get%sBitmap = %s.GetBitmap\n" % (varName, varName)) - if icon: - out.write("get%sIcon = %s.GetIcon\n" % (varName, varName)) - - out.write("\n") - - if imgName: - n_msg = ' using "%s"' % imgName - else: - n_msg = "" - - if maskClr: - m_msg = " with mask %s" % maskClr - else: - m_msg = "" - - print("Embedded %s%s into %s%s" % (image_file, n_msg, python_file, m_msg)) - finally: - if python_file != '-': - out.close() + if maskClr: + m_msg = " with mask %s" % maskClr + else: + m_msg = "" + print("Embedded %s%s into %s%s" % (image_file, n_msg, python_file, m_msg)) def main(args=None): @@ -319,5 +307,6 @@ def main(args=None): img2py(image_file, python_file, append, compressed, maskClr, imgName, icon, catalog, compatible) + if __name__ == "__main__": main(sys.argv[1:])