code
stringlengths
1
1.72M
language
stringclasses
1 value
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys def hook(mod): if sys.version[0] > '1': for i in range(len(mod.imports)-1, -1, -1): if mod.imports[i][0] == 'strop': del mod.imports[i] return mod
Python
hiddenimports = ["sql_mar"]
Python
hiddenimports = ['sip', 'PyQt4.QtGui', 'PyQt4._qt'] from hooks.hookutils import qt4_phonon_plugins_dir pdir = qt4_phonon_plugins_dir() datas = [ (pdir + "/phonon_backend/*.so", "qt4_plugins/phonon_backend"), (pdir + "/phonon_backend/*.dll", "qt4_plugins/phonon_backend"), (pdir + "/phonon_backend/*.dylib", "qt4_plugins/phonon_backend"), ]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys, string def hook(mod): names = sys.builtin_module_names if 'posix' in names: removes = ['nt', 'ntpath', 'dos', 'dospath', 'os2', 'mac', 'macpath', 'ce', 'riscos', 'riscospath', 'win32api', 'riscosenviron'] elif 'nt' in names: removes = ['dos', 'dospath', 'os2', 'mac', 'macpath', 'ce', 'riscos', 'riscospath', 'riscosenviron',] elif 'os2' in names: removes = ['nt', 'dos', 'dospath', 'mac', 'macpath', 'win32api', 'ce', 'riscos', 'riscospath', 'riscosenviron',] elif 'dos' in names: removes = ['nt', 'ntpath', 'os2', 'mac', 'macpath', 'win32api', 'ce', 'riscos', 'riscospath', 'riscosenviron',] elif 'mac' in names: removes = ['nt', 'ntpath', 'dos', 'dospath', 'os2', 'win32api', 'ce', 'riscos', 'riscospath', 'riscosenviron',] for i in range(len(mod.imports)-1, -1, -1): nm = mod.imports[i][0] pos = string.find(nm, '.') if pos > -1: nm = nm[:pos] if nm in removes : del mod.imports[i] return mod
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # Submited by Seth Remington (ticket#15) # Refined by Marco Bonifazi (via e-mail) hiddenimports = ['gtkglext', 'gdkgl', 'gdkglext', 'gdk', 'gtk.gdk', 'gtk.gtkgl', 'gtk.gtkgl._gtkgl', 'gtkgl', 'pangocairo', 'pango', 'atk', 'gobject', 'gtk.glade', 'cairo', 'gio']
Python
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import glob def hook(mod): global hiddenimports modpath = mod.__path__[0] hiddenimports = [] for fn in glob.glob('%s/commands/*.py' % modpath): fn = os.path.basename(fn) fn = os.path.splitext(fn)[0] hiddenimports.append('django.core.management.commands.' + fn) return mod
Python
hiddenimports = ['sip', 'PyQt4.QtCore', 'PyQt4._qt']
Python
# Copyright (C) 2009, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys def hook(mod): # forbid imports in the port_v2 directory under Python 3 # The code wouldn't import and would crash the build process. if sys.hexversion >= 0x03000000: mod.__path__ = [] return mod
Python
hiddenimports = ['sip', 'PyQt4.QtCore', 'PyQt4.QtGui', 'PyQt4._qt']
Python
# Copyirght (C) 2005, Eugene Prigorodov # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # Courtesy of Eugene Prigorodov <eprigorodov at naumen dot ru> #kinterbasdb hiddenimports = ['k_exceptions', 'services', 'typeconv_naked', 'typeconv_backcompat', 'typeconv_23plus', 'typeconv_datetime_stdlib', 'typeconv_datetime_mx', 'typeconv_datetime_naked', 'typeconv_fixed_fixedpoint', 'typeconv_fixed_stdlib', 'typeconv_text_unicode', 'typeconv_util_isinstance', '_kinterbasdb', '_kiservices']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA def hook(mod): import sys if hasattr(sys, 'version_info'): vers = '%d%d' % (sys.version_info[0], sys.version_info[1]) else: import string toks = string.split(sys.version[:3], '.') vers = '%s%s' % (toks[0], toks[1]) newname = 'PyWinTypes%s' % vers if mod.typ == 'EXTENSION': mod.__name__ = newname else: import win32api h = win32api.LoadLibrary(newname+'.dll') pth = win32api.GetModuleFileName(h) #win32api.FreeLibrary(h) import mf mod = mf.ExtensionModule(newname, pth) return mod
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA #xml.dom.html.HTMLDocument hiddenimports = ['xml.dom.html.HTMLAnchorElement', 'xml.dom.html.HTMLAppletElement', 'xml.dom.html.HTMLAreaElement', 'xml.dom.html.HTMLBaseElement', 'xml.dom.html.HTMLBaseFontElement', 'xml.dom.html.HTMLBodyElement', 'xml.dom.html.HTMLBRElement', 'xml.dom.html.HTMLButtonElement', 'xml.dom.html.HTMLDirectoryElement', 'xml.dom.html.HTMLDivElement', 'xml.dom.html.HTMLDListElement', 'xml.dom.html.HTMLElement', 'xml.dom.html.HTMLFieldSetElement', 'xml.dom.html.HTMLFontElement', 'xml.dom.html.HTMLFormElement', 'xml.dom.html.HTMLFrameElement', 'xml.dom.html.HTMLFrameSetElement', 'xml.dom.html.HTMLHeadElement', 'xml.dom.html.HTMLHeadingElement', 'xml.dom.html.HTMLHRElement', 'xml.dom.html.HTMLHtmlElement', 'xml.dom.html.HTMLIFrameElement', 'xml.dom.html.HTMLImageElement', 'xml.dom.html.HTMLInputElement', 'xml.dom.html.HTMLIsIndexElement', 'xml.dom.html.HTMLLabelElement', 'xml.dom.html.HTMLLegendElement', 'xml.dom.html.HTMLLIElement', 'xml.dom.html.HTMLLinkElement', 'xml.dom.html.HTMLMapElement', 'xml.dom.html.HTMLMenuElement', 'xml.dom.html.HTMLMetaElement', 'xml.dom.html.HTMLModElement', 'xml.dom.html.HTMLObjectElement', 'xml.dom.html.HTMLOListElement', 'xml.dom.html.HTMLOptGroupElement', 'xml.dom.html.HTMLOptionElement', 'xml.dom.html.HTMLParagraphElement', 'xml.dom.html.HTMLParamElement', 'xml.dom.html.HTMLPreElement', 'xml.dom.html.HTMLQuoteElement', 'xml.dom.html.HTMLScriptElement', 'xml.dom.html.HTMLSelectElement', 'xml.dom.html.HTMLStyleElement', 'xml.dom.html.HTMLTableCaptionElement', 'xml.dom.html.HTMLTableCellElement', 'xml.dom.html.HTMLTableColElement', 'xml.dom.html.HTMLTableElement', 'xml.dom.html.HTMLTableRowElement', 'xml.dom.html.HTMLTableSectionElement', 'xml.dom.html.HTMLTextAreaElement', 'xml.dom.html.HTMLTitleElement', 'xml.dom.html.HTMLUListElement', ]
Python
from hooks import hookutils hiddenimports = ["PyQt4.QtCore", "PyQt4.QtGui", "PyQt4.QtSvg"] if hookutils.qwt_numpy_support(): hiddenimports.append("numpy") if hookutils.qwt_numeric_support(): hiddenimports.append("Numeric") if hookutils.qwt_numarray_support(): hiddenimports.append("numarray")
Python
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import glob def hook(mod): global hiddenimports modpath = mod.__path__[0] hiddenimports = [] for fn in glob.glob('%s/backends/*.py' % modpath): fn = os.path.basename(fn) fn = os.path.splitext(fn)[0] hiddenimports.append('django.core.cache.backends.' + fn) return mod
Python
# Contributed by jkp@kirkconsulting.co.uk # This hook checks for the distutils hacks present when using the # virtualenv package. def hook(mod): import distutils if hasattr(distutils, "distutils_path"): import os import marshal mod_path = os.path.join(distutils.distutils_path, "__init__.pyc") parsed_code = marshal.loads(open(mod_path, "rb").read()[8:]) mod.__init__('distutils', mod_path, parsed_code) return mod
Python
hiddenimports = ['default']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA attrs = [('HTML_4_STRICT_INLINE',0), ('HTML_4_TRANSITIONAL_INLINE',0), ('HTML_FORBIDDEN_END',0), ('HTML_OPT_END',0), ('HTML_BOOLEAN_ATTRS',0), ('HTML_CHARACTER_ENTITIES',0), ('HTML_NAME_ALLOWED',0), ('HTML_DTD',0), ('HTMLDOMImplementation',0), ('htmlImplementation',0), ('utf8_to_code',0), ('ConvertChar',0), ('UseHtmlCharEntities',0), ('TranslateHtmlCdata',0), ('SECURE_HTML_ELEMS',0), ]
Python
hiddenimports = ['sip', 'PyQt4._qt', 'PyQt4.QtAssistant', 'PyQt4.QtCore', 'PyQt4.QtGui', 'PyQt4.QtNetwork', 'PyQt4.Qt3Support', 'PyQt4.QtSql', 'PyQt4.QtSvg', 'PyQt4.QtTest', 'PyQt4.QtSql', 'PyQt4.QtXml', 'PyQt4.QtWebKit', 'PyQt4.QtOpenGL', ]
Python
hiddenimports = ['sip', 'PyQt4.QtCore', 'PyQt4.QtGui', 'PyQt4._qt'] from hooks.hookutils import qt4_plugins_dir pdir = qt4_plugins_dir() datas = [ (pdir + "/sqldrivers/*.so", "qt4_plugins/sqldrivers"), (pdir + "/sqldrivers/*.dll", "qt4_plugins/sqldrivers"), (pdir + "/sqldrivers/*.dylib", "qt4_plugins/sqldrivers"), ]
Python
hiddenimports = ['sip', 'PyQt4._qt']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['warnings']
Python
# Copyright (C) 2009, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys def hook(mod): # forbid imports in the port_v3 directory under Python 2 # The code wouldn't import and would crash the build process. if sys.hexversion < 0x03000000: mod.__path__ = [] return mod
Python
hiddenimports = ['sip', 'PyQt4.QtCore', 'PyQt4.QtGui', 'PyQt4._qt']
Python
hiddenimports = ['sip', 'PyQt4.QtCore', 'PyQt4._qt']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['copy_reg']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['encodings']
Python
# email.message imports the old-style naming of two modules: # email.Iterators and email.Generator. Since those modules # don't exist anymore and there are import trick to map them # to the real modules (lowercase), we need to specify them # as hidden imports to make PyInstaller package them. hiddenimports = [ "email.iterators", "email.generator" ]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # courtesy of David C. Morrill (4/2/2002) import os if os.name == 'posix': hiddenimports = ['libvtkCommonPython','libvtkFilteringPython','libvtkIOPython','libvtkImagingPython','libvtkGraphicsPython','libvtkRenderingPython','libvtkHybridPython','libvtkParallelPython','libvtkPatentedPython'] else: hiddenimports = ['vtkCommonPython','vtkFilteringPython','vtkIOPython','vtkImagingPython','vtkGraphicsPython','vtkRenderingPython','vtkHybridPython','vtkParallelPython','vtkPatentedPython']
Python
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # django.core.mail uses part of the email package. # Problem is: when using runserver with autoreload mode, the thread that # checks fore changed files unwillingly trigger further imports within # the email package because of the LazyImporter in email (used in 2.5 for # backward compatibility). # We then need to name those modules as hidden imports, otherwise at # runtime the autoreload thread will complain with a traceback. hiddenimports = [ 'email.mime.message', 'email.mime.image', 'email.mime.text', 'email.mime.multipart', 'email.mime.audio' ]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA attrs = [('__version__', '1.3.0')]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['xmlparse', 'xmltok']
Python
hiddenimports = [ "allcontrols", "asianhotkey", "comboboxdroppedheight", "comparetoreffont", "leadtrailspaces", "miscvalues", "missalignment", "missingextrastring", "overlapping", "repeatedhotkey", "translation", "truncation", ]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA #xml.dom.domreg line 54 hiddenimports = ['xml.dom.minidom','xml.dom.DOMImplementation']
Python
hiddenimports = ['agile', 'dotnet']
Python
hiddenimports = [ '_fontdata_enc_macexpert', '_fontdata_enc_macroman', '_fontdata_enc_pdfdoc', '_fontdata_enc_standard', '_fontdata_enc_symbol', '_fontdata_enc_winansi', '_fontdata_enc_zapfdingbats', '_fontdata_widths_courier', '_fontdata_widths_courierbold', '_fontdata_widths_courierboldoblique', '_fontdata_widths_courieroblique', '_fontdata_widths_helvetica', '_fontdata_widths_helveticabold', '_fontdata_widths_helveticaboldoblique', '_fontdata_widths_helveticaoblique', '_fontdata_widths_symbol', '_fontdata_widths_timesbold', '_fontdata_widths_timesbolditalic', '_fontdata_widths_timesitalic', '_fontdata_widths_timesroman', '_fontdata_widths_zapfdingbats']
Python
# Copyright (C) 2006, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # PIL's SpiderImagePlugin features a tkPhotoImage() method which imports # ImageTk (and thus brings the whole Tcl/Tk library in). # We cheat a little and remove the ImageTk import: I assume that if people # are really using ImageTk in their application, they will also import it # directly. def hook(mod): for i in range(len(mod.imports)): if mod.imports[i][0] == "ImageTk": del mod.imports[i] break return mod
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['win32com.server.policy'] def hook(mod): import sys if hasattr(sys, 'version_info'): vers = '%d%d' % (sys.version_info[0], sys.version_info[1]) else: import string toks = string.split(sys.version[:3], '.') vers = '%s%s' % (toks[0], toks[1]) newname = 'pythoncom%s' % vers if mod.typ == 'EXTENSION': mod.__name__ = newname else: import win32api h = win32api.LoadLibrary(newname+'.dll') pth = win32api.GetModuleFileName(h) #win32api.FreeLibrary(h) import mf mod = mf.ExtensionModule(newname, pth) return mod
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # PyQt (qt.pyd) has a secret dependence on sip.pyd hiddenimports = ['sip']
Python
# Copyright (C) 2006, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys # Since Python 2.3, builtin module "time" imports Python module _strptime # to implement "time.strptime". if hasattr(sys, "version_info") and sys.version_info >= (2,3): hiddenimports = ['_strptime']
Python
# Contributed by Peter Burgers # The matplotlib.numerix package sneaks these imports in under the radar: hiddenimports = [ 'fft', 'linear_algebra', 'random_array', 'ma', 'mlab', ]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['cStringIO', 'traceback']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['copy_reg', 'types', 'string']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['xml.sax.xmlreader','xml.sax.expatreader'] def hook(mod): # This hook checks for the infamous _xmlcore hack # http://www.amk.ca/diary/2003/03/pythons__xmlplus_hack.html from hookutils import exec_statement import string, marshal txt = exec_statement("import xml;print xml.__file__") if string.find(txt, '_xmlplus') > -1: if txt[:-3] == ".py": txt = txt + 'c' co = marshal.loads(open(txt, 'rb').read()[8:]) old_pth = mod.__path__[:] mod.__init__('xml', txt, co) mod.__path__.extend(old_pth) return mod
Python
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import glob def hook(mod): global hiddenimports modpath = mod.__path__[0] hiddenimports = [] for fn in glob.glob('%s/*' % modpath): if os.path.isdir(fn): fn = os.path.basename(fn) hiddenimports.append('django.db.backends.' + fn + '.base') # Compiler (see class BaseDatabaseOperations) hiddenimports.append("django.db.models.sql.compiler") return mod
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # empty
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys, string def hook(mod): names = sys.builtin_module_names if 'posix' in names: removes = ['nt', 'dos', 'os2', 'mac', 'win32api'] elif 'nt' in names: removes = ['dos', 'os2', 'mac'] elif 'os2' in names: removes = ['nt', 'dos', 'mac', 'win32api'] elif 'dos' in names: removes = ['nt', 'os2', 'mac', 'win32api'] elif 'mac' in names: removes = ['nt', 'dos', 'os2', 'win32api'] for i in range(len(mod.imports)-1, -1, -1): nm = mod.imports[i][0] pos = string.find(nm, '.') if pos > -1: nm = nm[:pos] if nm in removes: del mod.imports[i] return mod
Python
hiddenimports = ['mx.DateTime']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA attrs = [('Node',0), ('NodeFilter',0), ('XML_NAMESPACE',0), ('XMLNS_NAMESPACE',0), ('DOMException',0), ('HTML_4_TRANSITIONAL_INLINE',0), ('IsDOMString',0), ('FtDomException',0), ('NodeTypeDict',0), ('NodeTypeToClassName',0), ('Print',0), ('PrettyPrint',0), ('XHtmlPrettyPrint',0), ('XHtmlPrint',0), ('ReleaseNode',0), ('StripHtml',0), ('StripXml',0), ('GetElementById',0), ('XmlSpaceState',0), ('GetAllNs',0), ('SplitQName',0), ('SeekNss',0), ]
Python
hiddenimports = ["sip", "PyQt4.QtCore", "PyQt4.QtGui", "PyQt4.QtNetwork", "PyQt4._qt"]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA attrs = [('InputSource', 0), ('ContentHandler', 0), ('ErrorHandler', 0), ('SAXException', 0), ('SAXNotRecognizedException', 0), ('SAXParseException', 0), ('SAXNotSupportedException', 0), ('SAXReaderNotAvailable', 0), ('parse', 0), ('parseString', 0), ('make_parser', 0), ]
Python
hiddenimports = ['sip', 'PyQt4.QtCore', 'PyQt4._qt']
Python
#!/usr/bin/env python import os def exec_statement(stat): """Executes a Python statement in an externally spawned interpreter, and returns anything that was emitted in the standard output as a single string. """ import os, tempfile, sys fnm = tempfile.mktemp() exe = sys.executable # Using "echo on" as a workaround for a bug in NT4 shell if os.name == "nt": cmd = 'echo on && "%s" -c "%s" > "%s"' % (exe, stat, fnm) else: cmd = '"%s" -c "%s" > "%s"' % (exe, stat, fnm) # Prepend PYTHONPATH with pathex pp = os.pathsep.join(sys.pathex) old_pp = os.environ.get('PYTHONPATH', '') if old_pp: pp = os.pathsep.join([pp, old_pp]) os.environ["PYTHONPATH"] = pp try: # Actually execute the statement os.system(cmd) finally: if old_pp: os.environ["PYTHONPATH"] = old_pp else: del os.environ["PYTHONPATH"] txt = open(fnm, 'r').read()[:-1] os.remove(fnm) return txt def qt4_plugins_dir(): import os qt4_plugin_dirs = eval(exec_statement("from PyQt4.QtCore import QCoreApplication; app=QCoreApplication([]); print map(unicode,app.libraryPaths())")) if not qt4_plugin_dirs: print "E: Cannot find PyQt4 plugin directories" return "" for d in qt4_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds print "E: Cannot find existing PyQt4 plugin directory" return "" def qt4_phonon_plugins_dir(): import os qt4_plugin_dirs = eval(exec_statement("from PyQt4.QtGui import QApplication; app=QApplication([]); app.setApplicationName('pyinstaller'); from PyQt4.phonon import Phonon; v=Phonon.VideoPlayer(Phonon.VideoCategory); print map(unicode,app.libraryPaths())")) if not qt4_plugin_dirs: print "E: Cannot find PyQt4 phonon plugin directories" return "" for d in qt4_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds print "E: Cannot find existing PyQt4 phonon plugin directory" return "" def babel_localedata_dir(): return exec_statement("import babel.localedata; print babel.localedata._dirname") def mpl_data_dir(): return exec_statement("import matplotlib; print matplotlib._get_data_path()") def qwt_numpy_support(): return eval(exec_statement("from PyQt4 import Qwt5; print hasattr(Qwt5, 'toNumpy')")) def qwt_numeric_support(): return eval(exec_statement("from PyQt4 import Qwt5; print hasattr(Qwt5, 'toNumeric')")) def qwt_numarray_support(): return eval(exec_statement("from PyQt4 import Qwt5; print hasattr(Qwt5, 'toNumarray')")) def django_dottedstring_imports(django_root_dir): package_name = os.path.basename(django_root_dir) os.environ["DJANGO_SETTINGS_MODULE"] = "%s.settings" %package_name return eval(exec_statement("execfile(r'%s')" %os.path.join(os.path.dirname(__file__), "django-import-finder.py"))) def find_django_root(dir): entities = os.listdir(dir) if "manage.py" in entities and "settings.py" in entities and "urls.py" in entities: return [dir] else: django_root_directories = [] for entity in entities: path_to_analyze = os.path.join(dir, entity) if os.path.isdir(path_to_analyze): dir_entities = os.listdir(path_to_analyze) if "manage.py" in dir_entities and "settings.py" in dir_entities and "urls.py" in dir_entities: django_root_directories.append(path_to_analyze) return django_root_directories
Python
hiddenimports = ["tables._comp_lzo", "tables._comp_bzip2"]
Python
## Hook for PyOpenGL 3.x versions from 3.0.0b6 up. Previous versions have a ## plugin system based on pkg_resources which is problematic to handle correctly ## under pyinstaller; 2.x versions used to run fine without hooks, so this one ## shouldn't hurt. import os import sys ## PlatformPlugin performs a conditional import based on os.name and ## sys.platform. pyinstaller misses this so let's add it ourselves... if os.name == 'nt': hiddenimports = ['OpenGL.platform.win32'] else: if sys.platform == 'linux2': hiddenimports = ['OpenGL.platform.glx'] elif sys.platform[:6] == 'darwin': hiddenimports = ['OpenGL.platform.darwin'] else: print 'ERROR: hook-OpenGL: Unrecognised combo (os.name: %s, sys.platform: %s)' % (os.name, sys.platform) ## arrays modules are needed too hiddenimports += ['OpenGL.arrays.ctypesparameters', 'OpenGL.arrays.numarrays', 'OpenGL.arrays._numeric', 'OpenGL.arrays._strings', 'OpenGL.arrays.ctypespointers', 'OpenGL.arrays.lists', 'OpenGL.arrays.numbers', 'OpenGL.arrays.numeric', 'OpenGL.arrays.strings', 'OpenGL.arrays.ctypesarrays', 'OpenGL.arrays.nones', 'OpenGL.arrays.numericnames', 'OpenGL.arrays.numpymodule', 'OpenGL.arrays.vbo', ]
Python
# Contributed by pyplant@googlemail.com hiddenimports = ['_elementpath', 'gzip']
Python
from hooks.hookutils import babel_localedata_dir hiddenimports = ["babel.dates"] datas = [ (babel_localedata_dir(), ""), ]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # Forward to shared code for PIL. PIL can be imported either as a top-level package # (from PIL import Image), or not (import Image), because it installs a # PIL.pth. from hooks.shared_PIL_SpiderImagePlugin import *
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA hiddenimports = ['ISO', 'ARPA', 'ODMG', 'Locale', 'Feasts', 'Parser', 'NIST']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # FIXME: for a strange bug in Python's import machinery, we need to adjust # the module name before proceeding to the PIL import. The name would # otherwise be "hooks.hook-PIL.Image", which will then produce this # monstruosity: # <module 'hooks.hook-PIL.PIL.Image' from 'C:\python24\lib\site-packages\PIL\Image.pyc'> # __name__ = "hook-image" # Forward to shared code for PIL. PIL can be imported either as a top-level package # (from PIL import Image), or not (import Image), because it installs a # PIL.pth. from hooks.shared_PIL_Image import *
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # cElementTree has a hidden import (Python >=2.5 stdlib version) hiddenimports = ['xml.etree.ElementTree']
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA attrs = [('NeedUnicodeConversions', 0), ('Dispatch',0)]
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import string, os, sys, win32api, Makespec tmplt = """\ import sys import string import os import pythoncom pythoncom.frozen = 1 inprocess = getattr(sys, 'frozen', None) %(modules)s klasses = (%(klasses)s,) def DllRegisterServer(): import win32com.server.register win32com.server.register.RegisterClasses(*klasses) return 0 def DllUnregisterServer(): import win32com.server.register win32com.server.register.UnregisterClasses(*klasses) return 0 if sys.frozen!="dll": import win32com.server.localserver for i in range(1, len(sys.argv)): arg = string.lower(sys.argv[i]) if string.find(arg, "/reg") > -1 or string.find(arg, "--reg") > -1: DllRegisterServer() break if string.find(arg, "/unreg") > -1 or string.find(arg, "--unreg") > -1: DllUnregisterServer() break # MS seems to like /automate to run the class factories. if string.find(arg, "/automate") > -1: clsids = [] for k in klasses: clsids.append(k._reg_clsid_) win32com.server.localserver.serve(clsids) break else: # You could do something else useful here. import win32api win32api.MessageBox(0, "This program hosts a COM Object and\\r\\nis started automatically", "COM Object") """ def create(scripts, debug, verbosity, workdir, ascii=0): infos = [] # (path, module, klasses) for script in scripts: infos.append(analscriptname(script)) if not os.path.exists(workdir): os.makedirs(workdir) outfnm = 'drive%s.py' % infos[0][1] outfnm = os.path.join(workdir, outfnm) outf = open(outfnm, 'w') klassspecs = [] modimports = [] flags = 'debug=%s, quiet=%s' % (debug, verbosity==0) paths = [] for path, module, klasses in infos: if path: paths.append(path) modimports.append("import %s" % (module,)) for klass in klasses: klassspecs.append("%s.%s" % (module, klass)) for i in range(len(paths)): path = paths[i] paths[i] = win32api.GetShortPathName(os.path.normpath(path)) modimports = string.join(modimports, '\n') klassspecs = string.join(klassspecs, ', ') d = { 'modules':modimports, 'klasses':klassspecs, } outf.write( tmplt % d ) outf.close() print "**********************************" print "Driver script %s created" % outfnm specfnm = Makespec.main([outfnm], console=debug, debug=debug, workdir=workdir, pathex=paths, comserver=1, ascii=ascii) print "Spec file %s created" % specfnm def analscriptname(script): # return (path, module, klasses) path, basename = os.path.split(script) module = os.path.splitext(basename)[0] while ispkgdir(path): path, basename = os.path.split(path) module = '%s.%s' % (basename, module) try: __import__(module) except ImportError: oldpath = sys.path[:] sys.path.insert(0, path) try: __import__(module) finally: sys.path = oldpath else: path = None m = sys.modules[module] klasses = [] for nm, thing in m.__dict__.items(): if hasattr(thing, '_reg_clsid_'): klasses.append(nm) return (path, module, klasses) def ispkgdir(path): try: open(os.path.join(path, '__init__.py'), 'r') except IOError: try: open(os.path.join(path, '__init__.pyc'), 'rb') except IOError: return 0 return 1 usage = """\ Usage: python %s [options] <scriptname>.py [<scriptname>.py ...] --debug -> use debug console build and register COM servers with debug --verbose -> use verbose flag in COM server registration --out dir -> generate script and spec file in dir The next step is to run Build.py against the generated spec file. See doc/Tutorial.html for details. """ if __name__ == '__main__': #scripts, debug, verbosity, workdir debug = verbosity = ascii = 0 workdir = '.' import getopt opts, args = getopt.getopt(sys.argv[1:], '', ['debug', 'verbose', 'ascii', 'out=']) for opt, val in opts: if opt == '--debug': debug = 1 elif opt == '--verbose': verbosity = 1 elif opt == '--out': workdir = val elif opt == '--ascii': ascii = 1 else: print usage % sys.argv[0] sys.exit(1) if not args: print usage % sys.argv[0] else: create(args, debug, verbosity, workdir, ascii)
Python
#!/usr/bin/python # Tkinter interface to the McMillan installer # (c) 2003 Alan James Salmoni - yes, all this bad code is all mine!!! # released under the MIT license import os, os.path from Tkinter import * import tkFileDialog import FileDialog class McGUI: def __init__(self): root = Tk() fr1 = Frame(root) fr1["width"] = 200 fr1["height"] = 100 fr1.pack(side="top") fr2 = Frame(root) fr2["width"] = 200 fr2["height"] = 300 fr2["borderwidth"] = 2 fr2["relief"] = "ridge" fr2.pack() fr4 = Frame(root) fr4["width"]=200 fr4["height"]=100 fr4.pack(side="bottom") getFileButton = Button(fr1) getFileButton["text"] = "Script..." getFileButton.bind("<Button>",self.GetFile) getFileButton.pack(side="left") self.filein = Entry(fr1) self.filein.pack(side="right") self.filetypecheck = Checkbutton(fr2) self.filetypecheck["text"] = "One File Package " self.filetype = IntVar() self.filetypecheck["variable"] = self.filetype self.filetypecheck.pack() self.tkcheck = Checkbutton(fr2) self.tkcheck["text"] = "Include Tcl/Tk " self.tk = IntVar() self.tkcheck["variable"] = self.tk self.tkcheck.pack() self.asciicheck = Checkbutton(fr2) self.asciicheck["text"] = "Do NOT include decodings" self.ascii = IntVar() self.asciicheck["variable"] = self.ascii self.asciicheck.pack() self.debugcheck = Checkbutton(fr2) self.debugcheck["text"] = "Use debug versions " self.debug = IntVar() self.debugcheck["variable"] = self.debug self.debugcheck.pack() self.noconsolecheck = Checkbutton(fr2) self.noconsolecheck["text"] = "No console (Windows only)" self.noconsole = IntVar() self.noconsolecheck["variable"] = self.noconsole self.noconsolecheck.pack() okaybutton = Button(fr4) okaybutton["text"] = "Okay " okaybutton.bind("<Button>",self.makePackage) okaybutton.pack(side="left") cancelbutton = Button(fr4) cancelbutton["text"] = "Cancel" cancelbutton.bind("<Button>",self.killapp) cancelbutton.pack(side="right") self.fin = '' self.fout = '' root.mainloop() def killapp(self, event): sys.exit(0) def makePackage(self, event): commands = 'python Makespec.py ' if (self.filetype.get() == 1): commands = commands + '--onefile ' if (self.tk.get() == 1): commands = commands + '--tk ' if (self.ascii.get() == 1): commands = commands + '--ascii ' if (self.debug.get() == 1): commands = commands + '--debug ' if (self.noconsole.get() == 1): commands = commands + '--noconsole ' commands = commands + self.fin x = os.path.split(self.fin) y = os.path.splitext(x[1]) os.system(commands) commands = 'python Build.py '+str(y[0])+os.sep+str(y[0])+'.spec' os.system(commands) sys.exit(0) def GetFile(self, event): self.fin = tkFileDialog.askopenfilename() self.filein.insert(0,self.fin) if __name__ == "__main__": app = McGUI()
Python
#!/usr/bin/env python # Crypt support routines # Copyright (C) 2005, Giovanni Bajo import sys class ArgsError(Exception): pass def gen_random_key(size=32): """ Generate a cryptographically-secure random key. This is done by using Python 2.4's os.urandom, or PyCrypto. """ import os if hasattr(os, "urandom"): # Python 2.4+ return os.urandom(size) # Try using PyCrypto if available try: from Crypto.Util.randpool import RandomPool from Crypto.Hash import SHA256 return RandomPool(hash=SHA256).get_bytes(size) except ImportError: print >>sys.stderr, "WARNING: The generated key will not be cryptographically-secure key. Consider using Python 2.4+ to generate the key, or install PyCrypto." # Stupid random generation import random L = [] for i in range(size): L.append(chr(random.randint(0, 255))) return "".join(L) def cmd_genkey(args): import pprint if len(args) != 1: raise ArgsError, "invalid number of arguments" key_file = args[0] key = gen_random_key() f = open(key_file, "w") print >>f, "key = %s" % repr(key) return 0 def main(): global global_opts global opts import pyi_optparse as optparse cmds = {} p = optparse.OptionParser( usage="%prog [opts] file", description="Generate a plaintext keyfile containing a " "random-generated encryption key. ") cmds["genkey"] = p for c,p in cmds.items(): p.prog = p.get_prog_name() + " " + c cmdnames = cmds.keys() cmdnames.sort() p = optparse.OptionParser( usage="%prog cmd [opts]\n\n" + "Available Commands:\n " + "\n ".join(cmdnames), description="This tool is a helper of crypt-related tasks with PyInstaller." ) p.disable_interspersed_args() global_opts,args = p.parse_args() if not args: p.print_usage() return -1 c = args.pop(0) if c not in cmds.keys(): print "invalid command: %s" % c return -1 p = cmds[c] opts, args = p.parse_args(args) try: return globals()["cmd_" + c](args) except ArgsError, e: p.error(e) if __name__ == "__main__": sys.exit(main())
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import string, os, sys, win32api, Makespec modspec = """\ %(mod)s.%(klass)s._reg_class_spec_ = "%(mod)s.%(klass)s" if (not hasattr(%(mod)s.%(klass)s, '_reg_clsctx_') or %(mod)s.%(klass)s._reg_clsctx_ & pythoncom.CLSCTX_INPROC): %(mod)s.%(klass)s._reg_options_ = {'InprocServer32': os.path.abspath( os.path.join( os.path.dirname(sys.executable), "%(dllname)s"))} """ #mod, klass, dllname tmplt = """\ import sys import string import os inprocess = getattr(sys, 'frozen', None) %(modimports)s register = 0 for i in range(1, len(sys.argv)): arg = sys.argv[i] if string.find(arg, "reg") > -1: register = 1 if arg == '/unreg': sys.argv[i] = '--unregister' if register: import pythoncom pythoncom.frozen = 1 %(modspecs)s from win32com.server import register register.UseCommandLine(%(regspecs)s, %(flags)s) else: #older Python's need to force this import before pythoncom does it import win32com.server.policy if inprocess == 'dll': pass else: import win32com.server.localserver win32com.server.localserver.main() """ #modimports, modspecs regspecs, flags def create(scripts, debug, verbosity, workdir, ascii=0): infos = [] # (path, module, klasses) for script in scripts: infos.append(analscriptname(script)) outfnm = 'drive%s.py' % infos[0][1] dllname = 'drive%s.dll' % infos[0][1] if not os.path.exists(workdir): os.makedirs(workdir) outfnm = os.path.join(workdir, outfnm) outf = open(outfnm, 'w') modspecs = [] regspecs = [] modimports = [] flags = 'debug=0, quiet=%s' % (verbosity==0) paths = [] for path, module, klasses in infos: if path: paths.append(path) for klass in klasses: d = { 'mod':module, 'klass':klass, 'dllname':dllname } modspecs.append(modspec % d) regspecs.append('%(mod)s.%(klass)s' % d) modimports.append("import %(mod)s" % d) for i in range(len(paths)): path = paths[i] paths[i] = win32api.GetShortPathName(os.path.normpath(path)) modspecs = string.join(modspecs, '\n') modimports = string.join(modimports, '\n') regspecs = string.join(regspecs, ', ') d = { 'modspecs':modspecs, 'regspecs':regspecs, 'modimports':modimports, 'flags':flags } outf.write( tmplt % d ) outf.close() print "**********************************" print "Driver script %s created" % outfnm specfnm = Makespec.main([outfnm], console=debug, debug=debug, workdir=workdir, pathex=paths, comserver=1, ascii=ascii) print "Spec file %s created" % specfnm def analscriptname(script): # return (path, module, klasses) path, basename = os.path.split(script) module = os.path.splitext(basename)[0] while ispkgdir(path): path, basename = os.path.split(path) module = '%s.%s' % (basename, module) try: __import__(module) except ImportError: oldpath = sys.path[:] sys.path.insert(0, path) try: __import__(module) finally: sys.path = oldpath else: path = None m = sys.modules[module] klasses = [] for nm, thing in m.__dict__.items(): if hasattr(thing, '_reg_clsid_'): klasses.append(nm) return (path, module, klasses) def ispkgdir(path): try: open(os.path.join(path, '__init__.py'), 'r') except IOError: try: open(os.path.join(path, '__init__.pyc'), 'rb') except IOError: return 0 return 1 usage = """\ Usage: python %s [options] <scriptname>.py [<scriptname>.py ...] --debug -> use debug console build and register COM servers with debug --verbose -> use verbose flag in COM server registration --out dir -> generate script and spec file in dir The next step is to run Build.py against the generated spec file. See doc/Tutorial.html for details. """ if __name__ == '__main__': #scripts, debug, verbosity, workdir debug = verbosity = ascii = 0 workdir = '.' import getopt opts, args = getopt.getopt(sys.argv[1:], '', ['debug', 'verbose', 'ascii', 'out=']) for opt, val in opts: if opt == '--debug': debug = 1 elif opt == '--verbose': verbosity = 1 elif opt == '--out': workdir = val elif opt == '--ascii': ascii = 1 else: print usage % sys.argv[0] sys.exit(1) if not args: print usage % sys.argv[0] else: create(args, debug, verbosity, workdir, ascii)
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition to the permissions in the GNU General Public License, the # authors give you unlimited permission to link or embed the compiled # version of this file into combinations with other programs, and to # distribute those combinations without any restriction coming from the # use of this file. (The General Public License restrictions do apply in # other respects; for example, they cover modification of the file, and # distribution when not linked into a combine executable.) # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # subclasses may not need marshal or struct, but since they're # builtin, importing is safe. # # While an Archive is really an abstraction for any "filesystem # within a file", it is tuned for use with imputil.FuncImporter. # This assumes it contains python code objects, indexed by the # the internal name (ie, no '.py'). # See carchive.py for a more general archive (contains anything) # that can be understood by a C program. _verbose = 0 _listdir = None _environ = None # **NOTE** This module is used during bootstrap. Import *ONLY* builtin modules. import marshal import struct import imp import sys _c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes()) for nm in ('nt', 'posix', 'dos', 'os2', 'mac'): if nm in sys.builtin_module_names: mod = __import__(nm) _listdir = mod.listdir _environ = mod.environ break if hasattr(sys, 'version_info'): versuffix = '%d%d'%(sys.version_info[0],sys.version_info[1]) else: vers = sys.version dot1 = dot2 = 0 for i in range(len(vers)): if vers[i] == '.': if dot1: dot2 = i break else: dot1 = i else: dot2 = len(vers) versuffix = '%s%s' % (vers[:dot1], vers[dot1+1:dot2]) if "-vi" in sys.argv[1:]: _verbose = 1 class ArchiveReadError(RuntimeError): pass class Archive: """ A base class for a repository of python code objects. The extract method is used by imputil.ArchiveImporter to get code objects by name (fully qualified name), so an enduser "import a.b" would become extract('a.__init__') extract('a.b') """ MAGIC = 'PYL\0' HDRLEN = 12 # default is MAGIC followed by python's magic, int pos of toc TOCPOS = 8 TRLLEN = 0 # default - no trailer TOCTMPLT = {} # os = None _bincache = None def __init__(self, path=None, start=0): "Initialize an Archive. If path is omitted, it will be an empty Archive." self.toc = None self.path = path self.start = start import imp self.pymagic = imp.get_magic() if path is not None: self.lib = open(self.path, 'rb') self.checkmagic() self.loadtoc() ####### Sub-methods of __init__ - override as needed ############# def checkmagic(self): """ Overridable. Check to see if the file object self.lib actually has a file we understand. """ self.lib.seek(self.start) #default - magic is at start of file if self.lib.read(len(self.MAGIC)) != self.MAGIC: raise ArchiveReadError, "%s is not a valid %s archive file" \ % (self.path, self.__class__.__name__) if self.lib.read(len(self.pymagic)) != self.pymagic: raise ArchiveReadError, "%s has version mismatch to dll" % (self.path) self.lib.read(4) def loadtoc(self): """ Overridable. Default: After magic comes an int (4 byte native) giving the position of the TOC within self.lib. Default: The TOC is a marshal-able string. """ self.lib.seek(self.start + self.TOCPOS) (offset,) = struct.unpack('!i', self.lib.read(4)) self.lib.seek(self.start + offset) self.toc = marshal.load(self.lib) ######## This is what is called by FuncImporter ####### ## Since an Archive is flat, we ignore parent and modname. #XXX obsolete - imputil only code ## def get_code(self, parent, modname, fqname): #### if _verbose: #### print "I: get_code(%s, %s, %s, %s)" % (self, parent, modname, fqname) ## iname = fqname ## if parent: ## iname = '%s.%s' % (parent.__dict__.get('__iname__', parent.__name__), modname) #### if _verbose: #### print "I: get_code: iname is %s" % iname ## rslt = self.extract(iname) # None if not found, (ispkg, code) otherwise #### if _verbose: #### print 'I: get_code: rslt', rslt ## if rslt is None: #### if _verbose: #### print 'I: get_code: importer', getattr(parent, "__importer__", None),'self',self ## # check the cache if there is no parent or self is the parents importer ## if parent is None or getattr(parent, "__importer__", None) is self: #### if _verbose: #### print 'I: get_code: cached 1',iname ## file, desc = Archive._bincache.get(iname, (None, None)) #### if _verbose: #### print 'I: get_code: file',file,'desc',desc ## if file: ## try: ## fp = open(file, desc[1]) ## except IOError: ## pass ## else: ## module = imp.load_module(fqname, fp, file, desc) ## if _verbose: ## print "I: import %s found %s" % (fqname, file) ## return 0, module, {'__file__':file} ## if _verbose: ## print "I: import %s failed" % fqname ## ## return None ## ## ispkg, code = rslt ## values = {'__file__' : code.co_filename, '__iname__' : iname} ## if ispkg: ## values['__path__'] = [fqname] ## if _verbose: ## print "I: import %s found %s" % (fqname, iname) ## return ispkg, code, values ####### Core method - Override as needed ######### def extract(self, name): """ Get the object corresponding to name, or None. For use with imputil ArchiveImporter, object is a python code object. 'name' is the name as specified in an 'import name'. 'import a.b' will become: extract('a') (return None because 'a' is not a code object) extract('a.__init__') (return a code object) extract('a.b') (return a code object) Default implementation: self.toc is a dict self.toc[name] is pos self.lib has the code object marshal-ed at pos """ ispkg, pos = self.toc.get(name, (0,None)) if pos is None: return None self.lib.seek(self.start + pos) return ispkg, marshal.load(self.lib) ######################################################################## # Informational methods def contents(self): """Return a list of the contents Default implementation assumes self.toc is a dict like object. Not required by ArchiveImporter. """ return self.toc.keys() ######################################################################## # Building ####### Top level method - shouldn't need overriding ####### def build(self, path, lTOC): """Create an archive file of name 'path'. lTOC is a 'logical TOC' - a list of (name, path, ...) where name is the internal name, eg 'a' and path is a file to get the object from, eg './a.pyc'. """ self.path = path self.lib = open(path, 'wb') #reserve space for the header if self.HDRLEN: self.lib.write('\0'*self.HDRLEN) #create an empty toc if type(self.TOCTMPLT) == type({}): self.toc = {} else: # assume callable self.toc = self.TOCTMPLT() for tocentry in lTOC: self.add(tocentry) # the guts of the archive tocpos = self.lib.tell() self.save_toc(tocpos) if self.TRLLEN: self.save_trailer(tocpos) if self.HDRLEN: self.update_headers(tocpos) self.lib.close() ####### manages keeping the internal TOC and the guts in sync ####### def add(self, entry): """Override this to influence the mechanics of the Archive. Assumes entry is a seq beginning with (nm, pth, ...) where nm is the key by which we'll be asked for the object. pth is the name of where we find the object. Overrides of get_obj_from can make use of further elements in entry. """ if self.os is None: import os self.os = os nm = entry[0] pth = entry[1] pynm, ext = self.os.path.splitext(self.os.path.basename(pth)) ispkg = pynm == '__init__' assert ext in ('.pyc', '.pyo') self.toc[nm] = (ispkg, self.lib.tell()) f = open(entry[1], 'rb') f.seek(8) #skip magic and timestamp self.lib.write(f.read()) def save_toc(self, tocpos): """Default - toc is a dict Gets marshaled to self.lib """ marshal.dump(self.toc, self.lib) def save_trailer(self, tocpos): """Default - not used""" pass def update_headers(self, tocpos): """Default - MAGIC + Python's magic + tocpos""" self.lib.seek(self.start) self.lib.write(self.MAGIC) self.lib.write(self.pymagic) self.lib.write(struct.pack('!i', tocpos)) class DummyZlib: def decompress(self, data): #raise RuntimeError, "zlib required but cannot be imported" return data def compress(self, data, lvl): #raise RuntimeError, "zlib required but cannot be imported" return data import iu ############################################################## # # ZlibArchive - an archive with compressed entries # class ZlibArchive(Archive): MAGIC = 'PYZ\0' TOCPOS = 8 HDRLEN = Archive.HDRLEN + 5 TRLLEN = 0 TOCTMPLT = {} LEVEL = 9 def __init__(self, path=None, offset=None, level=9, crypt=None): if path is None: offset = 0 elif offset is None: for i in range(len(path)-1, -1, -1): if path[i] == '?': try: offset = int(path[i+1:]) except ValueError: # Just ignore any spurious "?" in the path # (like in Windows UNC \\?\<path>). continue path = path[:i] break else: offset = 0 self.LEVEL = level if crypt is not None: self.crypted = 1 self.key = (crypt + "*"*32)[:32] else: self.crypted = 0 self.key = None Archive.__init__(self, path, offset) # dynamic import so not imported if not needed global zlib if self.LEVEL: try: import zlib except ImportError: zlib = DummyZlib() else: print "WARNING: compression level=0!!!" zlib = DummyZlib() global AES if self.crypted: import AES def _iv(self, nm): IV = nm * ((AES.block_size + len(nm) - 1) // len(nm)) return IV[:AES.block_size] def extract(self, name): (ispkg, pos, lngth) = self.toc.get(name, (0, None, 0)) if pos is None: return None self.lib.seek(self.start + pos) obj = self.lib.read(lngth) if self.crypted: if self.key is None: raise ImportError, "decryption key not found" obj = AES.new(self.key, AES.MODE_CFB, self._iv(name)).decrypt(obj) try: obj = zlib.decompress(obj) except zlib.error: if not self.crypted: raise raise ImportError, "invalid decryption key" try: co = marshal.loads(obj) except EOFError: raise ImportError, "PYZ entry '%s' failed to unmarshal" % name return ispkg, co def add(self, entry): if self.os is None: import os self.os = os nm = entry[0] pth = entry[1] base, ext = self.os.path.splitext(self.os.path.basename(pth)) ispkg = base == '__init__' try: txt = open(pth[:-1], 'r').read()+'\n' except (IOError, OSError): try: f = open(pth, 'rb') f.seek(8) #skip magic and timestamp bytecode = f.read() marshal.loads(bytecode).co_filename # to make sure it's valid obj = zlib.compress(bytecode, self.LEVEL) except (IOError, ValueError, EOFError, AttributeError): raise ValueError("bad bytecode in %s and no source" % pth) else: txt = iu._string_replace(txt, '\r\n', '\n') try: co = compile(txt, "%s/%s" % (self.path, nm), 'exec') except SyntaxError, e: print "Syntax error in", pth[:-1] print e.args raise obj = zlib.compress(marshal.dumps(co), self.LEVEL) if self.crypted: obj = AES.new(self.key, AES.MODE_CFB, self._iv(nm)).encrypt(obj) self.toc[nm] = (ispkg, self.lib.tell(), len(obj)) self.lib.write(obj) def update_headers(self, tocpos): """add level""" Archive.update_headers(self, tocpos) self.lib.write(struct.pack('!iB', self.LEVEL, self.crypted)) def checkmagic(self): Archive.checkmagic(self) self.LEVEL, self.crypted = struct.unpack('!iB', self.lib.read(5)) class Keyfile: def __init__(self, fn=None): if fn is None: fn = sys.argv[0] if fn[-4] == '.': fn = fn[:-4] fn += ".key" execfile(fn, {"__builtins__": None}, self.__dict__) if not hasattr(self, "key"): self.key = None class PYZOwner(iu.Owner): def __init__(self, path, target_platform=None): try: self.pyz = ZlibArchive(path) self.pyz.checkmagic() except (IOError, ArchiveReadError), e: raise iu.OwnerError(e) if self.pyz.crypted: if not hasattr(sys, "keyfile"): sys.keyfile = Keyfile() self.pyz = ZlibArchive(path, crypt=sys.keyfile.key) iu.Owner.__init__(self, path) def getmod(self, nm, newmod=imp.new_module): rslt = self.pyz.extract(nm) if rslt is None: return None ispkg, co = rslt mod = newmod(nm) try: mod.__file__ = co.co_filename except AttributeError: raise ImportError, "PYZ entry '%s' (%s) is not a valid code object" % (nm, repr(co)) if ispkg: if _environ.has_key('_MEIPASS2'): localpath = _environ['_MEIPASS2'][:-1] else: localpath = iu._os_path_dirname(self.path) mod.__path__ = [self.path, localpath, iu._os_path_dirname(mod.__file__)] #print "PYZOwner setting %s's __path__: %s" % (nm, mod.__path__) importer = iu.PathImportDirector(mod.__path__, {self.path:PkgInPYZImporter(nm, self), localpath:ExtInPkgImporter(localpath, nm)}, [iu.DirOwner]) mod.__importsub__ = importer.getmod mod.__co__ = co return mod class PkgInPYZImporter: def __init__(self, name, owner): self.name = name self.owner = owner def getmod(self, nm): #print "PkgInPYZImporter.getmod %s -> %s" % (nm, self.name+'.'+nm) return self.owner.getmod(self.name+'.'+nm) class ExtInPkgImporter(iu.DirOwner): def __init__(self, path, prefix): iu.DirOwner.__init__(self, path) self.prefix = prefix def getmod(self, nm): return iu.DirOwner.getmod(self, self.prefix+'.'+nm) #XXX this should also get moved out ##iu._globalownertypes.insert(0, PYZOwner) ##iu.ImportManager().install()
Python
#! /usr/bin/env python # # Find external dependencies of binary libraries. # # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # use dumpbin.exe (if present) to find the binary # dependencies of an extension module. # if dumpbin not available, pick apart the PE hdr of the binary # while this appears to work well, it is complex and subject to # problems with changes to PE hdrs (ie, this works only on 32 bit Intel # Windows format binaries) # # Note also that you should check the results to make sure that the # dlls are redistributable. I've listed most of the common MS dlls # under "excludes" below; add to this list as necessary (or use the # "excludes" option in the INSTALL section of the config file). import os import time import string import sys import re from glob import glob seen = {} _bpath = None iswin = sys.platform[:3] == 'win' cygwin = sys.platform == 'cygwin' darwin = sys.platform[:6] == 'darwin' silent = False # True suppresses all informative messages from the dependency code if iswin: import shutil import traceback import zipfile if hasattr(sys, "version_info") and sys.version_info[:2] >= (2,6): try: import win32api import pywintypes except ImportError: print "ERROR: Python 2.6+ on Windows support needs pywin32" print "Please install http://sourceforge.net/projects/pywin32/" sys.exit(2) from winmanifest import RT_MANIFEST, GetManifestResources, Manifest try: from winmanifest import winresource except ImportError, detail: winresource = None excludes = { 'KERNEL32.DLL':1, 'ADVAPI.DLL':1, 'MSVCRT.DLL':1, 'ADVAPI32.DLL':1, 'COMCTL32.DLL':1, 'CRTDLL.DLL':1, 'GDI32.DLL':1, 'MFC42.DLL':1, 'NTDLL.DLL':1, 'OLE32.DLL':1, 'OLEAUT32.DLL':1, 'RPCRT4.DLL':1, 'SHELL32.DLL':1, 'USER32.DLL':1, 'WINSPOOL.DRV':1, 'WS2HELP.DLL':1, 'WS2_32.DLL':1, 'WSOCK32.DLL':1, 'MSWSOCK.DLL':1, 'WINMM.DLL':1, 'COMDLG32.DLL':1, ## 'ZLIB.DLL':1, # test with python 1.5.2 'ODBC32.DLL':1, 'VERSION.DLL':1, 'IMM32.DLL':1, 'DDRAW.DLL':1, 'DCIMAN32.DLL':1, 'OPENGL32.DLL':1, 'GLU32.DLL':1, 'GLUB32.DLL':1, 'NETAPI32.DLL':1, 'MSCOREE.DLL':1, 'PSAPI.DLL':1, 'MSVCP80.DLL':1, 'MSVCR80.DLL':1, 'MSVCP90.DLL':1, 'MSVCR90.DLL':1, 'IERTUTIL.DLL':1, 'POWRPROF.DLL':1, 'SHLWAPI.DLL':1, 'URLMON.DLL':1, 'MSIMG32.DLL':1, 'MPR.DLL':1, 'DNSAPI.DLL':1, 'RASAPI32.DLL':1, # regex excludes r'/libc\.so\..*':1, r'/libdl\.so\..*':1, r'/libm\.so\..*':1, r'/libpthread\.so\..*':1, r'/librt\.so\..*':1, r'/libthread_db\.so\..*':1, r'/libdb-.*\.so':1, # libGL can reference some hw specific libraries (like nvidia libs) r'/libGL\..*':1, # MS assembly excludes 'Microsoft.Windows.Common-Controls':1, } # Darwin has a stable ABI for applications, so there is no need # to include either /usr/lib nor system frameworks. if darwin: excludes['^/usr/lib/'] = 1 excludes['^/System/Library/Frameworks'] = 1 excludesRe = re.compile('|'.join(excludes.keys()), re.I) def getfullnameof(mod, xtrapath = None): """Return the full path name of MOD. MOD is the basename of a dll or pyd. XTRAPATH is a path or list of paths to search first. Return the full path name of MOD. Will search the full Windows search path, as well as sys.path""" # Search sys.path first! epath = sys.path + getWindowsPath() if xtrapath is not None: if type(xtrapath) == type(''): epath.insert(0, xtrapath) else: epath = xtrapath + epath for p in epath: npth = os.path.join(p, mod) if os.path.exists(npth): return npth # second try: lower case filename for p in epath: npth = os.path.join(p, string.lower(mod)) if os.path.exists(npth): return npth return '' # TODO function is not used - remove? def _getImports_dumpbin(pth): """Find the binary dependencies of PTH. This implementation (not used right now) uses the MSVC utility dumpbin""" import tempfile rslt = [] tmpf = tempfile.mktemp() os.system('dumpbin /IMPORTS "%s" >%s' %(pth, tmpf)) time.sleep(0.1) txt = open(tmpf,'r').readlines() os.remove(tmpf) i = 0 while i < len(txt): tokens = string.split(txt[i]) if len(tokens) == 1 and string.find(tokens[0], '.') > 0: rslt.append(string.strip(tokens[0])) i = i + 1 return rslt def _getImports_pe_lib_pefile(pth): """Find the binary dependencies of PTH. This implementation walks through the PE header and uses library pefile for that and supports 32/64bit Windows""" import pefile pe = pefile.PE(pth) dlls = [] for entry in pe.DIRECTORY_ENTRY_IMPORT: dlls.append(entry.dll) return dlls # TODO function is not used - remove? def _getImports_pe_x(pth): """Find the binary dependencies of PTH. This implementation walks through the PE header""" import struct rslt = [] try: f = open(pth, 'rb').read() pehdrd = struct.unpack('l', f[60:64])[0] #after the MSDOS loader is the offset of the peheader magic = struct.unpack('l', f[pehdrd:pehdrd+4])[0] # pehdr starts with magic 'PE\000\000' (or 17744) # then 20 bytes of COFF header numsecs = struct.unpack('h', f[pehdrd+6:pehdrd+8])[0] # whence we get number of sections opthdrmagic = struct.unpack('h', f[pehdrd+24:pehdrd+26])[0] if opthdrmagic == 0x10b: # PE32 format numdictoffset = 116 importoffset = 128 elif opthdrmagic == 0x20b: # PE32+ format numdictoffset = 132 importoffset = 148 else: print "E: bindepend cannot analyze %s - unknown header format! %x" % (pth, opthdrmagic) return rslt numdirs = struct.unpack('l', f[pehdrd+numdictoffset:pehdrd+numdictoffset+4])[0] idata = '' if magic == 17744: importsec, sz = struct.unpack('2l', f[pehdrd+importoffset:pehdrd+importoffset+8]) if sz == 0: return rslt secttbl = pehdrd + numdictoffset + 4 + 8*numdirs secttblfmt = '8s7l2h' seclist = [] for i in range(numsecs): seclist.append(struct.unpack(secttblfmt, f[secttbl+i*40:secttbl+(i+1)*40])) #nm, vsz, va, rsz, praw, preloc, plnnums, qrelocs, qlnnums, flags \ # = seclist[-1] for i in range(len(seclist)-1): if seclist[i][2] <= importsec < seclist[i+1][2]: break vbase = seclist[i][2] raw = seclist[i][4] idatastart = raw + importsec - vbase idata = f[idatastart:idatastart+seclist[i][1]] i = 0 while 1: chunk = idata[i*20:(i+1)*20] if len(chunk) != 20: print "E: premature end of import table (chunk is %d, not 20)" % len(chunk) break vsa = struct.unpack('5l', chunk)[3] if vsa == 0: break sa = raw + vsa - vbase end = string.find(f, '\000', sa) nm = f[sa:end] if nm: rslt.append(nm) i = i + 1 else: print "E: bindepend cannot analyze %s - file is not in PE format!" % pth except IOError: print "E: bindepend cannot analyze %s - file not found!" % pth #except struct.error: # print "E: bindepend cannot analyze %s - error walking thru pehdr" % pth return rslt def _getImports_pe(path): """Find the binary dependencies of PTH. This implementation walks through the PE header""" import struct f = open(path, 'rb') # skip the MSDOS loader f.seek(60) # get offset to PE header offset = struct.unpack('l', f.read(4))[0] f.seek(offset) signature = struct.unpack('l', f.read(4))[0] coffhdrfmt = 'hhlllhh' rawcoffhdr = f.read(struct.calcsize(coffhdrfmt)) coffhdr = struct.unpack(coffhdrfmt, rawcoffhdr) coffhdr_numsections = coffhdr[1] opthdrfmt = 'hbblllllllllhhhhhhllllhhllllll' rawopthdr = f.read(struct.calcsize(opthdrfmt)) opthdr = struct.unpack(opthdrfmt, rawopthdr) opthdr_numrvas = opthdr[-1] datadirs = [] datadirsize = struct.calcsize('ll') # virtual address, size for i in range(opthdr_numrvas): rawdatadir = f.read(datadirsize) datadirs.append(struct.unpack('ll', rawdatadir)) sectionfmt = '8s6l2hl' sectionsize = struct.calcsize(sectionfmt) sections = [] for i in range(coffhdr_numsections): rawsection = f.read(sectionsize) sections.append(struct.unpack(sectionfmt, rawsection)) importva, importsz = datadirs[1] if importsz == 0: return [] # figure out what section it's in NAME, MISC, VIRTADDRESS, RAWSIZE, POINTERTORAW = range(5) for j in range(len(sections)-1): if sections[j][VIRTADDRESS] <= importva < sections[j+1][VIRTADDRESS]: importsection = sections[j] break else: if importva >= sections[-1][VIRTADDRESS]: importsection = sections[-1] else: print "E: import section is unavailable" return [] f.seek(importsection[POINTERTORAW] + importva - importsection[VIRTADDRESS]) data = f.read(importsz) iidescrfmt = 'lllll' CHARACTERISTICS, DATETIME, FWDRCHAIN, NAMERVA, FIRSTTHUNK = range(5) iidescrsz = struct.calcsize(iidescrfmt) dlls = [] while data: iid = struct.unpack(iidescrfmt, data[:iidescrsz]) if iid[NAMERVA] == 0: break f.seek(importsection[POINTERTORAW] + iid[NAMERVA] - importsection[VIRTADDRESS]) nm = f.read(256) nm, jnk = string.split(nm, '\0', 1) if nm: dlls.append(nm) data = data[iidescrsz:] return dlls def Dependencies(lTOC, platform=sys.platform, xtrapath=None, manifest=None): """Expand LTOC to include all the closure of binary dependencies. LTOC is a logical table of contents, ie, a seq of tuples (name, path). Return LTOC expanded by all the binary dependencies of the entries in LTOC, except those listed in the module global EXCLUDES manifest should be a winmanifest.Manifest instance on Windows, so that all dependent assemblies can be added""" for nm, pth, typ in lTOC: if seen.get(string.upper(nm),0): continue if not silent: print "I: Analyzing", pth seen[string.upper(nm)] = 1 if iswin: for ftocnm, fn in selectAssemblies(pth, manifest): lTOC.append((ftocnm, fn, 'BINARY')) for lib, npth in selectImports(pth, platform, xtrapath): if seen.get(string.upper(lib),0) or seen.get(string.upper(npth),0): continue seen[string.upper(npth)] = 1 lTOC.append((lib, npth, 'BINARY')) return lTOC def pkg_resouces_get_default_cache(): """Determine the default cache location This returns the ``PYTHON_EGG_CACHE`` environment variable, if set. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the "Application Data" directory. On all other systems, it's "~/.python-eggs". """ # This function borrowed from setuptools/pkg_resources try: return os.environ['PYTHON_EGG_CACHE'] except KeyError: pass if os.name!='nt': return os.path.expanduser('~/.python-eggs') app_data = 'Application Data' # XXX this may be locale-specific! app_homes = [ (('APPDATA',), None), # best option, should be locale-safe (('USERPROFILE',), app_data), (('HOMEDRIVE','HOMEPATH'), app_data), (('HOMEPATH',), app_data), (('HOME',), None), (('WINDIR',), app_data), # 95/98/ME ] for keys, subdir in app_homes: dirname = '' for key in keys: if key in os.environ: dirname = os.path.join(dirname, os.environ[key]) else: break else: if subdir: dirname = os.path.join(dirname,subdir) return os.path.join(dirname, 'Python-Eggs') else: raise RuntimeError( "Please set the PYTHON_EGG_CACHE enviroment variable" ) def check_extract_from_egg(pth, todir=None): r"""Check if path points to a file inside a python egg file, extract the file from the egg to a cache directory (following pkg_resources convention) and return [(extracted path, egg file path, relative path inside egg file)]. Otherwise, just return [(original path, None, None)]. If path points to an egg file directly, return a list with all files from the egg formatted like above. Example: >>> check_extract_from_egg(r'C:\Python26\Lib\site-packages\my.egg\mymodule\my.pyd') [(r'C:\Users\UserName\AppData\Roaming\Python-Eggs\my.egg-tmp\mymodule\my.pyd', r'C:\Python26\Lib\site-packages\my.egg', r'mymodule/my.pyd')] """ rv = [] if os.path.altsep: pth = pth.replace(os.path.altsep, os.path.sep) components = pth.split(os.path.sep) for i, name in enumerate(components): if name.lower().endswith(".egg"): eggpth = os.path.sep.join(components[:i + 1]) if os.path.isfile(eggpth): # eggs can also be directories! try: egg = zipfile.ZipFile(eggpth) except zipfile.BadZipfile, e: print "E:", eggpth, e sys.exit(1) if todir is None: # Use the same directory as setuptools/pkg_resources. So, # if the specific egg was accessed before (not necessarily # by pyinstaller), the extracted contents already exist # (pkg_resources puts them there) and can be used. todir = os.path.join(pkg_resouces_get_default_cache(), name + "-tmp") if components[i + 1:]: members = ["/".join(components[i + 1:])] else: members = egg.namelist() for member in members: pth = os.path.join(todir, member) if not os.path.isfile(pth): dirname = os.path.dirname(pth) if not os.path.isdir(dirname): os.makedirs(dirname) f = open(pth, "wb") f.write(egg.read(member)) f.close() rv.append((pth, eggpth, member)) return rv return [(pth, None, None)] def getAssemblies(pth): """Return the dependent assemblies of a binary.""" if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if pth.lower().endswith(".manifest"): return [] # check for manifest file manifestnm = pth + ".manifest" if os.path.isfile(manifestnm): fd = open(manifestnm, "rb") res = {RT_MANIFEST: {1: {0: fd.read()}}} fd.close() elif not winresource: # resource access unavailable (needs pywin32) return [] else: # check the binary for embedded manifest try: res = GetManifestResources(pth) except winresource.pywintypes.error, exc: if exc.args[0] == winresource.ERROR_BAD_EXE_FORMAT: if not silent: print 'I: Cannot get manifest resource from non-PE file:' print 'I:', pth return [] raise rv = [] if RT_MANIFEST in res and len(res[RT_MANIFEST]): for name in res[RT_MANIFEST]: for language in res[RT_MANIFEST][name]: # check the manifest for dependent assemblies try: manifest = Manifest() manifest.filename = ":".join([pth, str(RT_MANIFEST), str(name), str(language)]) manifest.parse_string(res[RT_MANIFEST][name][language], False) except Exception, exc: print ("E: Cannot parse manifest resource %s, %s " "from") % (name, language) print "E:", pth print "E:", traceback.print_exc() else: if manifest.dependentAssemblies and not silent: print "I: Dependent assemblies of %s:" % pth print "I:", ", ".join([assembly.getid() for assembly in manifest.dependentAssemblies]) rv.extend(manifest.dependentAssemblies) return rv def selectAssemblies(pth, manifest=None): """Return a binary's dependent assemblies files that should be included. Return a list of pairs (name, fullpath) """ rv = [] if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] for assembly in getAssemblies(pth): if seen.get(assembly.getid().upper(),0): continue if manifest: # Add assembly as dependency to our final output exe's manifest if not assembly.name in [dependentAssembly.name for dependentAssembly in manifest.dependentAssemblies]: print ("Adding %s to dependent assemblies " "of final executable") % assembly.name manifest.dependentAssemblies.append(assembly) if excludesRe.search(assembly.name): if not silent: print "I: Skipping assembly", assembly.getid() continue if assembly.optional: if not silent: print "I: Skipping optional assembly", assembly.getid() continue files = assembly.find_files() if files: seen[assembly.getid().upper()] = 1 for fn in files: fname, fext = os.path.splitext(fn) if fext.lower() == ".manifest": nm = assembly.name + fext else: nm = os.path.basename(fn) ftocnm = nm if assembly.language not in (None, "", "*", "neutral"): ftocnm = os.path.join(assembly.getlanguage(), ftocnm) nm, ftocnm, fn = [item.encode(sys.getfilesystemencoding()) for item in (nm, ftocnm, fn)] if not seen.get(fn.upper(),0): if not silent: print "I: Adding", ftocnm seen[nm.upper()] = 1 seen[fn.upper()] = 1 rv.append((ftocnm, fn)) else: #print "I: skipping", ftocnm, "part of assembly", \ # assembly.name, "dependency of", pth pass else: print "E: Assembly", assembly.getid(), "not found" return rv def selectImports(pth, platform=sys.platform, xtrapath=None): """Return the dependencies of a binary that should be included. Return a list of pairs (name, fullpath) """ rv = [] if xtrapath is None: xtrapath = [os.path.dirname(pth)] else: assert isinstance(xtrapath, list) xtrapath = [os.path.dirname(pth)] + xtrapath # make a copy dlls = getImports(pth, platform=platform) for lib in dlls: if seen.get(string.upper(lib),0): continue if not iswin and not cygwin: # all other platforms npth = lib dir, lib = os.path.split(lib) if excludes.get(dir,0): continue else: # plain win case npth = getfullnameof(lib, xtrapath) # now npth is a candidate lib if found # check again for excludes but with regex FIXME: split the list if npth: candidatelib = npth else: candidatelib = lib if excludesRe.search(candidatelib): if candidatelib.find('libpython') < 0 and \ candidatelib.find('Python.framework') < 0: # skip libs not containing (libpython or Python.framework) if not silent and \ not seen.get(string.upper(npth),0): print "I: Skipping", lib, "dependency of", \ os.path.basename(pth) continue else: pass if npth: if not seen.get(string.upper(npth),0): if not silent: print "I: Adding", lib, "dependency of", \ os.path.basename(pth) rv.append((lib, npth)) else: print "E: lib not found:", lib, "dependency of", pth return rv def _getImports_ldd(pth): """Find the binary dependencies of PTH. This implementation is for ldd platforms""" rslt = [] for line in os.popen('ldd "%s"' % pth).readlines(): m = re.search(r"\s+(.*?)\s+=>\s+(.*?)\s+\(.*\)", line) if m: name, lib = m.group(1), m.group(2) if name[:10] in ('linux-gate', 'linux-vdso'): # linux-gate is a fake library which does not exist and # should be ignored. See also: # http://www.trilithium.com/johan/2005/08/linux-gate/ continue if os.path.exists(lib): rslt.append(lib) else: print 'E: cannot find %s in path %s (needed by %s)' % \ (name, lib, pth) return rslt def _getImports_otool(pth): """Find the binary dependencies of PTH. This implementation is for otool platforms""" # dyld searches these paths for framework libs # we ignore DYLD_FALLBACK_LIBRARY_PATH for now (man dyld) fwpaths = ['/Library/Frameworks', '/Network/Library/Frameworks', '/System/Library/Frameworks'] for p in reversed(os.environ.get('DYLD_FRAMEWORK_PATH', '').split(':')): if p: fwpaths.insert(0, p) rslt = [] for line in os.popen('otool -L "%s"' % pth).readlines(): m = re.search(r"\s+(.*?)\s+\(.*\)", line) if m: lib = m.group(1) if lib.startswith("@executable_path"): rel_path = lib.replace("@executable_path",".") rel_path = os.path.join(os.path.dirname(pth), rel_path) lib = os.path.abspath(rel_path) elif lib.startswith("@loader_path"): rel_path = lib.replace("@loader_path",".") rel_path = os.path.join(os.path.dirname(pth), rel_path) lib = os.path.abspath(rel_path) elif not os.path.isabs(lib): # lookup matching framework path, if relative pathname for p in fwpaths: fwlib = os.path.join(p, lib) if os.path.exists(fwlib): lib = fwlib break if os.path.exists(lib): rslt.append(lib) else: print 'E: cannot find path %s (needed by %s)' % \ (lib, pth) return rslt def getImports(pth, platform=sys.platform): """Forwards to the correct getImports implementation for the platform. """ if not os.path.isfile(pth): pth = check_extract_from_egg(pth)[0][0] if platform[:3] == 'win' or platform == 'cygwin': if pth.lower().endswith(".manifest"): return [] try: return _getImports_pe_lib_pefile(pth) except Exception, exception: # Assemblies can pull in files which aren't necessarily PE, # but are still needed by the assembly. Any additional binary # dependencies should already have been handled by # selectAssemblies in that case, so just warn, return an empty # list and continue. if not silent: print 'W: Cannot get binary dependencies for file:' print 'W:', pth print 'W:', traceback.print_exc() return [] elif platform == 'darwin': return _getImports_otool(pth) else: return _getImports_ldd(pth) def getWindowsPath(): """Return the path that Windows will search for dlls.""" global _bpath if _bpath is None: _bpath = [] if iswin: try: import win32api except ImportError: print "W: Cannot determine your Windows or System directories" print "W: Please add them to your PATH if .dlls are not found" print "W: or install http://sourceforge.net/projects/pywin32/" else: sysdir = win32api.GetSystemDirectory() sysdir2 = os.path.normpath(os.path.join(sysdir, '..', 'SYSTEM')) windir = win32api.GetWindowsDirectory() _bpath = [sysdir, sysdir2, windir] _bpath.extend(string.split(os.environ.get('PATH', ''), os.pathsep)) return _bpath def findLibrary(name): """Look for a library in the system. Emulate the algorithm used by dlopen. `name`must include the prefix, e.g. ``libpython2.4.so`` """ assert sys.platform == 'linux2', "Current implementation for Linux only" lib = None # Look in the LD_LIBRARY_PATH lp = os.environ.get('LD_LIBRARY_PATH') if lp: for path in string.split(lp, os.pathsep): libs = glob(os.path.join(path, name + '*')) if libs: lib = libs[0] break # Look in /etc/ld.so.cache if lib is None: expr = r'/[^\(\)\s]*%s\.[^\(\)\s]*' % re.escape(name) m = re.search(expr, os.popen('/sbin/ldconfig -p 2>/dev/null').read()) if m: lib = m.group(0) # Look in the known safe paths if lib is None: for path in ['/lib', '/usr/lib']: libs = glob(os.path.join(path, name + '*')) if libs: lib = libs[0] break # give up :( if lib is None: return None # Resolve the file name into the soname dir, file = os.path.split(lib) return os.path.join(dir, getSoname(lib)) def getSoname(filename): """Return the soname of a library.""" cmd = "objdump -p -j .dynamic 2>/dev/null " + filename m = re.search(r'\s+SONAME\s+([^\s]+)', os.popen(cmd).read()) if m: return m.group(1) if __name__ == "__main__": from pyi_optparse import OptionParser parser = OptionParser(usage="%prog [options] <executable_or_dynamic_library>") parser.add_option('--target-platform', default=sys.platform, help='Target platform, required for cross-bundling (default: current platform)') opts, args = parser.parse_args() silent = True # Suppress all informative messages from the dependency code import glob for a in args: for fn in glob.glob(a): imports = getImports(fn, opts.target_platform) if opts.target_platform == "win32": imports.extend([a.getid() for a in getAssemblies(fn)]) print fn, imports
Python
#! /usr/bin/env python # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import versionInfo import sys if len(sys.argv) < 2: print "Usage: >python GrabVersion.py <exe>" print " where: <exe> is the fullpathname of a Windows executable." print " The printed output may be saved to a file, editted and " print " used as the input for a verion resource on any of the " print " executable targets in an Installer config file." print " Note that only NT / Win2K can set version resources." else: vs = versionInfo.decode(sys.argv[1]) print vs
Python
#!/usr/bin/env python """ Suffix definitions for cross platform builds. """ # Copyright (C) 2008 Hartmut Goebel <h.goebel@goebel-consult.de> # Licence: GNU General Public License version 3 (GPL v3) # # This file is part of PyInstaller <http://www.pyinstaller.org> # # pyinstaller is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # pyinstaller is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import imp import sys __all__ = ['get_suffixes'] # todo: complete this list for all available platforms SUFFIXES = { 'win32': ( (".py", "U", imp.PY_SOURCE), (".pyw", "U", imp.PY_SOURCE), (".pyc", "rb", imp.PY_COMPILED), (__debug__ and "_d.pyd" or ".pyd", "rb", imp.C_EXTENSION), (__debug__ and "_d.dll" or ".dll", "rb", imp.C_EXTENSION), ), } def get_suffixes(target_platform=None): if target_platform == sys.platform: return imp.get_suffixes() # per default use the values from imp.get_suffixes return SUFFIXES.get(target_platform, None) or imp.get_suffixes()
Python
#!/usr/bin/env python # # Automatically build spec files containing a description of the project # # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys, os, string # For Python 1.5 compatibility try: True, False except: True = 1 == 1 False = not True freezetmplt = """# -*- mode: python -*- a = Analysis(%(scripts)s, pathex=%(pathex)s) pyz = PYZ(a.pure) exe = EXE(%(tkpkg)s pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name=os.path.join(%(distdir)s, '%(exename)s'), debug=%(debug)s, strip=%(strip)s, upx=%(upx)s, console=%(console)s %(exe_options)s) """ # pathex scripts exename tkpkg debug console distdir collecttmplt = """# -*- mode: python -*- a = Analysis(%(scripts)s, pathex=%(pathex)s) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join(%(builddir)s, '%(exename)s'), debug=%(debug)s, strip=%(strip)s, upx=%(upx)s, console=%(console)s %(exe_options)s) coll = COLLECT(%(tktree)s exe, a.binaries, a.zipfiles, a.datas, strip=%(strip)s, upx=%(upx)s, name=os.path.join(%(distdir)s, '%(name)s')) """ # scripts pathex, exename, debug, console tktree distdir name comsrvrtmplt = """# -*- mode: python -*- a = Analysis(%(scripts)s, pathex=%(pathex)s) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, exclude_binaries=1, name=os.path.join(%(builddir)s, '%(exename)s'), debug=%(debug)s, strip=%(strip)s, upx=%(upx)s, console=%(console)s %(exe_options)s) dll = DLL(pyz, a.scripts, exclude_binaries=1, name=os.path.join(%(builddir)s, '%(dllname)s'), debug=%(debug)s) coll = COLLECT(exe, dll, a.binaries, a.zipfiles, a.datas, strip=%(strip)s, upx=%(upx)s, name=os.path.join(%(distdir)s, '%(name)s')) """ # scripts pathex, exename, debug, console tktree distdir name bundleexetmplt = """app = BUNDLE(exe, name=os.path.join(%(distdir)s, '%(exename)s.app')) """ # distdir exename bundletmplt = """app = BUNDLE(coll, name=os.path.join(%(distdir)s, '%(name)s.app')) """ # distdir name HOME = os.path.dirname(sys.argv[0]) HOME = os.path.abspath(HOME) def quote_win_filepath( path ): # quote all \ with another \ after using normpath to clean up the path return string.join( string.split( os.path.normpath( path ), '\\' ), '\\\\' ) # Support for trying to avoid hard-coded paths in the .spec files. # Eg, all files rooted in the Installer directory tree will be # written using "HOMEPATH", thus allowing this spec file to # be used with any Installer installation. # Same thing could be done for other paths too. path_conversions = ( (HOME, "HOMEPATH"), # Add Tk etc? ) def make_variable_path(filename, conversions = path_conversions): for (from_path, to_name) in conversions: assert os.path.abspath(from_path)==from_path, \ "path '%s' should already be absolute" % (from_path,) if filename[:len(from_path)] == from_path: rest = filename[len(from_path):] if rest[0] in "\\/": rest = rest[1:] return to_name, rest return None, filename # An object used in place of a "path string" which knows how to repr() # itself using variable names instead of hard-coded paths. class Path: def __init__(self, *parts): self.path = apply(os.path.join, parts) self.variable_prefix = self.filename_suffix = None def __repr__(self): if self.filename_suffix is None: self.variable_prefix, self.filename_suffix = make_variable_path(self.path) if self.variable_prefix is None: return repr(self.path) return "os.path.join(" + self.variable_prefix + "," + repr(self.filename_suffix) + ")" def main(scripts, configfile=None, name=None, tk=0, freeze=0, console=1, debug=0, strip=0, upx=0, comserver=0, ascii=0, workdir=None, pathex=[], version_file=None, icon_file=None, manifest=None, resources=[], crypt=None, **kwargs): try: config = eval(open(configfile, 'r').read()) except IOError: raise SystemExit("Configfile is missing or unreadable. Please run Configure.py before building!") if config['pythonVersion'] != sys.version: print "The current version of Python is not the same with which PyInstaller was configured." print "Please re-run Configure.py with this version." raise SystemExit(1) if not name: name = os.path.splitext(os.path.basename(scripts[0]))[0] distdir = "dist" builddir = os.path.join('build', 'pyi.' + config['target_platform'], name) pathex = pathex[:] if workdir is None: workdir = os.getcwd() pathex.append(workdir) else: pathex.append(os.getcwd()) if workdir == HOME: workdir = os.path.join(HOME, name) if not os.path.exists(workdir): os.makedirs(workdir) exe_options = '' if version_file: exe_options = "%s, version='%s'" % (exe_options, quote_win_filepath(version_file)) if icon_file: exe_options = "%s, icon='%s'" % (exe_options, quote_win_filepath(icon_file)) if manifest: if "<" in manifest: # Assume XML string exe_options = "%s, manifest='%s'" % (exe_options, manifest.replace("'", "\\'")) else: # Assume filename exe_options = "%s, manifest='%s'" % (exe_options, quote_win_filepath(manifest)) if resources: for i in range(len(resources)): resources[i] = quote_win_filepath(resources[i]) exe_options = "%s, resources=%s" % (exe_options, repr(resources)) if not ascii and config['hasUnicode']: scripts.insert(0, os.path.join(HOME, 'support', 'useUnicode.py')) for i in range(len(scripts)): scripts[i] = Path(scripts[i]) # Use relative path in specfiles d = {'tktree':'', 'tkpkg' :'', 'scripts':scripts, 'pathex' :pathex, #'exename': '', 'name': name, 'distdir': repr(distdir), 'builddir': repr(builddir), 'debug': debug, 'strip': strip, 'upx' : upx, 'crypt' : repr(crypt), 'crypted': crypt is not None, 'console': console or debug, 'exe_options': exe_options} if tk: d['tktree'] = "TkTree()," if freeze: scripts.insert(0, Path(HOME, 'support', 'useTK.py')) scripts.insert(0, Path(HOME, 'support', 'unpackTK.py')) scripts.append(Path(HOME, 'support', 'removeTK.py')) d['tkpkg'] = "TkPKG()," else: scripts.insert(0, Path(HOME, 'support', 'useTK.py')) scripts.insert(0, Path(HOME, 'support', '_mountzlib.py')) if config['target_platform'][:3] == "win" or \ config['target_platform'] == 'cygwin': d['exename'] = name+'.exe' d['dllname'] = name+'.dll' else: d['exename'] = name # only Windows and Mac OS X distinguish windowed and console apps if not config['target_platform'][:3] == "win" and \ not config['target_platform'].startswith('darwin'): d['console'] = 1 specfnm = os.path.join(workdir, name+'.spec') specfile = open(specfnm, 'w') if freeze: specfile.write(freezetmplt % d) if not console: specfile.write(bundleexetmplt % d) elif comserver: specfile.write(comsrvrtmplt % d) if not console: specfile.write(bundletmplt % d) else: specfile.write(collecttmplt % d) if not console: specfile.write(bundletmplt % d) specfile.close() return specfnm if __name__ == '__main__': import pyi_optparse as optparse p = optparse.OptionParser( usage="python %prog [opts] <scriptname> [<scriptname> ...]" ) p.add_option('-C', '--configfile', default=os.path.join(HOME, 'config.dat'), help='Name of configfile (default: %default)') g = p.add_option_group('What to generate') g.add_option("-F", "--onefile", dest="freeze", action="store_true", default=False, help="create a single file deployment") g.add_option("-D", "--onedir", dest="freeze", action="store_false", help="create a single directory deployment (default)") g.add_option("-o", "--out", type="string", default=None, dest="workdir", metavar="DIR", help="generate the spec file in the specified directory " "(default: current directory") g.add_option("-n", "--name", type="string", default=None, metavar="NAME", help="name to assign to the project " "(default: first script's basename)") g = p.add_option_group('What to bundle, where to search') g.add_option("-p", "--paths", type="string", default=[], dest="pathex", metavar="DIR", action="append", help="set base path for import (like using PYTHONPATH). " "Multiple directories are allowed, separating them " "with %s, or using this option multiple times" % repr(os.pathsep)) g.add_option("-K", "--tk", default=False, action="store_true", help="include TCL/TK in the deployment") g.add_option("-a", "--ascii", action="store_true", default=False, help="do NOT include unicode encodings " "(default: included if available)") g = p.add_option_group('How to generate') g.add_option("-d", "--debug", action="store_true", default=False, help="use the debug (verbose) build of the executable") g.add_option("-s", "--strip", action="store_true", default=False, help="strip the exe and shared libs " "(don't try this on Windows)") g.add_option("-X", "--upx", action="store_true", default=True, help="use UPX if available (works differently between " "Windows and *nix)") #p.add_option("-Y", "--crypt", type="string", default=None, metavar="FILE", # help="encrypt pyc/pyo files") g = p.add_option_group('Windows and Mac OS X specific options') g.add_option("-c", "--console", "--nowindowed", dest="console", action="store_true", help="use a console subsystem executable" "(default)") g.add_option("-w", "--windowed", "--noconsole", dest="console", action="store_false", default=True, help="use a Windows subsystem executable") g = p.add_option_group('Windows specific options') g.add_option("-v", "--version", type="string", dest="version_file", metavar="FILE", help="add a version resource from FILE to the exe ") g.add_option("-i", "--icon", type="string", dest="icon_file", metavar="FILE.ICO or FILE.EXE,ID", help="If FILE is an .ico file, add the icon to the final " "executable. Otherwise, the syntax 'file.exe,id' to " "extract the icon with the specified id " "from file.exe and add it to the final executable") g.add_option("-m", "--manifest", type="string", dest="manifest", metavar="FILE or XML", help="add manifest FILE or XML to the exe ") g.add_option("-r", "--resource", type="string", default=[], dest="resources", metavar="FILE[,TYPE[,NAME[,LANGUAGE]]]", action="append", help="add/update resource of the given type, name and language " "from FILE to the final executable. FILE can be a " "data file or an exe/dll. For data files, atleast " "TYPE and NAME need to be specified, LANGUAGE defaults " "to 0 or may be specified as wildcard * to update all " "resources of the given TYPE and NAME. For exe/dll " "files, all resources from FILE will be added/updated " "to the final executable if TYPE, NAME and LANGUAGE " "are omitted or specified as wildcard *." "Multiple resources are allowed, using this option " "multiple times.") opts,args = p.parse_args() # Split pathex by using the path separator temppaths = opts.pathex[:] opts.pathex = [] for p in temppaths: opts.pathex.extend(string.split(p, os.pathsep)) if not args: p.error('Requires at least one scriptname file') name = apply(main, (args,), opts.__dict__) print "wrote %s" % name print "now run Build.py to build the executable"
Python
# # Copyright (C) 2005, Giovanni Bajo # # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # import sys, string, os, imp, marshal, dircache, glob try: # zipimport is supported starting with Python 2.3 import zipimport except ImportError: zipimport = None try: # if ctypes is present, we can enable specific dependency discovery import ctypes from ctypes.util import find_library except ImportError: ctypes = None import suffixes try: STRINGTYPE = basestring except NameError: STRINGTYPE = type("") if not os.environ.has_key('PYTHONCASEOK') and sys.version_info >= (2, 1): def caseOk(filename): files = dircache.listdir(os.path.dirname(filename)) return os.path.basename(filename) in files else: def caseOk(filename): return True def pyco(): """ Returns correct extension ending: 'c' or 'o' """ if __debug__: return 'c' else: return 'o' #=======================Owners==========================# # An Owner does imports from a particular piece of turf # That is, there's an Owner for each thing on sys.path # There are owners for directories and .pyz files. # There could be owners for zip files, or even URLs. # Note that they replace the string in sys.path, # but str(sys.path[n]) should yield the original string. class OwnerError(Exception): pass class Owner: def __init__(self, path, target_platform=None): self.path = path self.target_platform = target_platform def __str__(self): return self.path def getmod(self, nm): return None class BaseDirOwner(Owner): def _getsuffixes(self): return suffixes.get_suffixes(self.target_platform) def getmod(self, nm, getsuffixes=None, loadco=marshal.loads): if getsuffixes is None: getsuffixes = self._getsuffixes possibles = [(nm, 0, None)] if self._isdir(nm) and self._caseok(nm): possibles.insert(0, (os.path.join(nm, '__init__'), 1, nm)) py = pyc = None for pth, ispkg, pkgpth in possibles: for ext, mode, typ in getsuffixes(): attempt = pth+ext modtime = self._modtime(attempt) if modtime is not None: # Check case if not self._caseok(attempt): continue if typ == imp.C_EXTENSION: #print "DirOwner.getmod -> ExtensionModule(%s, %s)" % (nm, attempt) return ExtensionModule(nm, os.path.join(self.path,attempt)) elif typ == imp.PY_SOURCE: py = (attempt, modtime) else: pyc = (attempt, modtime) if py or pyc: break if py is None and pyc is None: #print "DirOwner.getmod -> (py == pyc == None)" return None while 1: # If we have no pyc or py is newer if pyc is None or py and pyc[1] < py[1]: try: stuff = self._read(py[0])+'\n' co = compile(string.replace(stuff, "\r\n", "\n"), py[0], 'exec') pth = py[0] + pyco() break except SyntaxError, e: print "Syntax error in", py[0] print e.args raise elif pyc: stuff = self._read(pyc[0]) # If this file was not generated for this version of # Python, we need to regenerate it. if stuff[:4] != imp.get_magic(): print "W: wrong version .pyc found (%s), will use .py" % pyc[0] pyc = None continue try: co = loadco(stuff[8:]) pth = pyc[0] break except (ValueError, EOFError): print "W: bad .pyc found (%s), will use .py" % pyc[0] pyc = None else: #print "DirOwner.getmod while 1 -> None" return None pth = os.path.join(self.path, pth) if not os.path.isabs(pth): pth = os.path.abspath(pth) if ispkg: mod = self._pkgclass()(nm, pth, co) else: mod = self._modclass()(nm, pth, co) #print "DirOwner.getmod -> %s" % mod return mod class DirOwner(BaseDirOwner): def __init__(self, path, target_platform=None): if path == '': path = os.getcwd() if not os.path.isdir(path): raise OwnerError("%s is not a directory" % repr(path)) Owner.__init__(self, path, target_platform) def _isdir(self, fn): return os.path.isdir(os.path.join(self.path, fn)) def _modtime(self, fn): try: return os.stat(os.path.join(self.path, fn))[8] except OSError: return None def _read(self, fn): return open(os.path.join(self.path, fn), 'rb').read() def _pkgclass(self): return PkgModule def _modclass(self): return PyModule def _caseok(self, fn): return caseOk(os.path.join(self.path, fn)) class PYZOwner(Owner): def __init__(self, path, target_platform=None): import archive self.pyz = archive.ZlibArchive(path) Owner.__init__(self, path, target_platform) def getmod(self, nm): rslt = self.pyz.extract(nm) if not rslt: return None ispkg, co = rslt if ispkg: return PkgInPYZModule(nm, co, self) return PyModule(nm, self.path, co) ZipOwner = None if zipimport: # We cannot use zipimporter here because it has a stupid bug: # # >>> z.find_module("setuptools.setuptools.setuptools.setuptools.setuptools") is not None # True # # So mf will go into infinite recursion. # Instead, we'll reuse the BaseDirOwner logic, simply changing # the template methods. class ZipOwner(BaseDirOwner): def __init__(self, path, target_platform=None): import zipfile try: self.zf = zipfile.ZipFile(path, "r") except IOError: raise OwnerError("%s is not a zipfile" % path) Owner.__init__(self, path, target_platform) def getmod(self, fn): fn = fn.replace(".", "/") return BaseDirOwner.getmod(self, fn) def _modtime(self, fn): fn = fn.replace("\\","/") try: dt = self.zf.getinfo(fn).date_time return dt except KeyError: return None def _isdir(self, fn): # No way to find out if "fn" is a directory # so just always look into it in case it is. return True def _caseok(self, fn): # zipfile is always case-sensitive, so surely # there is no case mismatch. return True def _read(self, fn): # zipfiles always use forward slashes fn = fn.replace("\\","/") return self.zf.read(fn) def _pkgclass(self): return lambda *args: PkgInZipModule(self, *args) def _modclass(self): return lambda *args: PyInZipModule(self, *args) _globalownertypes = filter(None, [ DirOwner, ZipOwner, PYZOwner, Owner, ]) #===================Import Directors====================================# # ImportDirectors live on the metapath # There's one for builtins, one for frozen modules, and one for sys.path # Windows gets one for modules gotten from the Registry # There should be one for Frozen modules # Mac would have them for PY_RESOURCE modules etc. # A generalization of Owner - their concept of "turf" is broader class ImportDirector(Owner): pass class BuiltinImportDirector(ImportDirector): def __init__(self): self.path = 'Builtins' def getmod(self, nm, isbuiltin=imp.is_builtin): if isbuiltin(nm): return BuiltinModule(nm) return None class FrozenImportDirector(ImportDirector): def __init__(self): self.path = 'FrozenModules' def getmod(self, nm, isfrozen=imp.is_frozen): if isfrozen(nm): return FrozenModule(nm) return None class RegistryImportDirector(ImportDirector): # for Windows only def __init__(self): self.path = "WindowsRegistry" self.map = {} try: import win32api import win32con except ImportError: pass else: subkey = r"Software\Python\PythonCore\%s\Modules" % sys.winver for root in (win32con.HKEY_CURRENT_USER, win32con.HKEY_LOCAL_MACHINE): try: #hkey = win32api.RegOpenKeyEx(root, subkey, 0, win32con.KEY_ALL_ACCESS) hkey = win32api.RegOpenKeyEx(root, subkey, 0, win32con.KEY_READ) except Exception, e: #print "RegistryImportDirector", e pass else: numsubkeys, numvalues, lastmodified = win32api.RegQueryInfoKey(hkey) for i in range(numsubkeys): subkeyname = win32api.RegEnumKey(hkey, i) #hskey = win32api.RegOpenKeyEx(hkey, subkeyname, 0, win32con.KEY_ALL_ACCESS) hskey = win32api.RegOpenKeyEx(hkey, subkeyname, 0, win32con.KEY_READ) val = win32api.RegQueryValueEx(hskey, '') desc = getDescr(val[0]) #print " RegistryImportDirector got %s %s" % (val[0], desc) #XXX self.map[subkeyname] = (val[0], desc) hskey.Close() hkey.Close() break def getmod(self, nm): stuff = self.map.get(nm) if stuff: fnm, (suffix, mode, typ) = stuff if typ == imp.C_EXTENSION: return ExtensionModule(nm, fnm) elif typ == imp.PY_SOURCE: try: stuff = open(fnm, 'r').read()+'\n' co = compile(string.replace(stuff, "\r\n", "\n"), fnm, 'exec') except SyntaxError, e: print "Invalid syntax in %s" % py[0] print e.args raise else: stuff = open(fnm, 'rb').read() co = loadco(stuff[8:]) return PyModule(nm, fnm, co) return None class PathImportDirector(ImportDirector): def __init__(self, pathlist=None, importers=None, ownertypes=None, target_platform=None): if pathlist is None: self.path = sys.path else: self.path = pathlist if ownertypes == None: self.ownertypes = _globalownertypes else: self.ownertypes = ownertypes if importers: self.shadowpath = importers else: self.shadowpath = {} self.inMakeOwner = 0 self.building = {} self.target_platform = target_platform def __str__(self): return str(self.path) def getmod(self, nm): mod = None for thing in self.path: if isinstance(thing, STRINGTYPE): owner = self.shadowpath.get(thing, -1) if owner == -1: owner = self.shadowpath[thing] = self.makeOwner(thing) if owner: mod = owner.getmod(nm) else: mod = thing.getmod(nm) if mod: break return mod def makeOwner(self, path): if self.building.get(path): return None self.building[path] = 1 owner = None for klass in self.ownertypes: try: # this may cause an import, which may cause recursion # hence the protection owner = klass(path, self.target_platform) except OwnerError: pass except Exception, e: #print "FIXME: Wrong exception", e pass else: break del self.building[path] return owner def getDescr(fnm): ext = os.path.splitext(fnm)[1] for (suffix, mode, typ) in imp.get_suffixes(): if suffix == ext: return (suffix, mode, typ) #=================Import Tracker============================# # This one doesn't really import, just analyzes # If it *were* importing, it would be the one-and-only ImportManager # ie, the builtin import UNTRIED = -1 imptyps = ['top-level', 'conditional', 'delayed', 'delayed, conditional'] import hooks if __debug__: import sys import UserDict class LogDict(UserDict.UserDict): count = 0 def __init__(self, *args): UserDict.UserDict.__init__(self, *args) LogDict.count += 1 self.logfile = open("logdict%s-%d.log" % (".".join(map(str, sys.version_info)), LogDict.count), "w") def __setitem__(self, key, value): self.logfile.write("%s: %s -> %s\n" % (key, self.data.get(key), value)) UserDict.UserDict.__setitem__(self, key, value) def __delitem__(self, key): self.logfile.write(" DEL %s\n" % key) UserDict.UserDict.__delitem__(self, key) else: LogDict = dict class ImportTracker: # really the equivalent of builtin import def __init__(self, xpath=None, hookspath=None, excludes=None, target_platform=None): self.path = [] self.warnings = {} if xpath: self.path = xpath self.path.extend(sys.path) self.modules = LogDict() self.metapath = [ BuiltinImportDirector(), FrozenImportDirector(), RegistryImportDirector(), PathImportDirector(self.path, target_platform=target_platform) ] if hookspath: hooks.__path__.extend(hookspath) self.excludes = excludes if excludes is None: self.excludes = [] self.target_platform = target_platform def analyze_r(self, nm, importernm=None): importer = importernm if importer is None: importer = '__main__' seen = {} nms = self.analyze_one(nm, importernm) nms = map(None, nms, [importer]*len(nms)) i = 0 while i < len(nms): nm, importer = nms[i] if seen.get(nm,0): del nms[i] mod = self.modules[nm] if mod: mod.xref(importer) else: i = i + 1 seen[nm] = 1 j = i mod = self.modules[nm] if mod: mod.xref(importer) for name, isdelayed, isconditional, level in mod.imports: imptyp = isdelayed * 2 + isconditional newnms = self.analyze_one(name, nm, imptyp, level) newnms = map(None, newnms, [nm]*len(newnms)) nms[j:j] = newnms j = j + len(newnms) return map(lambda a: a[0], nms) def analyze_one(self, nm, importernm=None, imptyp=0, level=-1): #print '## analyze_one', nm, importernm, imptyp, level # break the name being imported up so we get: # a.b.c -> [a, b, c] ; ..z -> ['', '', z] if not nm: nm = importernm importernm = None level = 0 nmparts = string.split(nm, '.') if level < 0: # behaviour up to Python 2.4 (and default in Python 2.5) # first see if we could be importing a relative name contexts = [None] if importernm: if self.ispackage(importernm): contexts.insert(0, importernm) else: pkgnm = string.join(string.split(importernm, '.')[:-1], '.') if pkgnm: contexts.insert(0, pkgnm) elif level == 0: # absolute import, do not try relative importernm = None contexts = [None] elif level > 0: # relative import, do not try absolute if self.ispackage(importernm): level -= 1 if level > 0: importernm = string.join(string.split(importernm, '.')[:-level], ".") contexts = [importernm, None] importernm = None _all = None assert contexts # so contexts is [pkgnm, None] or just [None] if nmparts[-1] == '*': del nmparts[-1] _all = [] nms = [] for context in contexts: ctx = context for i in range(len(nmparts)): nm = nmparts[i] if ctx: fqname = ctx + '.' + nm else: fqname = nm mod = self.modules.get(fqname, UNTRIED) if mod is UNTRIED: mod = self.doimport(nm, ctx, fqname) if mod: nms.append(mod.__name__) ctx = fqname else: break else: # no break, point i beyond end i = i + 1 if i: break # now nms is the list of modules that went into sys.modules # just as result of the structure of the name being imported # however, each mod has been scanned and that list is in mod.imports if i<len(nmparts): if ctx: if hasattr(self.modules[ctx], nmparts[i]): return nms if not self.ispackage(ctx): return nms self.warnings["W: no module named %s (%s import by %s)" % (fqname, imptyps[imptyp], importernm or "__main__")] = 1 if self.modules.has_key(fqname): del self.modules[fqname] return nms if _all is None: return nms bottommod = self.modules[ctx] if bottommod.ispackage(): for nm in bottommod._all: if not hasattr(bottommod, nm): mod = self.doimport(nm, ctx, ctx+'.'+nm) if mod: nms.append(mod.__name__) else: bottommod.warnings.append("W: name %s not found" % nm) return nms def analyze_script(self, fnm): try: stuff = open(fnm, 'r').read()+'\n' co = compile(string.replace(stuff, "\r\n", "\n"), fnm, 'exec') except SyntaxError, e: print "Invalid syntax in %s" % fnm print e.args raise mod = PyScript(fnm, co) self.modules['__main__'] = mod return self.analyze_r('__main__') def ispackage(self, nm): return self.modules[nm].ispackage() def doimport(self, nm, ctx, fqname): #print "doimport", nm, ctx, fqname # Not that nm is NEVER a dotted name at this point assert ("." not in nm), nm if fqname in self.excludes: return None if ctx: parent = self.modules[ctx] if parent.ispackage(): mod = parent.doimport(nm) if mod: # insert the new module in the parent package # FIXME why? setattr(parent, nm, mod) else: # if parent is not a package, there is nothing more to do return None else: # now we're dealing with an absolute import # try to import nm using available directors for director in self.metapath: mod = director.getmod(nm) if mod: break # here we have `mod` from: # mod = parent.doimport(nm) # or # mod = director.getmod(nm) if mod: mod.__name__ = fqname self.modules[fqname] = mod # now look for hooks # this (and scan_code) are instead of doing "exec co in mod.__dict__" try: hookmodnm = 'hook-'+fqname hooks = __import__('hooks', globals(), locals(), [hookmodnm]) hook = getattr(hooks, hookmodnm) except AttributeError: pass else: # rearranged so that hook() has a chance to mess with hiddenimports & attrs if hasattr(hook, 'hook'): mod = hook.hook(mod) if hasattr(hook, 'hiddenimports'): for impnm in hook.hiddenimports: mod.imports.append((impnm, 0, 0, -1)) if hasattr(hook, 'attrs'): for attr, val in hook.attrs: setattr(mod, attr, val) if hasattr(hook, 'datas'): # hook.datas is a list of globs of files or directories to bundle # as datafiles. For each glob, a destination directory is specified. for g,dest_dir in hook.datas: if dest_dir: dest_dir += "/" for fn in glob.glob(g): if os.path.isfile(fn): mod.datas.append((dest_dir + os.path.basename(fn), fn, 'DATA')) else: def visit((base,dest_dir,datas), dirname, names): for fn in names: fn = os.path.join(dirname, fn) if os.path.isfile(fn): datas.append((dest_dir + fn[len(base)+1:], fn, 'DATA')) os.path.walk(fn, visit, (os.path.dirname(fn),dest_dir,mod.datas)) if fqname != mod.__name__: print "W: %s is changing it's name to %s" % (fqname, mod.__name__) self.modules[mod.__name__] = mod else: assert (mod == None), mod self.modules[fqname] = None # should be equivalent using only one # self.modules[fqname] = mod # here return mod def getwarnings(self): warnings = self.warnings.keys() for nm,mod in self.modules.items(): if mod: for w in mod.warnings: warnings.append(w+' - %s (%s)' % (mod.__name__, mod.__file__)) return warnings def getxref(self): mods = self.modules.items() # (nm, mod) mods.sort() rslt = [] for nm, mod in mods: if mod: importers = mod._xref.keys() importers.sort() rslt.append((nm, importers)) return rslt #====================Modules============================# # All we're doing here is tracking, not importing # If we were importing, these would be hooked to the real module objects class Module: _ispkg = 0 typ = 'UNKNOWN' def __init__(self, nm): self.__name__ = nm self.__file__ = None self._all = [] self.imports = [] self.warnings = [] self.binaries = [] self.datas = [] self._xref = {} def ispackage(self): return self._ispkg def doimport(self, nm): pass def xref(self, nm): self._xref[nm] = 1 def __str__(self): return "<Module %s %s imports=%s binaries=%s datas=%s>" % \ (self.__name__, self.__file__, self.imports, self.binaries, self.datas) class BuiltinModule(Module): typ = 'BUILTIN' def __init__(self, nm): Module.__init__(self, nm) class ExtensionModule(Module): typ = 'EXTENSION' def __init__(self, nm, pth): Module.__init__(self, nm) self.__file__ = pth class PyModule(Module): typ = 'PYMODULE' def __init__(self, nm, pth, co): Module.__init__(self, nm) self.co = co self.__file__ = pth if os.path.splitext(self.__file__)[1] == '.py': self.__file__ = self.__file__ + pyco() self.scancode() def scancode(self): self.imports, self.warnings, self.binaries, allnms = scan_code(self.co) if allnms: self._all = allnms if ctypes and self.binaries: self.binaries = _resolveCtypesImports(self.binaries) class PyScript(PyModule): typ = 'PYSOURCE' def __init__(self, pth, co): Module.__init__(self, '__main__') self.co = co self.__file__ = pth self.scancode() class PkgModule(PyModule): typ = 'PYMODULE' def __init__(self, nm, pth, co): PyModule.__init__(self, nm, pth, co) self._ispkg = 1 pth = os.path.dirname(pth) self.__path__ = [ pth ] self._update_director(force=True) def _update_director(self, force=False): if force or self.subimporter.path != self.__path__: self.subimporter = PathImportDirector(self.__path__) def doimport(self, nm): self._update_director() mod = self.subimporter.getmod(nm) if mod: mod.__name__ = self.__name__ + '.' + mod.__name__ return mod class PkgInPYZModule(PyModule): def __init__(self, nm, co, pyzowner): PyModule.__init__(self, nm, co.co_filename, co) self._ispkg = 1 self.__path__ = [ str(pyzowner) ] self.owner = pyzowner def doimport(self, nm): mod = self.owner.getmod(self.__name__ + '.' + nm) return mod class PyInZipModule(PyModule): typ = 'ZIPFILE' def __init__(self, zipowner, nm, pth, co): PyModule.__init__(self, nm, co.co_filename, co) self.owner = zipowner class PkgInZipModule(PyModule): typ = 'ZIPFILE' def __init__(self, zipowner, nm, pth, co): PyModule.__init__(self, nm, co.co_filename, co) self._ispkg = 1 self.__path__ = [ str(zipowner) ] self.owner = zipowner def doimport(self, nm): mod = self.owner.getmod(self.__name__ + '.' + nm) return mod #======================== Utility ================================# # Scan the code object for imports, __all__ and wierd stuff import dis IMPORT_NAME = dis.opname.index('IMPORT_NAME') IMPORT_FROM = dis.opname.index('IMPORT_FROM') try: IMPORT_STAR = dis.opname.index('IMPORT_STAR') except: IMPORT_STAR = 999 STORE_NAME = dis.opname.index('STORE_NAME') STORE_FAST = dis.opname.index('STORE_FAST') STORE_GLOBAL = dis.opname.index('STORE_GLOBAL') try: STORE_MAP = dis.opname.index('STORE_MAP') except: STORE_MAP = 999 LOAD_GLOBAL = dis.opname.index('LOAD_GLOBAL') LOAD_ATTR = dis.opname.index('LOAD_ATTR') LOAD_NAME = dis.opname.index('LOAD_NAME') EXEC_STMT = dis.opname.index('EXEC_STMT') try: SET_LINENO = dis.opname.index('SET_LINENO') except ValueError: SET_LINENO = 999 BUILD_LIST = dis.opname.index('BUILD_LIST') LOAD_CONST = dis.opname.index('LOAD_CONST') if getattr(sys, 'version_info', (0,0,0)) > (2,5,0): LOAD_CONST_level = LOAD_CONST else: LOAD_CONST_level = 999 if getattr(sys, 'version_info', (0,0,0)) >= (2,7,0): COND_OPS = [dis.opname.index('POP_JUMP_IF_TRUE'), dis.opname.index('POP_JUMP_IF_FALSE'), dis.opname.index('JUMP_IF_TRUE_OR_POP'), dis.opname.index('JUMP_IF_FALSE_OR_POP'), ] else: COND_OPS = [dis.opname.index('JUMP_IF_FALSE'), dis.opname.index('JUMP_IF_TRUE'), ] JUMP_FORWARD = dis.opname.index('JUMP_FORWARD') try: STORE_DEREF = dis.opname.index('STORE_DEREF') except ValueError: STORE_DEREF = 999 STORE_OPS = [STORE_NAME, STORE_FAST, STORE_GLOBAL, STORE_DEREF, STORE_MAP] #IMPORT_STAR -> IMPORT_NAME mod ; IMPORT_STAR #JUMP_IF_FALSE / JUMP_IF_TRUE / JUMP_FORWARD def pass1(code): instrs = [] i = 0 n = len(code) curline = 0 incondition = 0 out = 0 while i < n: if i >= out: incondition = 0 c = code[i] i = i+1 op = ord(c) if op >= dis.HAVE_ARGUMENT: oparg = ord(code[i]) + ord(code[i+1])*256 i = i+2 else: oparg = None if not incondition and op in COND_OPS: incondition = 1 out = oparg if op in dis.hasjrel: out += i elif incondition and op == JUMP_FORWARD: out = max(out, i + oparg) if op == SET_LINENO: curline = oparg else: instrs.append((op, oparg, incondition, curline)) return instrs def scan_code(co, m=None, w=None, b=None, nested=0): instrs = pass1(co.co_code) if m is None: m = [] if w is None: w = [] if b is None: b = [] all = None lastname = None level = -1 # import-level, same behaviour as up to Python 2.4 for i in range(len(instrs)): op, oparg, conditional, curline = instrs[i] if op == IMPORT_NAME: if level <= 0: name = lastname = co.co_names[oparg] else: name = lastname = co.co_names[oparg] #print 'import_name', name, `lastname`, level m.append((name, nested, conditional, level)) elif op == IMPORT_FROM: name = co.co_names[oparg] #print 'import_from', name, `lastname`, level, if level > 0 and (not lastname or lastname[-1:] == '.'): name = lastname + name else: name = lastname + '.' + name #print name m.append((name, nested, conditional, level)) assert lastname is not None elif op == IMPORT_STAR: assert lastname is not None m.append((lastname+'.*', nested, conditional, level)) elif op == STORE_NAME: if co.co_names[oparg] == "__all__": j = i - 1 pop, poparg, pcondtl, pline = instrs[j] if pop != BUILD_LIST: w.append("W: __all__ is built strangely at line %s" % pline) else: all = [] while j > 0: j = j - 1 pop, poparg, pcondtl, pline = instrs[j] if pop == LOAD_CONST: all.append(co.co_consts[poparg]) else: break elif op in STORE_OPS: pass elif op == LOAD_CONST_level: # starting with Python 2.5, _each_ import is preceeded with a # LOAD_CONST to indicate the relative level. if isinstance(co.co_consts[oparg], (int, long)): level = co.co_consts[oparg] elif op == LOAD_GLOBAL: name = co.co_names[oparg] cndtl = ['', 'conditional'][conditional] lvl = ['top-level', 'delayed'][nested] if name == "__import__": w.append("W: %s %s __import__ hack detected at line %s" % (lvl, cndtl, curline)) elif name == "eval": w.append("W: %s %s eval hack detected at line %s" % (lvl, cndtl, curline)) elif op == EXEC_STMT: cndtl = ['', 'conditional'][conditional] lvl = ['top-level', 'delayed'][nested] w.append("W: %s %s exec statement detected at line %s" % (lvl, cndtl, curline)) else: lastname = None if ctypes: # ctypes scanning requires a scope wider than one bytecode instruction, # so the code resides in a separate function for clarity. ctypesb, ctypesw = scan_code_for_ctypes(co, instrs, i) b.extend(ctypesb) w.extend(ctypesw) for c in co.co_consts: if isinstance(c, type(co)): # FIXME: "all" was not updated here nor returned. Was it the desired # behaviour? _, _, _, all_nested = scan_code(c, m, w, b, 1) if all_nested: all.extend(all_nested) return m, w, b, all def scan_code_for_ctypes(co, instrs, i): """Detects ctypes dependencies, using reasonable heuristics that should cover most common ctypes usages; returns a tuple of two lists, one containing names of binaries detected as dependencies, the other containing warnings. """ def _libFromConst(i): """Extracts library name from an expected LOAD_CONST instruction and appends it to local binaries list. """ op, oparg, conditional, curline = instrs[i] if op == LOAD_CONST: soname = co.co_consts[oparg] b.append(soname) b = [] op, oparg, conditional, curline = instrs[i] if op in (LOAD_GLOBAL, LOAD_NAME): name = co.co_names[oparg] if name in ("CDLL", "WinDLL"): # Guesses ctypes imports of this type: CDLL("library.so") # LOAD_GLOBAL 0 (CDLL) <--- we "are" here right now # LOAD_CONST 1 ('library.so') _libFromConst(i+1) elif name == "ctypes": # Guesses ctypes imports of this type: ctypes.DLL("library.so") # LOAD_GLOBAL 0 (ctypes) <--- we "are" here right now # LOAD_ATTR 1 (CDLL) # LOAD_CONST 1 ('library.so') op2, oparg2, conditional2, curline2 = instrs[i+1] if op2 == LOAD_ATTR: if co.co_names[oparg2] in ("CDLL", "WinDLL"): # Fetch next, and finally get the library name _libFromConst(i+2) elif name in ("cdll", "windll"): # Guesses ctypes imports of these types: # * cdll.library (only valid on Windows) # LOAD_GLOBAL 0 (cdll) <--- we "are" here right now # LOAD_ATTR 1 (library) # * cdll.LoadLibrary("library.so") # LOAD_GLOBAL 0 (cdll) <--- we "are" here right now # LOAD_ATTR 1 (LoadLibrary) # LOAD_CONST 1 ('library.so') op2, oparg2, conditional2, curline2 = instrs[i+1] if op2 == LOAD_ATTR: if co.co_names[oparg2] != "LoadLibrary": # First type soname = co.co_names[oparg2] + ".dll" b.append(soname) else: # Second type, needs to fetch one more instruction _libFromConst(i+2) # If any of the libraries has been requested with anything different from # the bare filename, drop that entry and warn the user - pyinstaller would # need to patch the compiled pyc file to make it work correctly! w = [] for bin in list(b): if bin != os.path.basename(bin): b.remove(bin) w.append("W: ignoring %s - ctypes imports only supported using bare filenames" % (bin,)) return b, w def _resolveCtypesImports(cbinaries): """Completes ctypes BINARY entries for modules with their full path. """ if sys.platform.startswith("linux"): envvar = "LD_LIBRARY_PATH" elif sys.platform.startswith("darwin"): envvar = "DYLD_LIBRARY_PATH" else: envvar = "PATH" def _savePaths(): old = os.environ.get(envvar, None) os.environ[envvar] = os.pathsep.join(getattr(sys, "pathex", [])) if old is not None: os.environ[envvar] = os.pathsep.join([os.environ[envvar], old]) return old def _restorePaths(old): del os.environ[envvar] if old is not None: os.environ[envvar] = old ret = [] # Try to locate the shared library on disk. This is done by # executing ctypes.utile.find_library prepending ImportTracker's # local paths to library search paths, then replaces original values. old = _savePaths() for cbin in cbinaries: ext = os.path.splitext(cbin)[1] # On Windows, only .dll files can be loaded. if os.name == "nt" and ext.lower() in [".so", ".dylib"]: continue cpath = find_library(os.path.splitext(cbin)[0]) if sys.platform == "linux2": # CAVEAT: find_library() is not the correct function. Ctype's # documentation says that it is meant to resolve only the filename # (as a *compiler* does) not the full path. Anyway, it works well # enough on Windows and Mac. On Linux, we need to implement # more code to find out the full path. if cpath is None: cpath = cbin # "man ld.so" says that we should first search LD_LIBRARY_PATH # and then the ldcache for d in os.environ["LD_LIBRARY_PATH"].split(":"): if os.path.isfile(d + "/" + cpath): cpath = d + "/" + cpath break else: for L in os.popen("ldconfig -p").read().splitlines(): if cpath in L: cpath = L.split("=>", 1)[1].strip() assert os.path.isfile(cpath) break else: cpath = None if cpath is None: print "W: library %s required via ctypes not found" % (cbin,) else: ret.append((cbin, cpath, "BINARY")) _restorePaths(old) return ret
Python
#!/usr/bin/env python # # Build packages using spec files # # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys import os import shutil import pprint import time import py_compile import tempfile try: from hashlib import md5 except ImportError: from md5 import new as md5 import UserList import mf import archive import iu import carchive import bindepend import traceback STRINGTYPE = type('') TUPLETYPE = type((None,)) UNCOMPRESSED, COMPRESSED = range(2) # todo: use pkg_resources here HOMEPATH = os.path.dirname(sys.argv[0]) SPEC = None SPECPATH = None BUILDPATH = None WARNFILE = None rthooks = {} iswin = sys.platform[:3] == 'win' cygwin = sys.platform == 'cygwin' def system(cmd): # This workaround is required because NT shell doesn't work with commands # that start with double quotes (required if there are spaces inside the # command path) if iswin: cmd = 'echo on && ' + cmd os.system(cmd) def _save_data(filename, data): outf = open(filename, 'w') pprint.pprint(data, outf) outf.close() def _load_data(filename): return eval(open(filename, 'r').read().replace("\r\n","\n")) def setupUPXFlags(): f = os.environ.get("UPX", "") is24 = hasattr(sys, "version_info") and sys.version_info[:2] >= (2,4) if iswin and is24: # Binaries built with Visual Studio 7.1 require --strip-loadconf # or they won't compress. Configure.py makes sure that UPX is new # enough to support --strip-loadconf. f = "--strip-loadconf " + f # Do not compress any icon, so that additional icons in the executable # can still be externally bound f = "--compress-icons=0 " + f f = "--best " + f os.environ["UPX"] = f def mtime(fnm): try: return os.stat(fnm)[8] except: return 0 def absnormpath(apath): return os.path.abspath(os.path.normpath(apath)) def compile_pycos(toc): """Given a TOC or equivalent list of tuples, generates all the required pyc/pyo files, writing in a local directory if required, and returns the list of tuples with the updated pathnames. """ global BUILDPATH # For those modules that need to be rebuilt, use the build directory # PyInstaller creates during the build process. basepath = "/".join([BUILDPATH, "localpycos"]) new_toc = [] for (nm, fnm, typ) in toc: # Trim the terminal "c" or "o" source_fnm = fnm[:-1] # If the source is newer than the compiled, or the compiled doesn't # exist, we need to perform a build ourselves. if mtime(source_fnm) > mtime(fnm): try: py_compile.compile(source_fnm) except IOError: # If we're compiling on a system directory, probably we don't # have write permissions; thus we compile to a local directory # and change the TOC entry accordingly. ext = os.path.splitext(fnm)[1] if "__init__" not in fnm: # If it's a normal module, use last part of the qualified # name as module name and the first as leading path leading, mod_name = nm.split(".")[:-1], nm.split(".")[-1] else: # In case of a __init__ module, use all the qualified name # as leading path and use "__init__" as the module name leading, mod_name = nm.split("."), "__init__" leading.insert(0, basepath) leading = "/".join(leading) if not os.path.exists(leading): os.makedirs(leading) fnm = "/".join([leading, mod_name + ext]) py_compile.compile(source_fnm, fnm) new_toc.append((nm, fnm, typ)) return new_toc def addSuffixToExtensions(toc): """ Returns a new TOC with proper library suffix for EXTENSION items. """ new_toc = TOC() for inm, fnm, typ in toc: if typ == 'EXTENSION': binext = os.path.splitext(fnm)[1] if not os.path.splitext(inm)[1] == binext: inm = inm + binext new_toc.append((inm, fnm, typ)) return new_toc def architecture(): """ Returns the bit depth of the python interpreter's architecture as a string ('32bit' or '64bit'). Similar to platform.architecture(), but with fixes for universal binaries on MacOS. """ if sys.platform == "darwin": # Darwin's platform.architecture() is buggy and always # returns "64bit" even for the 32bit version of Python's # universal binary. So we roll out our own (that works # on Darwin). if sys.maxint > 2L**32: return '64bit' else: return '32bit' # Python 2.3+ import platform return platform.architecture()[0] #--- functons for checking guts --- def _check_guts_eq(attr, old, new, last_build): """ rebuild is required if values differ """ if old != new: print "building because %s changed" % attr return True return False def _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0): """ rebuild is required if mtimes of files listed in old toc are newer than ast_build if pyc=1, check for .py files, too """ for (nm, fnm, typ) in old: if mtime(fnm) > last_build: print "building because %s changed" % fnm return True elif pyc and mtime(fnm[:-1]) > last_build: print "building because %s changed" % fnm[:-1] return True return False def _check_guts_toc(attr, old, toc, last_build, pyc=0): """ rebuild is required if either toc content changed if mtimes of files listed in old toc are newer than ast_build if pyc=1, check for .py files, too """ return _check_guts_eq (attr, old, toc, last_build) \ or _check_guts_toc_mtime(attr, old, toc, last_build, pyc=pyc) def _rmdir(path): """ Remove dirname(os.path.abspath(path)) and all its contents, but only if: 1. It doesn't start with BUILDPATH 2. It is a directory and not empty (otherwise continue without removing the directory) 3. BUILDPATH and SPECPATH don't start with it 4. The --noconfirm option is set, or sys.stdout is a tty and the user confirms directory removal Otherwise, error out. """ if not os.path.abspath(path): path = os.path.abspath(path) if not path.startswith(BUILDPATH) and os.path.isdir(path) and os.listdir(path): specerr = 0 if BUILDPATH.startswith(path): print ('E: specfile error: The output path "%s" contains ' 'BUILDPATH (%s)') % (path, BUILDPATH) specerr += 1 if SPECPATH.startswith(path): print ('E: Specfile error: The output path "%s" contains ' 'SPECPATH (%s)') % (path, SPECPATH) specerr += 1 if specerr: print ('Please edit/recreate the specfile (%s), set a different ' 'output name (e.g. "dist") and run Build.py again.') % SPEC sys.exit(1) if opts.noconfirm: choice = 'y' elif sys.stdout.isatty(): choice = raw_input('WARNING: The output directory "%s" and ALL ITS ' 'CONTENTS will be REMOVED! Continue? (y/n)' % path) else: print ('E: The output directory "%s" is not empty. Please remove ' 'all its contents and run Build.py again, or use Build.py ' '-y (remove output directory without confirmation).') % path sys.exit(1) if choice.strip().lower() == 'y': print 'I: Removing', path shutil.rmtree(path) else: print 'I: User aborted' sys.exit(1) def check_egg(pth): """Check if path points to a file inside a python egg file (or to an egg directly).""" if sys.version_info >= (2,3): if os.path.altsep: pth = pth.replace(os.path.altsep, os.path.sep) components = pth.split(os.path.sep) sep = os.path.sep else: components = pth.replace("\\", "/").split("/") sep = "/" if iswin: sep = "\\" for i,name in zip(range(0,len(components)), components): if name.lower().endswith(".egg"): eggpth = sep.join(components[:i + 1]) if os.path.isfile(eggpth): # eggs can also be directories! return True return False #-- class Target: invcnum = 0 def __init__(self): self.invcnum = Target.invcnum Target.invcnum += 1 self.out = os.path.join(BUILDPATH, 'out%s%d.toc' % (self.__class__.__name__, self.invcnum)) self.outnm = os.path.basename(self.out) self.dependencies = TOC() def __postinit__(self): print "checking %s" % (self.__class__.__name__,) if self.check_guts(mtime(self.out)): self.assemble() GUTS = [] def check_guts(self, last_build): pass def get_guts(self, last_build, missing ='missing or bad'): """ returns None if guts have changed """ try: data = _load_data(self.out) except: print "building because", os.path.basename(self.out), missing return None if len(data) != len(self.GUTS): print "building because %s is bad" % self.outnm return None for i in range(len(self.GUTS)): attr, func = self.GUTS[i] if func is None: # no check for this value continue if func(attr, data[i], getattr(self, attr), last_build): return None return data class Analysis(Target): def __init__(self, scripts=None, pathex=None, hookspath=None, excludes=None): Target.__init__(self) self.inputs = scripts for script in scripts: if not os.path.exists(script): raise ValueError, "script '%s' not found" % script self.pathex = [] if pathex: for path in pathex: self.pathex.append(absnormpath(path)) sys.pathex = self.pathex[:] self.hookspath = hookspath self.excludes = excludes self.scripts = TOC() self.pure = TOC() self.binaries = TOC() self.zipfiles = TOC() self.datas = TOC() self.__postinit__() GUTS = (('inputs', _check_guts_eq), ('pathex', _check_guts_eq), ('hookspath', _check_guts_eq), ('excludes', _check_guts_eq), ('scripts', _check_guts_toc_mtime), ('pure', lambda *args: apply(_check_guts_toc_mtime, args, {'pyc': 1 } )), ('binaries', _check_guts_toc_mtime), ('zipfiles', _check_guts_toc_mtime), ('datas', _check_guts_toc_mtime), ) def check_guts(self, last_build): if last_build == 0: print "building %s because %s non existent" % (self.__class__.__name__, self.outnm) return True for fnm in self.inputs: if mtime(fnm) > last_build: print "building because %s changed" % fnm return True data = Target.get_guts(self, last_build) if not data: return True scripts, pure, binaries, zipfiles, datas = data[-5:] self.scripts = TOC(scripts) self.pure = TOC(pure) self.binaries = TOC(binaries) self.zipfiles = TOC(zipfiles) self.datas = TOC(datas) return False def assemble(self): print "running Analysis", os.path.basename(self.out) # Reset seen variable to correctly discover dependencies # if there are multiple Analysis in a single specfile. bindepend.seen = {} paths = self.pathex for i in range(len(paths)): # FIXME: isn't self.pathex already norm-abs-pathed? paths[i] = absnormpath(paths[i]) ################################################### # Scan inputs and prepare: dirs = {} # input directories pynms = [] # python filenames with no extension for script in self.inputs: if not os.path.exists(script): print "Analysis: script %s not found!" % script sys.exit(1) d, base = os.path.split(script) if not d: d = os.getcwd() d = absnormpath(d) pynm, ext = os.path.splitext(base) dirs[d] = 1 pynms.append(pynm) ################################################### # Initialize analyzer and analyze scripts analyzer = mf.ImportTracker(dirs.keys()+paths, self.hookspath, self.excludes, target_platform=target_platform) #print analyzer.path scripts = [] # will contain scripts to bundle for i in range(len(self.inputs)): script = self.inputs[i] print "Analyzing:", script analyzer.analyze_script(script) scripts.append((pynms[i], script, 'PYSOURCE')) ################################################### # Fills pure, binaries and rthookcs lists to TOC pure = [] # pure python modules binaries = [] # binaries to bundle zipfiles = [] # zipfiles to bundle datas = [] # datafiles to bundle rthooks = [] # rthooks if needed for modnm, mod in analyzer.modules.items(): # FIXME: why can we have a mod == None here? if mod is not None: hooks = findRTHook(modnm) #XXX if hooks: rthooks.extend(hooks) datas.extend(mod.datas) if isinstance(mod, mf.BuiltinModule): pass else: fnm = mod.__file__ if isinstance(mod, mf.ExtensionModule): binaries.append((mod.__name__, fnm, 'EXTENSION')) elif isinstance(mod, (mf.PkgInZipModule, mf.PyInZipModule)): zipfiles.append(("eggs/" + os.path.basename(str(mod.owner)), str(mod.owner), 'ZIPFILE')) else: # mf.PyModule instances expose a list of binary # dependencies, most probably shared libraries accessed # via ctypes. Add them to the overall required binaries. binaries.extend(mod.binaries) if modnm != '__main__': pure.append((modnm, fnm, 'PYMODULE')) # Always add python's dependencies first # This ensures that assembly depencies under Windows get pulled in # first and we do not need to add assembly DLLs to the exclude list # explicitly python = config['python'] if not iswin: while os.path.islink(python): python = os.path.join(os.path.split(python)[0], os.readlink(python)) depmanifest = None else: depmanifest = winmanifest.Manifest(type_="win32", name=specnm, processorArchitecture="x86", version=(1, 0, 0, 0)) depmanifest.filename = os.path.join(BUILDPATH, specnm + ".exe.manifest") binaries.extend(bindepend.Dependencies([('', python, '')], target_platform, config['xtrapath'], manifest=depmanifest)[1:]) binaries.extend(bindepend.Dependencies(binaries, platform=target_platform, manifest=depmanifest)) if iswin: depmanifest.writeprettyxml() self.fixMissingPythonLib(binaries) if zipfiles: scripts[-1:-1] = [("_pyi_egg_install.py", os.path.join(HOMEPATH, "support/_pyi_egg_install.py"), 'PYSOURCE')] # Add realtime hooks just before the last script (which is # the entrypoint of the application). scripts[-1:-1] = rthooks self.scripts = TOC(scripts) self.pure = TOC(pure) self.binaries = TOC(binaries) self.zipfiles = TOC(zipfiles) self.datas = TOC(datas) try: # read .toc oldstuff = _load_data(self.out) except: oldstuff = None self.pure = TOC(compile_pycos(self.pure)) newstuff = (self.inputs, self.pathex, self.hookspath, self.excludes, self.scripts, self.pure, self.binaries, self.zipfiles, self.datas) if oldstuff != newstuff: _save_data(self.out, newstuff) wf = open(WARNFILE, 'w') for ln in analyzer.getwarnings(): wf.write(ln+'\n') wf.close() print "Warnings written to %s" % WARNFILE return 1 print self.out, "no change!" return 0 def fixMissingPythonLib(self, binaries): """Add the Python library if missing from the binaries. Some linux distributions (e.g. debian-based) statically build the Python executable to the libpython, so bindepend doesn't include it in its output. Darwin custom builds could possibly also have non-framework style libraries, so this method also checks for that variant as well. """ if target_platform.startswith("linux"): names = ('libpython%d.%d.so' % sys.version_info[:2],) elif target_platform.startswith("darwin"): names = ('Python', 'libpython%d.%d.dylib' % sys.version_info[:2]) else: return for (nm, fnm, typ) in binaries: for name in names: if typ == 'BINARY' and name in fnm: # lib found return # resume search using the first item in names name = names[0] if target_platform.startswith("linux"): lib = bindepend.findLibrary(name) if lib is None: raise IOError("Python library not found!") elif target_platform.startswith("darwin"): # On MacPython, Analysis.assemble is able to find the libpython with # no additional help, asking for config['python'] dependencies. # However, this fails on system python, because the shared library # is not listed as a dependency of the binary (most probably it's # opened at runtime using some dlopen trickery). lib = os.path.join(sys.exec_prefix, 'Python') if not os.path.exists(lib): raise IOError("Python library not found!") binaries.append((os.path.split(lib)[1], lib, 'BINARY')) def findRTHook(modnm): hooklist = rthooks.get(modnm) if hooklist: rslt = [] for script in hooklist: nm = os.path.basename(script) nm = os.path.splitext(nm)[0] if os.path.isabs(script): path = script else: path = os.path.join(HOMEPATH, script) rslt.append((nm, path, 'PYSOURCE')) return rslt return None class PYZ(Target): typ = 'PYZ' def __init__(self, toc, name=None, level=9, crypt=None): Target.__init__(self) self.toc = toc self.name = name if name is None: self.name = self.out[:-3] + 'pyz' if config['useZLIB']: self.level = level else: self.level = 0 if config['useCrypt'] and crypt is not None: self.crypt = archive.Keyfile(crypt).key else: self.crypt = None self.dependencies = compile_pycos(config['PYZ_dependencies']) self.__postinit__() GUTS = (('name', _check_guts_eq), ('level', _check_guts_eq), ('crypt', _check_guts_eq), ('toc', _check_guts_toc), # todo: pyc=1 ) def check_guts(self, last_build): _rmdir(self.name) if not os.path.exists(self.name): print "rebuilding %s because %s is missing" % (self.outnm, os.path.basename(self.name)) return True data = Target.get_guts(self, last_build) if not data: return True return False def assemble(self): print "building PYZ", os.path.basename(self.out) pyz = archive.ZlibArchive(level=self.level, crypt=self.crypt) toc = self.toc - config['PYZ_dependencies'] pyz.build(self.name, toc) _save_data(self.out, (self.name, self.level, self.crypt, self.toc)) return 1 def cacheDigest(fnm): data = open(fnm, "rb").read() digest = md5(data).digest() return digest def checkCache(fnm, strip, upx): # On darwin a cache is required anyway to keep the libaries # with relative install names if (not strip and not upx and sys.platform[:6] != 'darwin' and sys.platform != 'win32') or fnm.lower().endswith(".manifest"): return fnm if strip: strip = 1 else: strip = 0 if upx: upx = 1 else: upx = 0 # Load cache index cachedir = os.path.join(HOMEPATH, 'bincache%d%d' % (strip, upx)) if not os.path.exists(cachedir): os.makedirs(cachedir) cacheindexfn = os.path.join(cachedir, "index.dat") if os.path.exists(cacheindexfn): cache_index = _load_data(cacheindexfn) else: cache_index = {} # Verify if the file we're looking for is present in the cache. basenm = os.path.normcase(os.path.basename(fnm)) digest = cacheDigest(fnm) cachedfile = os.path.join(cachedir, basenm) cmd = None if cache_index.has_key(basenm): if digest != cache_index[basenm]: os.remove(cachedfile) else: return cachedfile if upx: if strip: fnm = checkCache(fnm, 1, 0) bestopt = "--best" # FIXME: Linux builds of UPX do not seem to contain LZMA (they assert out) # A better configure-time check is due. if config["hasUPX"] >= (3,) and os.name == "nt": bestopt = "--lzma" upx_executable = "upx" if config.get('upx_dir'): upx_executable = os.path.join(config['upx_dir'], upx_executable) cmd = '"' + upx_executable + '" ' + bestopt + " -q \"%s\"" % cachedfile else: if strip: # -S = strip only debug symbols. # The default strip behaviour breaks some shared libraries # under Mac OSX. cmd = "strip -S \"%s\"" % cachedfile shutil.copy2(fnm, cachedfile) os.chmod(cachedfile, 0755) if pyasm and fnm.lower().endswith(".pyd"): # If python.exe has dependent assemblies, check for embedded manifest # of cached pyd file because we may need to 'fix it' for pyinstaller try: res = winmanifest.GetManifestResources(os.path.abspath(cachedfile)) except winresource.pywintypes.error, e: if e.args[0] == winresource.ERROR_BAD_EXE_FORMAT: # Not a win32 PE file pass else: print "E:", os.path.abspath(cachedfile) raise else: if winmanifest.RT_MANIFEST in res and len(res[winmanifest.RT_MANIFEST]): for name in res[winmanifest.RT_MANIFEST]: for language in res[winmanifest.RT_MANIFEST][name]: try: manifest = winmanifest.Manifest() manifest.filename = ":".join([cachedfile, str(winmanifest.RT_MANIFEST), str(name), str(language)]) manifest.parse_string(res[winmanifest.RT_MANIFEST][name][language], False) except Exception, exc: print ("E: Cannot parse manifest resource %s, " "%s from") % (name, language) print "E:", cachedfile print "E:", traceback.format_exc() else: # Fix the embedded manifest (if any): # Extension modules built with Python 2.6.5 have # an empty <dependency> element, we need to add # dependentAssemblies from python.exe for # pyinstaller olen = len(manifest.dependentAssemblies) for pydep in pyasm: if not pydep.name in [dep.name for dep in manifest.dependentAssemblies]: print ("Adding %s to dependent assemblies " "of %s") % (pydep.name, cachedfile) manifest.dependentAssemblies.append(pydep) if len(manifest.dependentAssemblies) > olen: try: manifest.update_resources(os.path.abspath(cachedfile), [name], [language]) except Exception, e: print "E:", os.path.abspath(cachedfile) raise if cmd: system(cmd) # update cache index cache_index[basenm] = digest _save_data(cacheindexfn, cache_index) return cachedfile UNCOMPRESSED, COMPRESSED, ENCRYPTED = range(3) class PKG(Target): typ = 'PKG' xformdict = {'PYMODULE' : 'm', 'PYSOURCE' : 's', 'EXTENSION' : 'b', 'PYZ' : 'z', 'PKG' : 'a', 'DATA': 'x', 'BINARY': 'b', 'ZIPFILE': 'Z', 'EXECUTABLE': 'b'} def __init__(self, toc, name=None, cdict=None, exclude_binaries=0, strip_binaries=0, upx_binaries=0, crypt=0): Target.__init__(self) self.toc = toc self.cdict = cdict self.name = name self.exclude_binaries = exclude_binaries self.strip_binaries = strip_binaries self.upx_binaries = upx_binaries self.crypt = crypt if name is None: self.name = self.out[:-3] + 'pkg' if self.cdict is None: if config['useZLIB']: self.cdict = {'EXTENSION':COMPRESSED, 'DATA':COMPRESSED, 'BINARY':COMPRESSED, 'EXECUTABLE':COMPRESSED, 'PYSOURCE':COMPRESSED, 'PYMODULE':COMPRESSED } if self.crypt: self.cdict['PYSOURCE'] = ENCRYPTED self.cdict['PYMODULE'] = ENCRYPTED else: self.cdict = { 'PYSOURCE':UNCOMPRESSED } self.__postinit__() GUTS = (('name', _check_guts_eq), ('cdict', _check_guts_eq), ('toc', _check_guts_toc_mtime), ('exclude_binaries', _check_guts_eq), ('strip_binaries', _check_guts_eq), ('upx_binaries', _check_guts_eq), ('crypt', _check_guts_eq), ) def check_guts(self, last_build): _rmdir(self.name) if not os.path.exists(self.name): print "rebuilding %s because %s is missing" % (self.outnm, os.path.basename(self.name)) return 1 data = Target.get_guts(self, last_build) if not data: return True # todo: toc equal return False def assemble(self): print "building PKG", os.path.basename(self.name) trash = [] mytoc = [] seen = {} toc = addSuffixToExtensions(self.toc) for inm, fnm, typ in toc: if not os.path.isfile(fnm) and check_egg(fnm): # file is contained within python egg, it is added with the egg continue if typ in ('BINARY', 'EXTENSION'): if self.exclude_binaries: self.dependencies.append((inm, fnm, typ)) else: fnm = checkCache(fnm, self.strip_binaries, self.upx_binaries and ( iswin or cygwin ) and config['hasUPX']) # Avoid importing the same binary extension twice. This might # happen if they come from different sources (eg. once from # binary dependence, and once from direct import). if typ == 'BINARY' and seen.has_key(fnm): continue seen[fnm] = 1 mytoc.append((inm, fnm, self.cdict.get(typ,0), self.xformdict.get(typ,'b'))) elif typ == 'OPTION': mytoc.append((inm, '', 0, 'o')) else: mytoc.append((inm, fnm, self.cdict.get(typ,0), self.xformdict.get(typ,'b'))) archive = carchive.CArchive() archive.build(self.name, mytoc) _save_data(self.out, (self.name, self.cdict, self.toc, self.exclude_binaries, self.strip_binaries, self.upx_binaries, self.crypt)) for item in trash: os.remove(item) return 1 class EXE(Target): typ = 'EXECUTABLE' exclude_binaries = 0 append_pkg = 1 def __init__(self, *args, **kws): Target.__init__(self) self.console = kws.get('console',1) self.debug = kws.get('debug',0) self.name = kws.get('name',None) self.icon = kws.get('icon',None) self.versrsrc = kws.get('version',None) self.manifest = kws.get('manifest',None) self.resources = kws.get('resources',[]) self.strip = kws.get('strip',None) self.upx = kws.get('upx',None) self.crypt = kws.get('crypt', 0) self.exclude_binaries = kws.get('exclude_binaries',0) self.append_pkg = kws.get('append_pkg', self.append_pkg) if self.name is None: self.name = self.out[:-3] + 'exe' if not os.path.isabs(self.name): self.name = os.path.join(SPECPATH, self.name) if target_iswin or cygwin: self.pkgname = self.name[:-3] + 'pkg' else: self.pkgname = self.name + '.pkg' self.toc = TOC() for arg in args: if isinstance(arg, TOC): self.toc.extend(arg) elif isinstance(arg, Target): self.toc.append((os.path.basename(arg.name), arg.name, arg.typ)) self.toc.extend(arg.dependencies) else: self.toc.extend(arg) if iswin: if sys.version[:3] == '1.5': import exceptions toc.append((os.path.basename(exceptions.__file__), exceptions.__file__, 'BINARY')) if self.manifest: if isinstance(self.manifest, basestring) and "<" in self.manifest: # Assume XML string self.manifest = winmanifest.ManifestFromXML(self.manifest) elif not isinstance(self.manifest, winmanifest.Manifest): # Assume filename self.manifest = winmanifest.ManifestFromXMLFile(self.manifest) else: self.manifest = winmanifest.ManifestFromXMLFile(os.path.join(BUILDPATH, specnm + ".exe.manifest")) self.manifest.name = os.path.splitext(os.path.basename(self.name))[0] if self.manifest.filename != os.path.join(BUILDPATH, specnm + ".exe.manifest"): # Update dependent assemblies depmanifest = winmanifest.ManifestFromXMLFile(os.path.join(BUILDPATH, specnm + ".exe.manifest")) for assembly in depmanifest.dependentAssemblies: if not assembly.name in [dependentAssembly.name for dependentAssembly in self.manifest.dependentAssemblies]: self.manifest.dependentAssemblies.append(assembly) if not self.console and \ not "Microsoft.Windows.Common-Controls" in [dependentAssembly.name for dependentAssembly in self.manifest.dependentAssemblies]: # Add Microsoft.Windows.Common-Controls to dependent assemblies self.manifest.dependentAssemblies.append(winmanifest.Manifest(type_="win32", name="Microsoft.Windows.Common-Controls", language="*", processorArchitecture="x86", version=(6, 0, 0, 0), publicKeyToken="6595b64144ccf1df")) self.manifest.writeprettyxml(os.path.join(BUILDPATH, specnm + ".exe.manifest")) self.toc.append((os.path.basename(self.name) + ".manifest", os.path.join(BUILDPATH, specnm + ".exe.manifest"), 'BINARY')) self.pkg = PKG(self.toc, cdict=kws.get('cdict',None), exclude_binaries=self.exclude_binaries, strip_binaries=self.strip, upx_binaries=self.upx, crypt=self.crypt) self.dependencies = self.pkg.dependencies self.__postinit__() GUTS = (('name', _check_guts_eq), ('console', _check_guts_eq), ('debug', _check_guts_eq), ('icon', _check_guts_eq), ('versrsrc', _check_guts_eq), ('manifest', _check_guts_eq), ('resources', _check_guts_eq), ('strip', _check_guts_eq), ('upx', _check_guts_eq), ('crypt', _check_guts_eq), ('mtm', None,), # checked bellow ) def check_guts(self, last_build): _rmdir(self.name) if not os.path.exists(self.name): print "rebuilding %s because %s missing" % (self.outnm, os.path.basename(self.name)) return 1 if not self.append_pkg and not os.path.exists(self.pkgname): print "rebuilding because %s missing" % ( os.path.basename(self.pkgname),) return 1 data = Target.get_guts(self, last_build) if not data: return True icon, versrsrc, manifest, resources = data[3:7] if (icon or versrsrc or manifest or resources) and not config['hasRsrcUpdate']: # todo: really ignore :-) print "ignoring icon, version, manifest and resources = platform not capable" mtm = data[-1] crypt = data[-2] if crypt != self.crypt: print "rebuilding %s because crypt option changed" % outnm return 1 if mtm != mtime(self.name): print "rebuilding", self.outnm, "because mtimes don't match" return True if mtm < mtime(self.pkg.out): print "rebuilding", self.outnm, "because pkg is more recent" return True return False def _bootloader_file(self, exe): try: import platform # On some Windows installation (Python 2.4) platform.system() is # broken and incorrectly returns 'Microsoft' instead of 'Windows'. # http://mail.python.org/pipermail/patches/2007-June/022947.html syst = platform.system() syst_real = {'Microsoft': 'Windows'}.get(syst, syst) PLATFORM = syst_real + "-" + architecture() except ImportError: import os n = { "nt": "Windows", "linux2": "Linux", "darwin": "Darwin" } PLATFORM = n[os.name] + "-32bit" if not self.console: exe = exe + 'w' if self.debug: exe = exe + '_d' import os return os.path.join('support', 'loader', PLATFORM, exe) def assemble(self): print "building EXE from", os.path.basename(self.out) trash = [] if not os.path.exists(os.path.dirname(self.name)): os.makedirs(os.path.dirname(self.name)) outf = open(self.name, 'wb') exe = self._bootloader_file('run') exe = os.path.join(HOMEPATH, exe) if target_iswin or cygwin: exe = exe + '.exe' if config['hasRsrcUpdate'] and (self.icon or self.versrsrc or self.resources): tmpnm = tempfile.mktemp() shutil.copy2(exe, tmpnm) os.chmod(tmpnm, 0755) if self.icon: icon.CopyIcons(tmpnm, self.icon) if self.versrsrc: versionInfo.SetVersion(tmpnm, self.versrsrc) for res in self.resources: res = res.split(",") for i in range(len(res[1:])): try: res[i + 1] = int(res[i + 1]) except ValueError: pass resfile = res[0] if len(res) > 1: restype = res[1] else: restype = None if len(res) > 2: resname = res[2] else: restype = None if len(res) > 3: reslang = res[3] else: restype = None try: winresource.UpdateResourcesFromResFile(tmpnm, resfile, [restype or "*"], [resname or "*"], [reslang or "*"]) except winresource.pywintypes.error, exc: if exc.args[0] != winresource.ERROR_BAD_EXE_FORMAT: print "E:", str(exc) continue if not restype or not resname: print "E: resource type and/or name not specified" continue if "*" in (restype, resname): print ("E: no wildcards allowed for resource type " "and name when source file does not contain " "resources") continue try: winresource.UpdateResourcesFromDataFile(tmpnm, resfile, restype, [resname], [reslang or 0]) except winresource.pywintypes.error, exc: print "E:", str(exc) trash.append(tmpnm) exe = tmpnm exe = checkCache(exe, self.strip, self.upx and config['hasUPX']) self.copy(exe, outf) if self.append_pkg: print "Appending archive to EXE", self.name self.copy(self.pkg.name, outf) else: print "Copying archive to", self.pkgname shutil.copy2(self.pkg.name, self.pkgname) outf.close() os.chmod(self.name, 0755) _save_data(self.out, (self.name, self.console, self.debug, self.icon, self.versrsrc, self.resources, self.strip, self.upx, self.crypt, mtime(self.name))) for item in trash: os.remove(item) return 1 def copy(self, fnm, outf): inf = open(fnm, 'rb') while 1: data = inf.read(64*1024) if not data: break outf.write(data) class DLL(EXE): def assemble(self): print "building DLL", os.path.basename(self.out) outf = open(self.name, 'wb') dll = self._bootloader_file('inprocsrvr') dll = os.path.join(HOMEPATH, dll) + '.dll' self.copy(dll, outf) self.copy(self.pkg.name, outf) outf.close() os.chmod(self.name, 0755) _save_data(self.out, (self.name, self.console, self.debug, self.icon, self.versrsrc, self.manifest, self.resources, self.strip, self.upx, mtime(self.name))) return 1 class COLLECT(Target): def __init__(self, *args, **kws): Target.__init__(self) self.name = kws.get('name',None) if self.name is None: self.name = 'dist_' + self.out[:-4] self.strip_binaries = kws.get('strip',0) self.upx_binaries = kws.get('upx',0) if not os.path.isabs(self.name): self.name = os.path.join(SPECPATH, self.name) self.toc = TOC() for arg in args: if isinstance(arg, TOC): self.toc.extend(arg) elif isinstance(arg, Target): self.toc.append((os.path.basename(arg.name), arg.name, arg.typ)) if isinstance(arg, EXE): for tocnm, fnm, typ in arg.toc: if tocnm == os.path.basename(arg.name) + ".manifest": self.toc.append((tocnm, fnm, typ)) if not arg.append_pkg: self.toc.append((os.path.basename(arg.pkgname), arg.pkgname, 'PKG')) self.toc.extend(arg.dependencies) else: self.toc.extend(arg) self.__postinit__() GUTS = (('name', _check_guts_eq), ('strip_binaries', _check_guts_eq), ('upx_binaries', _check_guts_eq), ('toc', _check_guts_eq), # additional check below ) def check_guts(self, last_build): _rmdir(self.name) data = Target.get_guts(self, last_build) if not data: return True toc = data[-1] for inm, fnm, typ in self.toc: if typ == 'EXTENSION': ext = os.path.splitext(fnm)[1] test = os.path.join(self.name, inm+ext) else: test = os.path.join(self.name, os.path.basename(fnm)) if not os.path.exists(test): print "building %s because %s is missing" % (self.outnm, test) return 1 if mtime(fnm) > mtime(test): print "building %s because %s is more recent" % (self.outnm, fnm) return 1 return 0 def assemble(self): print "building COLLECT", os.path.basename(self.out) if not os.path.exists(self.name): os.makedirs(self.name) toc = addSuffixToExtensions(self.toc) for inm, fnm, typ in toc: if not os.path.isfile(fnm) and check_egg(fnm): # file is contained within python egg, it is added with the egg continue tofnm = os.path.join(self.name, inm) todir = os.path.dirname(tofnm) if not os.path.exists(todir): os.makedirs(todir) if typ in ('EXTENSION', 'BINARY'): fnm = checkCache(fnm, self.strip_binaries, self.upx_binaries and ( iswin or cygwin ) and config['hasUPX']) shutil.copy2(fnm, tofnm) if typ in ('EXTENSION', 'BINARY'): os.chmod(tofnm, 0755) _save_data(self.out, (self.name, self.strip_binaries, self.upx_binaries, self.toc)) return 1 class BUNDLE(Target): def __init__(self, *args, **kws): # BUNDLE only has a sense under Mac OS X, it's a noop on other platforms if not sys.platform.startswith("darwin"): return Target.__init__(self) self.name = kws.get('name', None) if self.name is not None: self.appname = os.path.splitext(os.path.basename(self.name))[0] self.version = kws.get("version", "0.0.0") self.toc = TOC() for arg in args: if isinstance(arg, EXE): self.toc.append((os.path.basename(arg.name), arg.name, arg.typ)) self.toc.extend(arg.dependencies) elif isinstance(arg, TOC): self.toc.extend(arg) elif isinstance(arg, COLLECT): self.toc.extend(arg.toc) else: print "unsupported entry %s", arg.__class__.__name__ # Now, find values for app filepath (name), app name (appname), and name # of the actual executable (exename) from the first EXECUTABLE item in # toc, which might have come from a COLLECT too (not from an EXE). for inm, name, typ in self.toc: if typ == "EXECUTABLE": self.exename = name if self.name is None: self.appname = "Mac%s" % (os.path.splitext(inm)[0],) self.name = os.path.join(SPECPATH, self.appname + ".app") break self.__postinit__() GUTS = (('toc', _check_guts_eq), # additional check below ) def check_guts(self, last_build): _rmdir(self.name) data = Target.get_guts(self, last_build) if not data: return True toc = data[-1] for inm, fnm, typ in self.toc: test = os.path.join(self.name, os.path.basename(fnm)) if not os.path.exists(test): print "building %s because %s is missing" % (self.outnm, test) return 1 if mtime(fnm) > mtime(test): print "building %s because %s is more recent" % (self.outnm, fnm) return 1 return 0 def assemble(self): print "building BUNDLE", os.path.basename(self.out) if os.path.exists(self.name): shutil.rmtree(self.name) # Create a minimal Mac bundle structure os.makedirs(os.path.join(self.name, "Contents", "MacOS")) os.makedirs(os.path.join(self.name, "Contents", "Resources")) os.makedirs(os.path.join(self.name, "Contents", "Frameworks")) # Key/values for a minimal Info.plist file info_plist_dict = {"CFBundleDisplayName": self.appname, "CFBundleName": self.appname, "CFBundleExecutable": os.path.basename(self.exename), "CFBundleIconFile": "App.icns", "CFBundleInfoDictionaryVersion": "6.0", "CFBundlePackageType": "APPL", "CFBundleShortVersionString": self.version, # Setting this to 1 will cause Mac OS X *not* to show # a dock icon for the PyInstaller process which # decompresses the real executable's contents. As a # side effect, the main application doesn't get one # as well, but at startup time the loader will take # care of transforming the process type. "LSBackgroundOnly": "1", } info_plist = """<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict>""" for k, v in info_plist_dict.items(): info_plist += "<key>%s</key>\n<string>%s</string>\n" % (k, v) info_plist += """</dict> </plist>""" f = open(os.path.join(self.name, "Contents", "Info.plist"), "w") f.write(info_plist) f.close() toc = addSuffixToExtensions(self.toc) for inm, fnm, typ in toc: tofnm = os.path.join(self.name, "Contents", "MacOS", inm) todir = os.path.dirname(tofnm) if not os.path.exists(todir): os.makedirs(todir) shutil.copy2(fnm, tofnm) return 1 class TOC(UserList.UserList): def __init__(self, initlist=None): UserList.UserList.__init__(self) self.fltr = {} if initlist: for tpl in initlist: self.append(tpl) def append(self, tpl): try: fn = tpl[0] if tpl[2] == "BINARY": # Normalize the case for binary files only (to avoid duplicates # for different cases under Windows). We can't do that for # Python files because the import semantic (even at runtime) # depends on the case. fn = os.path.normcase(fn) if not self.fltr.get(fn): self.data.append(tpl) self.fltr[fn] = 1 except TypeError: print "TOC found a %s, not a tuple" % tpl raise def insert(self, pos, tpl): fn = tpl[0] if tpl[2] == "BINARY": fn = os.path.normcase(fn) if not self.fltr.get(fn): self.data.insert(pos, tpl) self.fltr[fn] = 1 def __add__(self, other): rslt = TOC(self.data) rslt.extend(other) return rslt def __radd__(self, other): rslt = TOC(other) rslt.extend(self.data) return rslt def extend(self, other): for tpl in other: self.append(tpl) def __sub__(self, other): fd = self.fltr.copy() # remove from fd if it's in other for tpl in other: if fd.get(tpl[0],0): del fd[tpl[0]] rslt = TOC() # return only those things still in fd (preserve order) for tpl in self.data: if fd.get(tpl[0],0): rslt.append(tpl) return rslt def __rsub__(self, other): rslt = TOC(other) return rslt.__sub__(self) def intersect(self, other): rslt = TOC() for tpl in other: if self.fltr.get(tpl[0],0): rslt.append(tpl) return rslt class Tree(Target, TOC): def __init__(self, root=None, prefix=None, excludes=None): Target.__init__(self) TOC.__init__(self) self.root = root self.prefix = prefix self.excludes = excludes if excludes is None: self.excludes = [] self.__postinit__() GUTS = (('root', _check_guts_eq), ('prefix', _check_guts_eq), ('excludes', _check_guts_eq), ('toc', None), ) def check_guts(self, last_build): data = Target.get_guts(self, last_build) if not data: return True stack = [ data[0] ] # root toc = data[3] # toc while stack: d = stack.pop() if mtime(d) > last_build: print "building %s because directory %s changed" % (self.outnm, d) return True for nm in os.listdir(d): path = os.path.join(d, nm) if os.path.isdir(path): stack.append(path) self.data = toc return False def assemble(self): print "building Tree", os.path.basename(self.out) stack = [(self.root, self.prefix)] excludes = {} xexcludes = {} for nm in self.excludes: if nm[0] == '*': xexcludes[nm[1:]] = 1 else: excludes[nm] = 1 rslt = [] while stack: dir, prefix = stack.pop() for fnm in os.listdir(dir): if excludes.get(fnm, 0) == 0: ext = os.path.splitext(fnm)[1] if xexcludes.get(ext,0) == 0: fullfnm = os.path.join(dir, fnm) rfnm = prefix and os.path.join(prefix, fnm) or fnm if os.path.isdir(fullfnm): stack.append((fullfnm, rfnm)) else: rslt.append((rfnm, fullfnm, 'DATA')) self.data = rslt try: oldstuff = _load_data(self.out) except: oldstuff = None newstuff = (self.root, self.prefix, self.excludes, self.data) if oldstuff != newstuff: _save_data(self.out, newstuff) return 1 print self.out, "no change!" return 0 def TkTree(): tclroot = config['TCL_root'] tclnm = os.path.join('_MEI', config['TCL_dirname']) tkroot = config['TK_root'] tknm = os.path.join('_MEI', config['TK_dirname']) tcltree = Tree(tclroot, tclnm, excludes=['demos','encoding','*.lib']) tktree = Tree(tkroot, tknm, excludes=['demos','encoding','*.lib']) return tcltree + tktree def TkPKG(): return PKG(TkTree(), name='tk.pkg') #--- def build(spec): global SPECPATH, BUILDPATH, WARNFILE, rthooks, SPEC, specnm rthooks = _load_data(os.path.join(HOMEPATH, 'rthooks.dat')) SPEC = spec SPECPATH, specnm = os.path.split(spec) specnm = os.path.splitext(specnm)[0] if SPECPATH == '': SPECPATH = os.getcwd() WARNFILE = os.path.join(SPECPATH, 'warn%s.txt' % specnm) BUILDPATH = os.path.join(SPECPATH, 'build', "pyi." + config['target_platform'], specnm) if opts.buildpath != parser.get_option('--buildpath').default: bpath = opts.buildpath if os.path.isabs(bpath): BUILDPATH = bpath else: BUILDPATH = os.path.join(SPECPATH, bpath) if not os.path.exists(BUILDPATH): os.makedirs(BUILDPATH) execfile(spec) def main(specfile, configfilename): global target_platform, target_iswin, config global icon, versionInfo, winresource, winmanifest, pyasm try: config = _load_data(configfilename) except IOError: print "You must run Configure.py before building!" sys.exit(1) target_platform = config.get('target_platform', sys.platform) target_iswin = target_platform[:3] == 'win' if target_platform == sys.platform: # _not_ cross compiling if config['pythonVersion'] != sys.version: print "The current version of Python is not the same with which PyInstaller was configured." print "Please re-run Configure.py with this version." sys.exit(1) if config.setdefault('pythonDebug', None) != __debug__: print "python optimization flags changed: rerun Configure.py with the same [-O] option" print "Configure.py optimize=%s, Build.py optimize=%s" % (not config['pythonDebug'], not __debug__) sys.exit(1) if iswin: import winmanifest if config['hasRsrcUpdate']: import icon, versionInfo, winresource pyasm = bindepend.getAssemblies(config['python']) else: pyasm = None if config['hasUPX']: setupUPXFlags() if not config['useELFEXE']: EXE.append_pkg = 0 build(specfile) from pyi_optparse import OptionParser parser = OptionParser('%prog [options] specfile') parser.add_option('-C', '--configfile', default=os.path.join(HOMEPATH, 'config.dat'), help='Name of generated configfile (default: %default)') parser.add_option('-o', '--buildpath', default=os.path.join('SPECPATH', 'build', 'pyi.TARGET_PLATFORM', 'SPECNAME'), help='Buildpath (default: %default)') parser.add_option('-y', '--noconfirm', action="store_true", default=False, help='Remove output directory (default: %s) without ' 'confirmation' % os.path.join('SPECPATH', 'dist')) if __name__ == '__main__': opts, args = parser.parse_args() if len(args) != 1: parser.error('Requires exactly one .spec-file') main(args[0], configfilename=opts.configfile) else: opts = parser.get_default_values()
Python
#! /usr/bin/env python # # Configure PyInstaller for the current Python installation. # # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os import sys import string import shutil import pprint import re import glob import mf import bindepend import Build HOME = os.path.dirname(sys.argv[0]) iswin = sys.platform[:3] == 'win' is24 = hasattr(sys, "version_info") and sys.version_info[:2] >= (2,4) cygwin = sys.platform == 'cygwin' if sys.platform == 'darwin' and Build.architecture() == '64bit': print "ERROR: PyInstaller does not support Python 64-bit on Mac OSX" print "Try using the 32-bit version of Python, by setting" print "VERSIONER_PYTHON_PREFER_32_BIT=yes in the environment" print "or run Python as 32-bit binary by command:" print "" print "arch -i386 python" sys.exit(2) def find_EXE_dependencies(config): global target_platform, target_iswin print "I: computing EXE_dependencies" python = opts.executable or sys.executable target_platform = opts.target_platform or sys.platform config['python'] = python config['target_platform'] = target_platform target_iswin = target_platform[:3] == 'win' xtrapath = [] if target_iswin and not iswin: # try to find a mounted Windows system xtrapath = glob.glob('/mnt/*/WINDOWS/system32/') if not xtrapath: print "E: Can not find a mounted Windows system" print "W: Please set 'xtrpath' in the config file yourself" xtrapath = config.get('xtrapath') or xtrapath config['xtrapath'] = xtrapath _useTK = """\ # Generated by Configure.py # This file is public domain import os, sys try: basedir = os.environ['_MEIPASS2'] except KeyError: basedir = sys.path[0] tcldir = os.path.join(basedir, '_MEI', '%s') tkdir = os.path.join(basedir, '_MEI', '%s') os.environ["TCL_LIBRARY"] = tcldir os.environ["TK_LIBRARY"] = tkdir os.putenv("TCL_LIBRARY", tcldir) os.putenv("TK_LIBRARY", tkdir) """ def test_TCL_TK(config): # TCL_root, TK_root and support/useTK.py print "I: Finding TCL/TK..." if not (target_iswin): saveexcludes = bindepend.excludes bindepend.excludes = {} if target_platform.startswith("win"): pattern = r'(?i)tcl(\d\d)\.dll' elif target_platform.startswith("linux"): pattern = r'libtcl(\d\.\d)?\.so' elif target_platform.startswith("darwin"): pattern = r'_tkinter' a = mf.ImportTracker() a.analyze_r('Tkinter') binaries = [] for modnm, mod in a.modules.items(): if isinstance(mod, mf.ExtensionModule): binaries.append((mod.__name__, mod.__file__, 'EXTENSION')) binaries.extend(bindepend.Dependencies(binaries)) binaries.extend(bindepend.Dependencies([('', sys.executable, '')])) for nm, fnm, typ in binaries: mo = re.match(pattern, nm) if not mo: continue if not target_platform.startswith("darwin"): ver = mo.group(1) tclbindir = os.path.dirname(fnm) if target_iswin: ver = ver[0] + '.' + ver[1:] elif ver is None: # we found "libtcl.so.0" so we need to get the version from the lib directory for name in os.listdir(tclbindir): mo = re.match(r'tcl(\d.\d)', name) if mo: ver = mo.group(1) print "I: found TCL/TK version %s" % ver open(os.path.join(HOME, 'support', 'useTK.py'), 'w').write(_useTK % ("tcl%s"%ver, "tk%s"%ver)) tclnm = 'tcl%s' % ver tknm = 'tk%s' % ver # Linux: /usr/lib with the .tcl files in /usr/lib/tcl8.3 and /usr/lib/tk8.3 # Windows: Python21/DLLs with the .tcl files in Python21/tcl/tcl8.3 and Python21/tcl/tk8.3 # or D:/Programs/Tcl/bin with the .tcl files in D:/Programs/Tcl/lib/tcl8.0 and D:/Programs/Tcl/lib/tk8.0 if target_iswin: for attempt in ['../tcl', '../lib']: if os.path.exists(os.path.join(tclbindir, attempt, tclnm)): config['TCL_root'] = os.path.join(tclbindir, attempt, tclnm) config['TK_root'] = os.path.join(tclbindir, attempt, tknm) config['TCL_dirname'] = os.path.basename(config['TCL_root']) config['TK_dirname'] = os.path.basename(config['TK_root']) break else: config['TCL_root'] = os.path.join(tclbindir, tclnm) config['TK_root'] = os.path.join(tclbindir, tknm) config['TCL_dirname'] = os.path.basename(config['TCL_root']) config['TK_dirname'] = os.path.basename(config['TK_root']) break elif target_platform.startswith("darwin"): tclbindir = os.path.dirname(fnm) print "I: found TCL/TK" tcldir = "Tcl.framework/Resources/Scripts" tkdir = "Tk.framework/Resources/Scripts" open(os.path.join(HOME, 'support', 'useTK.py'), 'w').write(_useTK % (tcldir, tkdir)) config['TCL_root'] = "/System/Library/Frameworks/Tcl.framework/Versions/Current" config['TK_root'] = "/System/Library/Frameworks/Tk.framework/Versions/Current" config['TCL_dirname'] = "Tcl.framework" config['TK_dirname'] = "Tk.framework" break else: print "I: could not find TCL/TK" if not target_iswin: bindepend.excludes = saveexcludes def test_Crypt(config): # TODO: disabled for now config["useCrypt"] = 0 return #Crypt support. We need to build the AES module and we'll use distutils # for that. FIXME: the day we'll use distutils for everything this will be # a solved problem. print "I: trying to build crypt support..." from distutils.core import run_setup cwd = os.getcwd() args = sys.argv[:] try: os.chdir(os.path.join(HOME, "source", "crypto")) dist = run_setup("setup.py", ["install"]) if dist.have_run.get("install", 0): config["useCrypt"] = 1 print "I: ... crypto support available" else: config["useCrypt"] = 0 print "I: ... error building crypto support" finally: os.chdir(cwd) sys.argv = args def test_Zlib(config): #useZLIB print "I: testing for Zlib..." try: import zlib config['useZLIB'] = 1 print 'I: ... Zlib available' except ImportError: config['useZLIB'] = 0 print 'I: ... Zlib unavailable' def test_RsrcUpdate(config): config['hasRsrcUpdate'] = 0 if not iswin: return # only available on windows print "I: Testing for ability to set icons, version resources..." try: import win32api, icon, versionInfo except ImportError, detail: print 'I: ... resource update unavailable -', detail return test_exe = os.path.join(HOME, 'support', 'loader', 'Windows-32bit', 'runw.exe') if not os.path.exists( test_exe ): config['hasRsrcUpdate'] = 0 print 'E: ... resource update unavailable - %s not found' % test_exe return # The test_exe may be read-only # make a writable copy and test using that rw_test_exe = os.path.join( os.environ['TEMP'], 'me_test_exe.tmp' ) shutil.copyfile( test_exe, rw_test_exe ) try: hexe = win32api.BeginUpdateResource(rw_test_exe, 0) except: print 'I: ... resource update unavailable - win32api.BeginUpdateResource failed' else: win32api.EndUpdateResource(hexe, 1) config['hasRsrcUpdate'] = 1 print 'I: ... resource update available' os.remove(rw_test_exe) _useUnicode = """\ # Generated by Configure.py # This file is public domain import %s """ _useUnicodeFN = os.path.join(HOME, 'support', 'useUnicode.py') def test_unicode(config): print 'I: Testing for Unicode support...' try: import codecs config['hasUnicode'] = 1 try: import encodings except ImportError: module = "codecs" else: module = "encodings" open(_useUnicodeFN, 'w').write(_useUnicode % module) print 'I: ... Unicode available' except ImportError: try: os.remove(_useUnicodeFN) except OSError: pass config['hasUnicode'] = 0 print 'I: ... Unicode NOT available' def test_UPX(config): print 'I: testing for UPX...' cmd = "upx" if opts.upx_dir: cmd = '"' + os.path.normpath(os.path.join(opts.upx_dir, cmd)) + '"' hasUPX = 0 try: vers = os.popen(cmd + ' -V').readlines() if vers: v = string.split(vers[0])[1] hasUPX = tuple(map(int, string.split(v, "."))) if iswin and is24 and hasUPX < (1,92): print 'E: UPX is too old! Python 2.4 under Windows requires UPX 1.92+' hasUPX = 0 print 'I: ...UPX %s' % (('unavailable','available')[hasUPX != 0]) except Exception, e: print 'I: ...exception result in testing for UPX' print e, e.args config['hasUPX'] = hasUPX config['upx_dir'] = opts.upx_dir def find_PYZ_dependencies(config): print "I: computing PYZ dependencies..." a = mf.ImportTracker([os.path.join(HOME, 'support')]) a.analyze_r('archive') mod = a.modules['archive'] toc = Build.TOC([(mod.__name__, mod.__file__, 'PYMODULE')]) for i in range(len(toc)): nm, fnm, typ = toc[i] mod = a.modules[nm] tmp = [] for importednm, isdelayed, isconditional, level in mod.imports: if not isconditional: realnms = a.analyze_one(importednm, nm) for realnm in realnms: imported = a.modules[realnm] if not isinstance(imported, mf.BuiltinModule): tmp.append((imported.__name__, imported.__file__, imported.typ)) toc.extend(tmp) toc.reverse() config['PYZ_dependencies'] = toc.data def main(configfilename): try: config = Build._load_data(configfilename) print 'I: read old config from', configfilename except IOError, SyntaxError: # IOerror: file not present/readable # SyntaxError: invalid file (platform change?) # if not set by Make.py we can assume Windows config = {'useELFEXE': 1} # Save Python version, to detect and avoid conflicts config["pythonVersion"] = sys.version config["pythonDebug"] = __debug__ find_EXE_dependencies(config) test_TCL_TK(config) test_Zlib(config) test_Crypt(config) test_RsrcUpdate(config) test_unicode(config) test_UPX(config) find_PYZ_dependencies(config) Build._save_data(configfilename, config) print "I: done generating", configfilename if __name__ == '__main__': from pyi_optparse import OptionParser parser = OptionParser(usage="%prog [options]") parser.add_option('--target-platform', default=None, help='Target platform, required for cross-bundling ' '(default: current platform).') parser.add_option('--upx-dir', default=None, help='Directory containing UPX.') parser.add_option('--executable', default=None, help='Python executable to use. Required for ' 'cross-bundling.') parser.add_option('-C', '--configfile', default=os.path.join(HOME, 'config.dat'), help='Name of generated configfile (default: %default)') opts, args = parser.parse_args() if args: parser.error('Does not expect any arguments') main(opts.configfile)
Python
"""optik.option Defines the Option class and some standard value-checking functions. """ # Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved. # See the README.txt distributed with Optik for licensing terms. import sys import types, string from pyi_optik.errors import OptionError, OptionValueError, gettext _ = gettext __revision__ = "$Id: option.py 470 2004-12-07 01:39:56Z gward $" __all__ = ['Option'] # Do the right thing with boolean values for all known Python versions. try: True, False except NameError: (True, False) = (1, 0) # For Python 1.5, just ignore unicode (try it as str) try: unicode except NameError: unicode=str try: types.UnicodeType except AttributeError: types.UnicodeType = types.StringType _idmax = 2L * sys.maxint + 1 def _repr(self): return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self) & _idmax, self) def _parse_num(val, type): if string.lower(val[:2]) == "0x": # hexadecimal radix = 16 elif string.lower(val[:2]) == "0b": # binary radix = 2 val = val[2:] or "0" # have to remove "0b" prefix elif val[:1] == "0": # octal radix = 8 else: # decimal radix = 10 try: return type(val, radix) except TypeError: # In Python pre-2.0, int() and long() did not support the radix # argument. We catch the type error (not to be confused with ValueError, # which is a real parsing failure), and try again with string.atol. return type(string.atol(val, radix)) def _parse_int(val): return _parse_num(val, int) def _parse_long(val): return _parse_num(val, long) _builtin_cvt = { "int" : (_parse_int, _("integer")), "long" : (_parse_long, _("long integer")), "float" : (float, _("floating-point")), "complex" : (complex, _("complex")) } def check_builtin(option, opt, value): (cvt, what) = _builtin_cvt[option.type] try: return cvt(value) except ValueError: raise OptionValueError( _("option %s: invalid %s value: %s") % (opt, what, repr(value))) def check_choice(option, opt, value): if value in option.choices: return value else: choices = string.join(map(repr, option.choices), ", ") raise OptionValueError( _("option %s: invalid choice: %s (choose from %s)") % (opt, repr(value), choices)) # Not supplying a default is different from a default of None, # so we need an explicit "not supplied" value. NO_DEFAULT = ("NO", "DEFAULT") class Option: """ Instance attributes: _short_opts : [string] _long_opts : [string] action : string type : string dest : string default : any nargs : int const : any choices : [string] callback : function callback_args : (any*) callback_kwargs : { string : any } help : string metavar : string """ # The list of instance attributes that may be set through # keyword args to the constructor. ATTRS = ['action', 'type', 'dest', 'default', 'nargs', 'const', 'choices', 'callback', 'callback_args', 'callback_kwargs', 'help', 'metavar'] # The set of actions allowed by option parsers. Explicitly listed # here so the constructor can validate its arguments. ACTIONS = ("store", "store_const", "store_true", "store_false", "append", "append_const", "count", "callback", "help", "version") # The set of actions that involve storing a value somewhere; # also listed just for constructor argument validation. (If # the action is one of these, there must be a destination.) STORE_ACTIONS = ("store", "store_const", "store_true", "store_false", "append", "append_const", "count") # The set of actions for which it makes sense to supply a value # type, ie. which may consume an argument from the command line. TYPED_ACTIONS = ("store", "append", "callback") # The set of actions which *require* a value type, ie. that # always consume an argument from the command line. ALWAYS_TYPED_ACTIONS = ("store", "append") # The set of actions which take a 'const' attribute. CONST_ACTIONS = ("store_const", "append_const") # The set of known types for option parsers. Again, listed here for # constructor argument validation. TYPES = ("string", "int", "long", "float", "complex", "choice") # Dictionary of argument checking functions, which convert and # validate option arguments according to the option type. # # Signature of checking functions is: # check(option : Option, opt : string, value : string) -> any # where # option is the Option instance calling the checker # opt is the actual option seen on the command-line # (eg. "-a", "--file") # value is the option argument seen on the command-line # # The return value should be in the appropriate Python type # for option.type -- eg. an integer if option.type == "int". # # If no checker is defined for a type, arguments will be # unchecked and remain strings. TYPE_CHECKER = { "int" : check_builtin, "long" : check_builtin, "float" : check_builtin, "complex": check_builtin, "choice" : check_choice, } # CHECK_METHODS is a list of unbound method objects; they are called # by the constructor, in order, after all attributes are # initialized. The list is created and filled in later, after all # the methods are actually defined. (I just put it here because I # like to define and document all class attributes in the same # place.) Subclasses that add another _check_*() method should # define their own CHECK_METHODS list that adds their check method # to those from this class. CHECK_METHODS = None # -- Constructor/initialization methods ---------------------------- def __init__(self, *opts, **attrs): # Set _short_opts, _long_opts attrs from 'opts' tuple. # Have to be set now, in case no option strings are supplied. self._short_opts = [] self._long_opts = [] opts = self._check_opt_strings(opts) self._set_opt_strings(opts) # Set all other attrs (action, type, etc.) from 'attrs' dict self._set_attrs(attrs) # Check all the attributes we just set. There are lots of # complicated interdependencies, but luckily they can be farmed # out to the _check_*() methods listed in CHECK_METHODS -- which # could be handy for subclasses! The one thing these all share # is that they raise OptionError if they discover a problem. for checker in self.CHECK_METHODS: checker(self) def _check_opt_strings(self, opts): # Filter out None because early versions of Optik had exactly # one short option and one long option, either of which # could be None. opts = filter(None, opts) if not opts: raise TypeError("at least one option string must be supplied") return opts def _set_opt_strings(self, opts): for opt in opts: if len(opt) < 2: raise OptionError( "invalid option string %s: " "must be at least two characters long" % repr(opt), self) elif len(opt) == 2: if not (opt[0] == "-" and opt[1] != "-"): raise OptionError( "invalid short option string %s: " "must be of the form -x, (x any non-dash char)" % repr(opt), self) self._short_opts.append(opt) else: if not (opt[0:2] == "--" and opt[2] != "-"): raise OptionError( "invalid long option string %s: " "must start with --, followed by non-dash" % repr(opt), self) self._long_opts.append(opt) def _set_attrs(self, attrs): for attr in self.ATTRS: if attrs.has_key(attr): setattr(self, attr, attrs[attr]) del attrs[attr] else: if attr == 'default': setattr(self, attr, NO_DEFAULT) else: setattr(self, attr, None) if attrs: raise OptionError( "invalid keyword arguments: %s" % string.join(attrs.keys(), ", "), self) # -- Constructor validation methods -------------------------------- def _check_action(self): if self.action is None: self.action = "store" elif self.action not in self.ACTIONS: raise OptionError("invalid action: %s" % repr(self.action), self) def _check_type(self): if self.type is None: if self.action in self.ALWAYS_TYPED_ACTIONS: if self.choices is not None: # The "choices" attribute implies "choice" type. self.type = "choice" else: # No type given? "string" is the most sensible default. self.type = "string" else: # Allow type objects as an alternative to their names. if hasattr(self.type, "__name__"): self.type = self.type.__name__ if self.type == "str": self.type = "string" if self.type not in self.TYPES: raise OptionError("invalid option type: %s" % repr(self.type), self) if self.action not in self.TYPED_ACTIONS: raise OptionError( "must not supply a type for action %s" % repr(self.action), self) def _check_choice(self): if self.type == "choice": if self.choices is None: raise OptionError( "must supply a list of choices for type 'choice'", self) elif type(self.choices) not in (types.TupleType, types.ListType): raise OptionError( "choices must be a list of strings ('%s' supplied)" % string.split(str(type(self.choices)), "'")[1], self) elif self.choices is not None: raise OptionError( "must not supply choices for type %s" % repr(self.type), self) def _check_dest(self): # No destination given, and we need one for this action. The # self.type check is for callbacks that take a value. takes_value = (self.action in self.STORE_ACTIONS or self.type is not None) if self.dest is None and takes_value: # Glean a destination from the first long option string, # or from the first short option string if no long options. if self._long_opts: # eg. "--foo-bar" -> "foo_bar" self.dest = string.replace(self._long_opts[0][2:], '-', '_') else: self.dest = self._short_opts[0][1] def _check_const(self): if self.action not in self.CONST_ACTIONS and self.const is not None: raise OptionError( "'const' must not be supplied for action %s" % repr(self.action), self) def _check_nargs(self): if self.action in self.TYPED_ACTIONS: if self.nargs is None: self.nargs = 1 elif self.nargs is not None: raise OptionError( "'nargs' must not be supplied for action %s" % repr(self.action), self) def _check_callback(self): if self.action == "callback": if not callable(self.callback): raise OptionError( "callback not callable: %s" % repr(self.callback), self) if (self.callback_args is not None and type(self.callback_args) is not types.TupleType): raise OptionError( "callback_args, if supplied, must be a tuple: not %s" % repr(self.callback_args), self) if (self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType): raise OptionError( "callback_kwargs, if supplied, must be a dict: not %s" % repr(self.callback_kwargs), self) else: if self.callback is not None: raise OptionError( "callback supplied (%s) for non-callback option" % repr(self.callback), self) if self.callback_args is not None: raise OptionError( "callback_args supplied for non-callback option", self) if self.callback_kwargs is not None: raise OptionError( "callback_kwargs supplied for non-callback option", self) CHECK_METHODS = [_check_action, _check_type, _check_choice, _check_dest, _check_const, _check_nargs, _check_callback] # -- Miscellaneous methods ----------------------------------------- def __str__(self): return string.join(self._short_opts + self._long_opts, "/") __repr__ = _repr def takes_value(self): return self.type is not None def get_opt_string(self): if self._long_opts: return self._long_opts[0] else: return self._short_opts[0] # -- Processing methods -------------------------------------------- def check_value(self, opt, value): checker = self.TYPE_CHECKER.get(self.type) if checker is None: return value else: return checker(self, opt, value) def convert_value(self, opt, value): if value is not None: if self.nargs == 1: return self.check_value(opt, value) else: return tuple(map(lambda v,self=self,opt=opt: self.check_value(opt, v), value)) def process(self, opt, value, values, parser): # First, convert the value(s) to the right type. Howl if any # value(s) are bogus. value = self.convert_value(opt, value) # And then take whatever action is expected of us. # This is a separate method to make life easier for # subclasses to add new actions. return self.take_action( self.action, self.dest, opt, value, values, parser) def take_action(self, action, dest, opt, value, values, parser): if action == "store": setattr(values, dest, value) elif action == "store_const": setattr(values, dest, self.const) elif action == "store_true": setattr(values, dest, True) elif action == "store_false": setattr(values, dest, False) elif action == "append": values.ensure_value(dest, []).append(value) elif action == "append_const": values.ensure_value(dest, []).append(self.const) elif action == "count": setattr(values, dest, values.ensure_value(dest, 0) + 1) elif action == "callback": args = self.callback_args or () kwargs = self.callback_kwargs or {} apply(self.callback, (self, opt, value, parser)+args, kwargs) elif action == "help": parser.print_help() parser.exit() elif action == "version": parser.print_version() parser.exit() else: raise RuntimeError, "unknown action %s" % repr(self.action) return 1 # class Option
Python
"""optik.option_parser Provides the OptionParser and Values classes. """ # Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved. # See the README.txt distributed with Optik for licensing terms. import sys, os import types, string from pyi_optik.option import Option, NO_DEFAULT, _repr from pyi_optik.help import IndentedHelpFormatter from pyi_optik import errors from pyi_optik.errors import gettext _ = gettext __revision__ = "$Id: option_parser.py 470 2004-12-07 01:39:56Z gward $" __all__ = ['SUPPRESS_HELP', 'SUPPRESS_USAGE', 'Values', 'OptionContainer', 'OptionGroup', 'OptionParser'] SUPPRESS_HELP = "SUPPRESS"+"HELP" SUPPRESS_USAGE = "SUPPRESS"+"USAGE" # For compatibility with Python 2.2 try: True, False except NameError: (True, False) = (1, 0) def isbasestring(x): return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType) if not hasattr(string, "startswith"): def startswith(s, prefix): return s[:len(prefix)] == prefix string.startswith = startswith class Values: def __init__(self, defaults=None): if defaults: for (attr, val) in defaults.items(): setattr(self, attr, val) def __str__(self): return str(self.__dict__) __repr__ = _repr def __cmp__(self, other): if isinstance(other, Values): return cmp(self.__dict__, other.__dict__) elif isinstance(other, types.DictType): return cmp(self.__dict__, other) else: return -1 def _update_careful(self, dict): """ Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored. """ for attr in dir(self): if dict.has_key(attr): dval = dict[attr] if dval is not None: setattr(self, attr, dval) def _update_loose(self, dict): """ Update the option values from an arbitrary dictionary, using all keys from the dictionary regardless of whether they have a corresponding attribute in self or not. """ self.__dict__.update(dict) def _update(self, dict, mode): if mode == "careful": self._update_careful(dict) elif mode == "loose": self._update_loose(dict) else: raise ValueError, "invalid update mode: %s" % repr(mode) def read_module(self, modname, mode="careful"): __import__(modname) mod = sys.modules[modname] self._update(vars(mod), mode) def read_file(self, filename, mode="careful"): vars = {} execfile(filename, vars) self._update(vars, mode) def ensure_value(self, attr, value): if not hasattr(self, attr) or getattr(self, attr) is None: setattr(self, attr, value) return getattr(self, attr) class OptionContainer: """ Abstract base class. Class attributes: standard_option_list : [Option] list of standard options that will be accepted by all instances of this parser class (intended to be overridden by subclasses). Instance attributes: option_list : [Option] the list of Option objects contained by this OptionContainer _short_opt : { string : Option } dictionary mapping short option strings, eg. "-f" or "-X", to the Option instances that implement them. If an Option has multiple short option strings, it will appears in this dictionary multiple times. [1] _long_opt : { string : Option } dictionary mapping long option strings, eg. "--file" or "--exclude", to the Option instances that implement them. Again, a given Option can occur multiple times in this dictionary. [1] defaults : { string : any } dictionary mapping option destination names to default values for each destination [1] [1] These mappings are common to (shared by) all components of the controlling OptionParser, where they are initially created. """ def __init__(self, option_class, conflict_handler, description): # Initialize the option list and related data structures. # This method must be provided by subclasses, and it must # initialize at least the following instance attributes: # option_list, _short_opt, _long_opt, defaults. self._create_option_list() self.option_class = option_class self.set_conflict_handler(conflict_handler) self.set_description(description) def _create_option_mappings(self): # For use by OptionParser constructor -- create the master # option mappings used by this OptionParser and all # OptionGroups that it owns. self._short_opt = {} # single letter -> Option instance self._long_opt = {} # long option -> Option instance self.defaults = {} # maps option dest -> default value def _share_option_mappings(self, parser): # For use by OptionGroup constructor -- use shared option # mappings from the OptionParser that owns this OptionGroup. self._short_opt = parser._short_opt self._long_opt = parser._long_opt self.defaults = parser.defaults def set_conflict_handler(self, handler): if handler not in ("error", "resolve"): raise ValueError, "invalid conflict_resolution value %s" % repr(handler) self.conflict_handler = handler def set_description(self, description): self.description = description def get_description(self): return self.description # -- Option-adding methods ----------------------------------------- def _check_conflict(self, option): conflict_opts = [] for opt in option._short_opts: if self._short_opt.has_key(opt): conflict_opts.append((opt, self._short_opt[opt])) for opt in option._long_opts: if self._long_opt.has_key(opt): conflict_opts.append((opt, self._long_opt[opt])) if conflict_opts: handler = self.conflict_handler if handler == "error": opts = [] for co in conflict_opts: opts.append(co[0]) raise errors.OptionConflictError( "conflicting option string(s): %s" % string.join(opts, ", "), option) elif handler == "resolve": for (opt, c_option) in conflict_opts: if string.startswith(opt, "--"): c_option._long_opts.remove(opt) del self._long_opt[opt] else: c_option._short_opts.remove(opt) del self._short_opt[opt] if not (c_option._short_opts or c_option._long_opts): c_option.container.option_list.remove(c_option) def add_option(self, *args, **kwargs): """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ if type(args[0]) is types.StringType: option = apply(self.option_class, args, kwargs) elif len(args) == 1 and not kwargs: option = args[0] if not isinstance(option, Option): raise TypeError, "not an Option instance: %s" % repr(option) else: raise TypeError, "invalid arguments" self._check_conflict(option) self.option_list.append(option) option.container = self for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option if option.dest is not None: # option has a dest, we need a default if option.default is not NO_DEFAULT: self.defaults[option.dest] = option.default elif not self.defaults.has_key(option.dest): self.defaults[option.dest] = None return option def add_options(self, option_list): for option in option_list: self.add_option(option) # -- Option query/removal methods ---------------------------------- def get_option(self, opt_str): return (self._short_opt.get(opt_str) or self._long_opt.get(opt_str)) def has_option(self, opt_str): return (self._short_opt.has_key(opt_str) or self._long_opt.has_key(opt_str)) def remove_option(self, opt_str): option = self._short_opt.get(opt_str) if option is None: option = self._long_opt.get(opt_str) if option is None: raise ValueError("no such option %s" % repr(opt_str)) for opt in option._short_opts: del self._short_opt[opt] for opt in option._long_opts: del self._long_opt[opt] option.container.option_list.remove(option) # -- Help-formatting methods --------------------------------------- def format_option_help(self, formatter): if not self.option_list: return "" result = [] for option in self.option_list: if not option.help is SUPPRESS_HELP: result.append(formatter.format_option(option)) return string.join(result, "") def format_description(self, formatter): return formatter.format_description(self.get_description()) def format_help(self, formatter): result = [] if self.description: result.append(self.format_description(formatter)) if self.option_list: result.append(self.format_option_help(formatter)) return string.join(result, "\n") class OptionGroup (OptionContainer): def __init__(self, parser, title, description=None): self.parser = parser OptionContainer.__init__( self, parser.option_class, parser.conflict_handler, description) self.title = title def _create_option_list(self): self.option_list = [] self._share_option_mappings(self.parser) def set_title(self, title): self.title = title # -- Help-formatting methods --------------------------------------- def format_help(self, formatter): result = formatter.format_heading(self.title) formatter.indent() result = result + OptionContainer.format_help(self, formatter) formatter.dedent() return result class OptionParser (OptionContainer): """ Class attributes: standard_option_list : [Option] list of standard options that will be accepted by all instances of this parser class (intended to be overridden by subclasses). Instance attributes: usage : string a usage string for your program. Before it is displayed to the user, "%prog" will be expanded to the name of your program (self.prog or os.path.basename(sys.argv[0])). prog : string the name of the current program (to override os.path.basename(sys.argv[0])). option_groups : [OptionGroup] list of option groups in this parser (option groups are irrelevant for parsing the command-line, but very useful for generating help) allow_interspersed_args : bool = true if true, positional arguments may be interspersed with options. Assuming -a and -b each take a single argument, the command-line -ablah foo bar -bboo baz will be interpreted the same as -ablah -bboo -- foo bar baz If this flag were false, that command line would be interpreted as -ablah -- foo bar -bboo baz -- ie. we stop processing options as soon as we see the first non-option argument. (This is the tradition followed by Python's getopt module, Perl's Getopt::Std, and other argument- parsing libraries, but it is generally annoying to users.) process_default_values : bool = true if true, option default values are processed similarly to option values from the command line: that is, they are passed to the type-checking function for the option's type (as long as the default value is a string). (This really only matters if you have defined custom types; see SF bug #955889.) Set it to false to restore the behaviour of Optik 1.4.1 and earlier. rargs : [string] the argument list currently being parsed. Only set when parse_args() is active, and continually trimmed down as we consume arguments. Mainly there for the benefit of callback options. largs : [string] the list of leftover arguments that we have skipped while parsing options. If allow_interspersed_args is false, this list is always empty. values : Values the set of option values currently being accumulated. Only set when parse_args() is active. Also mainly for callbacks. Because of the 'rargs', 'largs', and 'values' attributes, OptionParser is not thread-safe. If, for some perverse reason, you need to parse command-line arguments simultaneously in different threads, use different OptionParser instances. """ standard_option_list = [] def __init__(self, usage=None, option_list=None, option_class=Option, version=None, conflict_handler="error", description=None, formatter=None, add_help_option=True, prog=None): OptionContainer.__init__( self, option_class, conflict_handler, description) self.set_usage(usage) self.prog = prog self.version = version self.allow_interspersed_args = True self.process_default_values = True if formatter is None: formatter = IndentedHelpFormatter() self.formatter = formatter self.formatter.set_parser(self) # Populate the option list; initial sources are the # standard_option_list class attribute, the 'option_list' # argument, and (if applicable) the _add_version_option() and # _add_help_option() methods. self._populate_option_list(option_list, add_help=add_help_option) self._init_parsing_state() # -- Private methods ----------------------------------------------- # (used by our or OptionContainer's constructor) def _create_option_list(self): self.option_list = [] self.option_groups = [] self._create_option_mappings() def _add_help_option(self): self.add_option("-h", "--help", action="help", help=_("show this help message and exit")) def _add_version_option(self): self.add_option("--version", action="version", help=_("show program's version number and exit")) def _populate_option_list(self, option_list, add_help=True): if self.standard_option_list: self.add_options(self.standard_option_list) if option_list: self.add_options(option_list) if self.version: self._add_version_option() if add_help: self._add_help_option() def _init_parsing_state(self): # These are set in parse_args() for the convenience of callbacks. self.rargs = None self.largs = None self.values = None # -- Simple modifier methods --------------------------------------- def set_usage(self, usage): if usage is None: self.usage = _("%prog [options]") elif usage is SUPPRESS_USAGE: self.usage = None # For backwards compatibility with Optik 1.3 and earlier. elif string.startswith(usage, "usage:" + " "): self.usage = usage[7:] else: self.usage = usage def enable_interspersed_args(self): self.allow_interspersed_args = True def disable_interspersed_args(self): self.allow_interspersed_args = False def set_process_default_values(self, process): self.process_default_values = process def set_default(self, dest, value): self.defaults[dest] = value def set_defaults(self, **kwargs): self.defaults.update(kwargs) def _get_all_options(self): options = self.option_list[:] for group in self.option_groups: options.extend(group.option_list) return options def get_default_values(self): if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return Values(self.defaults) defaults = self.defaults.copy() for option in self._get_all_options(): default = defaults.get(option.dest) if isbasestring(default): opt_str = option.get_opt_string() defaults[option.dest] = option.check_value(opt_str, default) return Values(defaults) # -- OptionGroup methods ------------------------------------------- def add_option_group(self, *args, **kwargs): # XXX lots of overlap with OptionContainer.add_option() if type(args[0]) is types.StringType: group = apply(OptionGroup, (self,) + args, kwargs) elif len(args) == 1 and not kwargs: group = args[0] if not isinstance(group, OptionGroup): raise TypeError, "not an OptionGroup instance: %s" % repr(group) if group.parser is not self: raise ValueError, "invalid OptionGroup (wrong parser)" else: raise TypeError, "invalid arguments" self.option_groups.append(group) return group def get_option_group(self, opt_str): option = (self._short_opt.get(opt_str) or self._long_opt.get(opt_str)) if option and option.container is not self: return option.container return None # -- Option-parsing methods ---------------------------------------- def _get_args(self, args): if args is None: return sys.argv[1:] else: return args[:] # don't modify caller's list def parse_args(self, args=None, values=None): """ parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options. """ rargs = self._get_args(args) if values is None: values = self.get_default_values() # Store the halves of the argument list as attributes for the # convenience of callbacks: # rargs # the rest of the command-line (the "r" stands for # "remaining" or "right-hand") # largs # the leftover arguments -- ie. what's left after removing # options and their arguments (the "l" stands for "leftover" # or "left-hand") self.rargs = rargs self.largs = largs = [] self.values = values try: stop = self._process_args(largs, rargs, values) except (errors.BadOptionError, errors.OptionValueError), err: self.error(str(err)) args = largs + rargs return self.check_values(values, args) def check_values(self, values, args): """ check_values(values : Values, args : [string]) -> (values : Values, args : [string]) Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new -- whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired. """ return (values, args) def _process_args(self, largs, rargs, values): """_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in 'largs'. """ while rargs: arg = rargs[0] # We handle bare "--" explicitly, and bare "-" is handled by the # standard arg handler since the short arg case ensures that the # len of the opt string is greater than 1. if arg == "--": del rargs[0] return elif arg[0:2] == "--": # process a single long option (possibly with value(s)) self._process_long_opt(rargs, values) elif arg[:1] == "-" and len(arg) > 1: # process a cluster of short options (possibly with # value(s) for the last one only) self._process_short_opts(rargs, values) elif self.allow_interspersed_args: largs.append(arg) del rargs[0] else: return # stop now, leave this arg in rargs # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset! def _match_long_opt(self, opt): """_match_long_opt(opt : string) -> string Determine which long option string 'opt' matches, ie. which one it is an unambiguous abbrevation for. Raises BadOptionError if 'opt' doesn't unambiguously match any long option string. """ return _match_abbrev(opt, self._long_opt) def _process_long_opt(self, rargs, values): arg = rargs.pop(0) # Value explicitly attached to arg? Pretend it's the next # argument. if "=" in arg: (opt, next_arg) = string.split(arg, "=", 1) rargs.insert(0, next_arg) had_explicit_value = True else: opt = arg had_explicit_value = False opt = self._match_long_opt(opt) option = self._long_opt[opt] if option.takes_value(): nargs = option.nargs if len(rargs) < nargs: if nargs == 1: self.error(_("%s option requires an argument") % opt) else: self.error(_("%s option requires %d arguments") % (opt, nargs)) elif nargs == 1: value = rargs.pop(0) else: value = tuple(rargs[0:nargs]) del rargs[0:nargs] elif had_explicit_value: self.error(_("%s option does not take a value") % opt) else: value = None option.process(opt, value, values, self) def _process_short_opts(self, rargs, values): arg = rargs.pop(0) stop = False i = 1 for ch in arg[1:]: opt = "-" + ch option = self._short_opt.get(opt) i = i+1 # we have consumed a character if not option: raise errors.BadOptionError(opt) #self.error(_("no such option: %s") % opt) if option.takes_value(): # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): rargs.insert(0, arg[i:]) stop = True nargs = option.nargs if len(rargs) < nargs: if nargs == 1: self.error(_("%s option requires an argument") % opt) else: self.error(_("%s option requires %d arguments") % (opt, nargs)) elif nargs == 1: value = rargs.pop(0) else: value = tuple(rargs[0:nargs]) del rargs[0:nargs] else: # option doesn't take a value value = None option.process(opt, value, values, self) if stop: break # -- Feedback methods ---------------------------------------------- def get_prog_name(self): if self.prog is None: return os.path.basename(sys.argv[0]) else: return self.prog def expand_prog_name(self, s): return string.replace(s, "%prog", self.get_prog_name()) def get_description(self): return self.expand_prog_name(self.description) def exit(self, status=0, msg=None): if msg: sys.stderr.write(msg) sys.exit(status) def error(self, msg): """error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(sys.stderr) self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg)) def get_usage(self): if self.usage: return self.formatter.format_usage( self.expand_prog_name(self.usage)) else: return "" def print_usage(self, file=None): """print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to 'file' (default stdout). Any occurence of the string "%prog" in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined. """ if self.usage: if file is None: file = sys.stdout file.write(self.get_usage() + "\n") def get_version(self): if self.version: return self.expand_prog_name(self.version) else: return "" def print_version(self, file=None): """print_version(file : file = stdout) Print the version message for this program (self.version) to 'file' (default stdout). As with print_usage(), any occurence of "%prog" in self.version is replaced by the current program's name. Does nothing if self.version is empty or undefined. """ if self.version: if file is None: file = sys.stdout file.write(self.get_version() + "\n") def format_option_help(self, formatter=None): if formatter is None: formatter = self.formatter formatter.store_option_strings(self) result = [] result.append(formatter.format_heading(_("options"))) formatter.indent() if self.option_list: result.append(OptionContainer.format_option_help(self, formatter)) result.append("\n") for group in self.option_groups: result.append(group.format_help(formatter)) result.append("\n") formatter.dedent() # Drop the last "\n", or the header if no options or option groups: return string.join(result[:-1], "") def format_help(self, formatter=None): if formatter is None: formatter = self.formatter result = [] if self.usage: result.append(self.get_usage() + "\n") if self.description: result.append(self.format_description(formatter) + "\n") result.append(self.format_option_help(formatter)) return string.join(result, "") def print_help(self, file=None): """print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout). """ if file is None: file = sys.stdout file.write(self.format_help()) # class OptionParser def _match_abbrev(s, wordmap): """_match_abbrev(s : string, wordmap : {string : Option}) -> string Return the string key in 'wordmap' for which 's' is an unambiguous abbreviation. If 's' is found to be ambiguous or doesn't match any of 'words', raise BadOptionError. """ # Is there an exact match? if wordmap.has_key(s): return s else: # Isolate all words with s as a prefix. possibilities = [] for word in wordmap.keys(): if string.startswith(word, s): possibilities.append(word) # No exact match, so there had better be just one possibility. if len(possibilities) == 1: return possibilities[0] elif not possibilities: raise errors.BadOptionError(s) else: # More than one possible completion: ambiguous prefix. raise errors.AmbiguousOptionError(s, possibilities)
Python
"""optik.errors Exception classes used by Optik. """ # Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved. # See the README.txt distributed with Optik for licensing terms. import string try: from gettext import gettext except ImportError: def gettext(message): return message _ = gettext __revision__ = "$Id: errors.py 470 2004-12-07 01:39:56Z gward $" __all__ = ['OptikError', 'OptionError', 'OptionConflictError', 'OptionValueError', 'BadOptionError'] class OptikError (Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg class OptionError (OptikError): """ Raised if an Option instance is created with invalid or inconsistent arguments. """ def __init__(self, msg, option): self.msg = msg self.option_id = str(option) def __str__(self): if self.option_id: return "option %s: %s" % (self.option_id, self.msg) else: return self.msg class OptionConflictError (OptionError): """ Raised if conflicting options are added to an OptionParser. """ class OptionValueError (OptikError): """ Raised if an invalid option value is encountered on the command line. """ class BadOptionError (OptikError): """ Raised if an invalid option is seen on the command line. """ def __init__(self, opt_str): self.opt_str = opt_str def __str__(self): return _("no such option: %s") % self.opt_str class AmbiguousOptionError (BadOptionError): """ Raised if an ambiguous option is seen on the command line. """ def __init__(self, opt_str, possibilities): BadOptionError.__init__(self, opt_str) self.possibilities = possibilities def __str__(self): return (_("ambiguous option: %s (%s?)") % (self.opt_str, string.join(self.possibilities, ", ")))
Python
"""Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward <gward@python.net> __revision__ = "$Id: textwrap.py,v 1.35 2004/06/03 01:59:40 gward Exp $" import string, re import types # Do the right thing with boolean values for all known Python versions # (so this module can be copied to projects that don't depend on Python # 2.3, e.g. Optik and Docutils). try: True, False except NameError: (True, False) = (1, 0) # For Python 1.5, just ignore unicode (try it as str) try: unicode except NameError: unicode=str __all__ = ['TextWrapper', 'wrap', 'fill'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales # that character winds up in string.whitespace. Respecting # string.whitespace in those cases would 1) make textwrap treat 0xa0 the # same as any other whitespace char, which is clearly wrong (it's a # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 1 .. 8 spaces, depending on its position in its line. If false, each tab is treated as a single character. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. """ whitespace_trans = string.maketrans(_whitespace, ' ' * len(_whitespace)) unicode_whitespace_trans = {} uspace = ord(unicode(' ')) for x in map(ord, _whitespace): unicode_whitespace_trans[x] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). try: wordsep_re = re.compile(r'(\s+|' # any whitespace r'[^\s\w]*\w{2,}-(?=\w{2,})|' # hyphenated words r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash except: # Under python 1.5, the above regular expression does not compile because # of positive look-behind assertions (?<=). This stripped down version # does but it causes some regressions in the testsuite. Better than # nothing... wordsep_re = re.compile(r'(\s+|' # any whitespace r'[^\s\w]*\w{2,}-(?=\w{2,})|' # hyphenated words r')') # em-dash # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[%s]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote % string.lowercase) def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = string.expandtabs(text) if self.replace_whitespace: if isinstance(text, types.StringType): text = string.translate(text, self.whitespace_trans) elif isinstance(text, types.UnicodeType): # This has to be Python 2.0+ (no unicode before), so # use directly string methods (the string module does not # support translate() with dictionary for unicode). text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' """ chunks = self.wordsep_re.split(text) chunks = filter(None, chunks) return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 pat = self.sentence_end_re while i < len(chunks)-1: if chunks[i+1] == " " and pat.search(chunks[i]): chunks[i+1] = " " i = i+2 else: i = i+1 def _handle_long_word(self, chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ space_left = max(width - cur_len, 1) # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(chunks[0][0:space_left]) chunks[0] = chunks[0][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(chunks.pop(0)) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if string.strip(chunks[0]) == '' and lines: del chunks[0] while chunks: l = len(chunks[0]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop(0)) cur_len = cur_len + l # Nope, this line is full. else: break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[0]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) # If the last chunk on this line is all whitespace, drop it. if cur_line and string.strip(cur_line[-1]) == '': del cur_line[-1] # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + string.join(cur_line, '')) return lines # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ text = self._munge_whitespace(text) indent = self.initial_indent chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return string.join(self.wrap(text), "\n") # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ kwargs["width"] = width w = apply(TextWrapper, (), kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ kwargs["width"] = width w = apply(TextWrapper, (), kwargs) return w.fill(text) # -- Loosely related functionality ------------------------------------- def dedent(text): """dedent(text : string) -> string Remove any whitespace than can be uniformly removed from the left of every line in `text`. This can be used e.g. to make triple-quoted strings line up with the left edge of screen/whatever, while still presenting it in the source code in indented form. For example: def test(): # end first line with \ to avoid the empty line! s = '''\ hello world ''' print repr(s) # prints ' hello\n world\n ' print repr(dedent(s)) # prints 'hello\n world\n' """ lines = string.split(string.expandtabs(text), '\n') margin = None for line in lines: content = string.lstrip(line) if not content: continue indent = len(line) - len(content) if margin is None: margin = indent else: margin = min(margin, indent) if margin is not None and margin > 0: for i in range(len(lines)): lines[i] = lines[i][margin:] return string.join(lines, "\n")
Python
"""optik.help Provides HelpFormatter and subclasses -- used by OptionParser to generate formatted help text. """ # Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved. # See the README.txt distributed with Optik for licensing terms. import os import string import textwrap from pyi_optik.option import NO_DEFAULT from pyi_optik.errors import gettext _ = gettext __revision__ = "$Id: help.py 470 2004-12-07 01:39:56Z gward $" __all__ = ['HelpFormatter', 'IndentedHelpFormatter', 'TitledHelpFormatter'] class HelpFormatter: """ Abstract base class for formatting option help. OptionParser instances should use one of the HelpFormatter subclasses for formatting help; by default IndentedHelpFormatter is used. Instance attributes: parser : OptionParser the controlling OptionParser instance indent_increment : int the number of columns to indent per nesting level max_help_position : int the maximum starting column for option help text help_position : int the calculated starting column for option help text; initially the same as the maximum width : int total number of columns for output (pass None to constructor for this value to be taken from the $COLUMNS environment variable) level : int current indentation level current_indent : int current indentation level (in columns) help_width : int number of columns available for option help text (calculated) default_tag : str text to replace with each option's default value, "%default" by default. Set to false value to disable default value expansion. option_strings : { Option : str } maps Option instances to the snippet of help text explaining the syntax of that option, e.g. "-h, --help" or "-fFILE, --file=FILE" _short_opt_fmt : str format string controlling how short options with values are printed in help text. Must be either "%s%s" ("-fFILE") or "%s %s" ("-f FILE"), because those are the two syntaxes that Optik supports. _long_opt_fmt : str similar but for long options; must be either "%s %s" ("--file FILE") or "%s=%s" ("--file=FILE"). """ NO_DEFAULT_VALUE = "none" def __init__(self, indent_increment, max_help_position, width, short_first): self.parser = None self.indent_increment = indent_increment self.help_position = self.max_help_position = max_help_position if width is None: try: width = int(os.environ['COLUMNS']) except (KeyError, ValueError): width = 80 width = width - 2 self.width = width self.current_indent = 0 self.level = 0 self.help_width = None # computed later self.short_first = short_first self.default_tag = "%default" self.option_strings = {} self._short_opt_fmt = "%s %s" self._long_opt_fmt = "%s=%s" def set_parser(self, parser): self.parser = parser def set_short_opt_delimiter(self, delim): if delim not in ("", " "): raise ValueError( "invalid metavar delimiter for short options: %r" % delim) self._short_opt_fmt = "%s" + delim + "%s" def set_long_opt_delimiter(self, delim): if delim not in ("=", " "): raise ValueError( "invalid metavar delimiter for long options: %r" % delim) self._long_opt_fmt = "%s" + delim + "%s" def indent(self): self.current_indent = self.current_indent + self.indent_increment self.level = self.level + 1 def dedent(self): self.current_indent = self.current_indent - self.indent_increment assert self.current_indent >= 0, "Indent decreased below 0." self.level = self.level - 1 def format_usage(self, usage): raise NotImplementedError, "subclasses must implement" def format_heading(self, heading): raise NotImplementedError, "subclasses must implement" def format_description(self, description): if not description: return "" desc_width = self.width - self.current_indent indent = " "*self.current_indent return textwrap.fill(description, desc_width, initial_indent=indent, subsequent_indent=indent) + "\n" def expand_default(self, option): if self.parser is None or not self.default_tag: return option.help default_value = self.parser.defaults.get(option.dest) if default_value is NO_DEFAULT or default_value is None: default_value = self.NO_DEFAULT_VALUE return string.replace(option.help, self.default_tag, str(default_value)) def format_option(self, option): # The help for each option consists of two parts: # * the opt strings and metavars # eg. ("-x", or "-fFILENAME, --file=FILENAME") # * the user-supplied help string # eg. ("turn on expert mode", "read data from FILENAME") # # If possible, we write both of these on the same line: # -x turn on expert mode # # But if the opt string list is too long, we put the help # string on a second line, indented to the same column it would # start in if it fit on the first line. # -fFILENAME, --file=FILENAME # read data from FILENAME result = [] opts = self.option_strings[option] opt_width = self.help_position - self.current_indent - 2 if len(opts) > opt_width: opts = "%*s%s\n" % (self.current_indent, "", opts) indent_first = self.help_position else: # start help on same line as opts opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) indent_first = 0 result.append(opts) if option.help: help_text = self.expand_default(option) help_lines = textwrap.wrap(help_text, self.help_width) result.append("%*s%s\n" % (indent_first, "", help_lines[0])) for line in help_lines[1:]: result.append("%*s%s\n" % (self.help_position, "", line)) elif opts[-1] != "\n": result.append("\n") return string.join(result, "") def store_option_strings(self, parser): self.indent() max_len = 0 for opt in parser.option_list: strings = self.format_option_strings(opt) self.option_strings[opt] = strings max_len = max(max_len, len(strings) + self.current_indent) self.indent() for group in parser.option_groups: for opt in group.option_list: strings = self.format_option_strings(opt) self.option_strings[opt] = strings max_len = max(max_len, len(strings) + self.current_indent) self.dedent() self.dedent() self.help_position = min(max_len + 2, self.max_help_position) self.help_width = self.width - self.help_position def format_option_strings(self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): metavar = option.metavar or string.upper(option.dest) short_opts = [] for sopt in option._short_opts: short_opts.append(self._short_opt_fmt % (sopt, metavar)) long_opts = [] for lopt in option._long_opts: long_opts.append(self._long_opt_fmt % (lopt, metavar)) else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = short_opts + long_opts else: opts = long_opts + short_opts return string.join(opts, ", ") class IndentedHelpFormatter (HelpFormatter): """Format help with indented section bodies. """ def __init__(self, indent_increment=2, max_help_position=24, width=None, short_first=1): HelpFormatter.__init__( self, indent_increment, max_help_position, width, short_first) def format_usage(self, usage): return _("usage: %s\n") % usage def format_heading(self, heading): return "%*s%s:\n" % (self.current_indent, "", heading) class TitledHelpFormatter (HelpFormatter): """Format help with underlined section headers. """ def __init__(self, indent_increment=0, max_help_position=24, width=None, short_first=0): HelpFormatter.__init__ ( self, indent_increment, max_help_position, width, short_first) def format_usage(self, usage): return "%s %s\n" % (self.format_heading(_("Usage")), usage) def format_heading(self, heading): return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
Python
"""optik A powerful, extensible, and easy-to-use command-line parser for Python. By Greg Ward <gward@python.net> See http://optik.sourceforge.net/ """ # Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved. # See the README.txt distributed with Optik for licensing terms. __revision__ = "$Id: __init__.py 472 2004-12-07 01:45:55Z gward $" __version__ = "1.5" # Re-import these for convenience from pyi_optik.option import Option from pyi_optik.option_parser import * from pyi_optik.help import * from pyi_optik.errors import * from pyi_optik import option, option_parser, help, errors __all__ = (option.__all__ + option_parser.__all__ + help.__all__ + errors.__all__) # Some day, there might be many Option classes. As of Optik 1.3, the # preferred way to instantiate Options is indirectly, via make_option(), # which will become a factory function when there are many Option # classes. make_option = Option
Python
#! /usr/bin/env python # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA from win32com.shell import shell import win32api import pythoncom import os import sys def CreateShortCut(Path, Target,Arguments = "", StartIn = "", Icon = ("",0), Description = ""): # Get the shell interface. sh = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, \ pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) # Get an IPersist interface persist = sh.QueryInterface(pythoncom.IID_IPersistFile) # Set the data sh.SetPath(Target) sh.SetDescription(Description) sh.SetArguments(Arguments) sh.SetWorkingDirectory(StartIn) sh.SetIconLocation(Icon[0],Icon[1]) # sh.SetShowCmd( win32con.SW_SHOWMINIMIZED) # Save the link itself. persist.Save(Path, 1) print "Saved to", Path if __name__ == "__main__": try: TempDir = os.environ["TEMP"] WinRoot = os.environ["windir"] Path = TempDir Target = os.path.normpath(sys.executable) Arguments = "" StartIn = TempDir Icon = ("", 0) Description = "py made shortcut" CreateShortCut(Path,Target,Arguments,StartIn,Icon,Description) except Exception, e: print "Failed!", e import traceback traceback.print_exc() raw_input("Press any key to continue...")
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA #import pythoncom pycomCLSCTX_INPROC = 3 pycomCLSCTX_LOCAL_SERVER = 4 import os d = {} class NextID: _reg_clsid_ = '{25E06E61-2D18-11D5-945F-00609736B700}' _reg_desc_ = 'Text COM server' _reg_progid_ = 'MEInc.NextID' _reg_clsctx_ = pycomCLSCTX_INPROC | pycomCLSCTX_LOCAL_SERVER _public_methods_ = [ 'getNextID' ] def __init__(self): import win32api win32api.MessageBox(0, "NextID.__init__ started", "NextID.py") global d if sys.frozen: for entry in sys.path: if entry.find('?') > -1: here = os.path.dirname(entry.split('?')[0]) break else: here = os.getcwd() else: here = os.path.dirname(__file__) self.fnm = os.path.join(here, 'id.cfg') try: d = eval(open(self.fnm, 'r').read()+'\n') except: d = { 'systemID': 0xaaaab, 'highID': 0 } win32api.MessageBox(0, "NextID.__init__ complete", "NextID.py") def getNextID(self): global d d['highID'] = d['highID'] + 1 open(self.fnm, 'w').write(repr(d)) return '%(systemID)-0.5x%(highID)-0.7x' % d def RegisterNextID(): from win32com.server import register register.UseCommandLine(NextID) def UnRegisterNextID(): from win32com.server import register register.UnregisterServer(NextID._reg_clsid_, NextID._reg_progid_) if __name__ == '__main__': import sys if "/unreg" in sys.argv: UnRegisterNextID() elif "/register" in sys.argv: RegisterNextID() else: print "running as server" import win32com.server.localserver win32com.server.localserver.main() raw_input("Press any key...")
Python
# Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # Test MSOffice # # Main purpose of test is to ensure that Dynamic COM objects # work as expected. # Assumes Word and Excel installed on your machine. import win32com, sys, string, win32api, traceback import win32com.client.dynamic from win32com.test.util import CheckClean import pythoncom from win32com.client import gencache from pywintypes import Unicode error = "MSOffice test error" # Test a few of the MSOffice components. def TestWord(): # Try and load the object exposed by Word 8 # Office 97 - _totally_ different object model! try: # NOTE - using "client.Dispatch" would return an msword8.py instance! print "Starting Word 8 for dynamic test" word = win32com.client.dynamic.Dispatch("Word.Application") TestWord8(word) word = None # Now we will test Dispatch without the new "lazy" capabilities print "Starting Word 8 for non-lazy dynamic test" dispatch = win32com.client.dynamic._GetGoodDispatch("Word.Application") typeinfo = dispatch.GetTypeInfo() attr = typeinfo.GetTypeAttr() olerepr = win32com.client.build.DispatchItem(typeinfo, attr, None, 0) word = win32com.client.dynamic.CDispatch(dispatch, olerepr) dispatch = typeinfo = attr = olerepr = None TestWord8(word) except pythoncom.com_error: print "Starting Word 7 for dynamic test" word = win32com.client.Dispatch("Word.Basic") TestWord7(word) try: print "Starting MSWord for generated test" # Typelib, lcid, major and minor for the typelib try: o = gencache.EnsureModule("{00020905-0000-0000-C000-000000000046}", 1033, 8, 0, bForDemand=1) except TypeError: o = gencache.EnsureModule("{00020905-0000-0000-C000-000000000046}", 1033, 8, 0) if o is None : raise ImportError, "Can not load the Word8 typelibrary." word = win32com.client.Dispatch("Word.Application.8") TestWord8(word) except ImportError, details: print "Can not test MSWord8 -", details def TestWord7(word): word.FileNew() # If not shown, show the app. if not word.AppShow(): word._proc_("AppShow") for i in xrange(12): word.FormatFont(Color=i+1, Points=i+12) word.Insert("Hello from Python %d\n" % i) word.FileClose(2) def TestWord8(word): word.Visible = 1 doc = word.Documents.Add() wrange = doc.Range() for i in range(10): wrange.InsertAfter("Hello from Python %d\n" % i) paras = doc.Paragraphs for i in range(len(paras)): paras[i]().Font.ColorIndex = i+1 paras[i]().Font.Size = 12 + (4 * i) # XXX - note that # for para in paras: # para().Font... # doesnt seem to work - no error, just doesnt work # Should check if it works for VB! doc.Close(SaveChanges = 0) word.Quit() win32api.Sleep(1000) # Wait for word to close, else we # may get OA error. def TestWord8OldStyle(): try: import win32com.test.Generated4Test.msword8 except ImportError: print "Can not do old style test" def TextExcel(xl): xl.Visible = 0 if xl.Visible: raise error, "Visible property is true." xl.Visible = 1 if not xl.Visible: raise error, "Visible property not true." if int(xl.Version[0])>=8: xl.Workbooks.Add() else: xl.Workbooks().Add() xl.Range("A1:C1").Value = (1,2,3) xl.Range("A2:C2").Value = ('x','y','z') xl.Range("A3:C3").Value = ('3','2','1') for i in xrange(20): xl.Cells(i+1,i+1).Value = "Hi %d" % i if xl.Range("A1").Value <> "Hi 0": raise error, "Single cell range failed" if xl.Range("A1:B1").Value <> ((Unicode("Hi 0"),2),): raise error, "flat-horizontal cell range failed" if xl.Range("A1:A2").Value <> ((Unicode("Hi 0"),),(Unicode("x"),)): raise error, "flat-vertical cell range failed" if xl.Range("A1:C3").Value <> ((Unicode("Hi 0"),2,3),(Unicode("x"),Unicode("Hi 1"),Unicode("z")),(3,2,Unicode("Hi 2"))): raise error, "square cell range failed" xl.Range("A1:C3").Value =((3,2,1),("x","y","z"),(1,2,3)) if xl.Range("A1:C3").Value <> ((3,2,1),(Unicode("x"),Unicode("y"),Unicode("z")),(1,2,3)): raise error, "Range was not what I set it to!" # test dates out with Excel xl.Cells(5,1).Value = "Excel time" xl.Cells(5,2).Formula = "=Now()" import time xl.Cells(6,1).Value = "Python time" xl.Cells(6,2).Value = pythoncom.MakeTime(time.time()) xl.Cells(6,2).NumberFormat = "d/mm/yy h:mm" xl.Columns("A:B").EntireColumn.AutoFit() xl.Workbooks(1).Close(0) xl.Quit() def TestAll(): try: TestWord() print "Starting Excel for Dynamic test..." xl = win32com.client.dynamic.Dispatch("Excel.Application") TextExcel(xl) try: print "Starting Excel 8 for generated excel8.py test..." try: mod = gencache.EnsureModule("{00020813-0000-0000-C000-000000000046}", 0, 1, 2, bForDemand=1) except TypeError: mod = gencache.EnsureModule("{00020813-0000-0000-C000-000000000046}", 0, 1, 2) xl = win32com.client.Dispatch("Excel.Application") TextExcel(xl) except ImportError: print "Could not import the generated Excel 97 wrapper" try: import xl5en32 mod = gencache.EnsureModule("{00020813-0000-0000-C000-000000000046}", 9, 1, 0) xl = win32com.client.Dispatch("Excel.Application.5") print "Starting Excel 95 for makepy test..." TextExcel(xl) except ImportError: print "Could not import the generated Excel 95 wrapper" except KeyboardInterrupt: print "*** Interrupted MSOffice test ***" except: traceback.print_exc() if __name__=='__main__': TestAll() CheckClean() pythoncom.CoUninitialize()
Python
# for older Pythons, we need to set up for the import of cPickle import string import copy_reg import win32com.client.gencache x = win32com.client.gencache.EnsureDispatch('ADOR.Recordset') print x x = None #raw_input("Press any key to continue...")
Python
# Animated Towers of Hanoi using Tk with optional bitmap file in # background. # # Usage: tkhanoi [n [bitmapfile]] # # n is the number of pieces to animate; default is 4, maximum 15. # # The bitmap file can be any X11 bitmap file (look in # /usr/include/X11/bitmaps for samples); it is displayed as the # background of the animation. Default is no bitmap. # This uses Steen Lumholt's Tk interface from Tkinter import * # Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c # as temporary. For each move, call report() def hanoi(n, a, b, c, report): if n <= 0: return hanoi(n-1, a, c, b, report) report(n, a, b) hanoi(n-1, c, b, a, report) # The graphical interface class Tkhanoi: # Create our objects def __init__(self, n, bitmap = None): self.n = n self.tk = tk = Tk() self.canvas = c = Canvas(tk) c.pack() width, height = tk.getint(c['width']), tk.getint(c['height']) # Add background bitmap if bitmap: self.bitmap = c.create_bitmap(width/2, height/2, bitmap=bitmap, foreground='blue') # Generate pegs pegwidth = 10 pegheight = height/2 pegdist = width/3 x1, y1 = (pegdist-pegwidth)/2, height*1/3 x2, y2 = x1+pegwidth, y1+pegheight self.pegs = [] p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) x1, x2 = x1+pegdist, x2+pegdist p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) x1, x2 = x1+pegdist, x2+pegdist p = c.create_rectangle(x1, y1, x2, y2, fill='black') self.pegs.append(p) self.tk.update() # Generate pieces pieceheight = pegheight/16 maxpiecewidth = pegdist*2/3 minpiecewidth = 2*pegwidth self.pegstate = [[], [], []] self.pieces = {} x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2 x2, y2 = x1+maxpiecewidth, y1+pieceheight dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1)) for i in range(n, 0, -1): p = c.create_rectangle(x1, y1, x2, y2, fill='red') self.pieces[i] = p self.pegstate[0].append(i) x1, x2 = x1 + dx, x2-dx y1, y2 = y1 - pieceheight-2, y2-pieceheight-2 self.tk.update() self.tk.after(25) # Run -- never returns def run(self): while 1: hanoi(self.n, 0, 1, 2, self.report) hanoi(self.n, 1, 2, 0, self.report) hanoi(self.n, 2, 0, 1, self.report) hanoi(self.n, 0, 2, 1, self.report) hanoi(self.n, 2, 1, 0, self.report) hanoi(self.n, 1, 0, 2, self.report) # Reporting callback for the actual hanoi function def report(self, i, a, b): if self.pegstate[a][-1] != i: raise RuntimeError # Assertion del self.pegstate[a][-1] p = self.pieces[i] c = self.canvas # Lift the piece above peg a ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a]) while 1: x1, y1, x2, y2 = c.bbox(p) if y2 < ay1: break c.move(p, 0, -1) self.tk.update() # Move it towards peg b bx1, by1, bx2, by2 = c.bbox(self.pegs[b]) newcenter = (bx1+bx2)/2 while 1: x1, y1, x2, y2 = c.bbox(p) center = (x1+x2)/2 if center == newcenter: break if center > newcenter: c.move(p, -1, 0) else: c.move(p, 1, 0) self.tk.update() # Move it down on top of the previous piece pieceheight = y2-y1 newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2 while 1: x1, y1, x2, y2 = c.bbox(p) if y2 >= newbottom: break c.move(p, 0, 1) self.tk.update() # Update peg state self.pegstate[b].append(i) # Main program def main(): import sys, string # First argument is number of pegs, default 4 if sys.argv[1:]: n = string.atoi(sys.argv[1]) else: n = 4 # Second argument is bitmap file, default none if sys.argv[2:]: bitmap = sys.argv[2] # Reverse meaning of leading '@' compared to Tk if bitmap[0] == '@': bitmap = bitmap[1:] else: bitmap = '@' + bitmap else: bitmap = None # Create the graphical objects... h = Tkhanoi(n, bitmap) # ...and run! h.run() # Call main when run as script if __name__ == '__main__': main()
Python
#!/usr/bin/env python # Copyright (C) 2005, Giovanni Bajo # Based on previous work under copyright (c) 1999, 2002 McMillan Enterprises, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import sys, string, os if sys.platform[:3] == 'win': stripopts = ('',) consoleopts = ('', '--noconsole') else: stripopts = ('', '--strip') consoleopts = ('',) if string.find(sys.executable, ' ') > -1: exe = '"%s"' % sys.executable else: exe = sys.executable if sys.platform[:3] == 'win': spec = "%s ../../Makespec.py --tk %%s %%s %%s %%s %%s --out t%%d hanoi.py" % exe bld = "%s ../../Build.py t%%d/hanoi.spec" % exe else: spec = "%s ../../Makespec.py --tk %%s %%s %%s %%s %%s --out /u/temp/t%%d hanoi.py" % exe bld = "%s ../../Build.py /u/temp/t%%d/hanoi.spec" % exe i = 0 for bldconfig in ('--onedir', '--onefile'): for console in consoleopts: for dbg in ('--debug', ''): for stripopt in stripopts: for upxopt in ('', '--upx'): cmd = spec % (bldconfig, console, dbg, stripopt, upxopt, i) os.system(cmd) os.system(bld % i) if sys.platform[:5] == 'linux': if bldconfig == '--onedir': os.system("ln -s /u/temp/t%d/disthanoi/hanoi hanoi%d" % (i,i)) else: os.system("ln -s /u/temp/t%d/hanoi hanoi%d" % (i,i)) i += 1
Python
# -*- coding: Latin-1 -*- """pefile, Portable Executable reader module All the PE file basic structures are available with their default names as attributes of the instance returned. Processed elements such as the import table are made available with lowercase names, to differentiate them from the upper case basic structure names. pefile has been tested against the limits of valid PE headers, that is, malware. Lots of packed malware attempt to abuse the format way beyond its standard use. To the best of my knowledge most of the abuses are handled gracefully. Copyright (c) 2005, 2006, 2007, 2008, 2009 Ero Carrera <ero@dkbza.org> All rights reserved. For detailed copyright information see the file COPYING in the root of the distribution archive. """ __revision__ = "$LastChangedRevision: 63 $" __author__ = 'Ero Carrera' __version__ = '1.2.10-%d' % int( __revision__[21:-2] ) __contact__ = 'ero@dkbza.org' import os import struct import time import math import re import exceptions import string import array sha1, sha256, sha512, md5 = None, None, None, None try: import hashlib sha1 = hashlib.sha1 sha256 = hashlib.sha256 sha512 = hashlib.sha512 md5 = hashlib.md5 except ImportError: try: import sha sha1 = sha.new except ImportError: pass try: import md5 md5 = md5.new except ImportError: pass try: enumerate except NameError: def enumerate(iter): L = list(iter) return zip(range(0, len(L)), L) fast_load = False IMAGE_DOS_SIGNATURE = 0x5A4D IMAGE_OS2_SIGNATURE = 0x454E IMAGE_OS2_SIGNATURE_LE = 0x454C IMAGE_VXD_SIGNATURE = 0x454C IMAGE_NT_SIGNATURE = 0x00004550 IMAGE_NUMBEROF_DIRECTORY_ENTRIES= 16 IMAGE_ORDINAL_FLAG = 0x80000000L IMAGE_ORDINAL_FLAG64 = 0x8000000000000000L OPTIONAL_HEADER_MAGIC_PE = 0x10b OPTIONAL_HEADER_MAGIC_PE_PLUS = 0x20b directory_entry_types = [ ('IMAGE_DIRECTORY_ENTRY_EXPORT', 0), ('IMAGE_DIRECTORY_ENTRY_IMPORT', 1), ('IMAGE_DIRECTORY_ENTRY_RESOURCE', 2), ('IMAGE_DIRECTORY_ENTRY_EXCEPTION', 3), ('IMAGE_DIRECTORY_ENTRY_SECURITY', 4), ('IMAGE_DIRECTORY_ENTRY_BASERELOC', 5), ('IMAGE_DIRECTORY_ENTRY_DEBUG', 6), ('IMAGE_DIRECTORY_ENTRY_COPYRIGHT', 7), ('IMAGE_DIRECTORY_ENTRY_GLOBALPTR', 8), ('IMAGE_DIRECTORY_ENTRY_TLS', 9), ('IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG', 10), ('IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT', 11), ('IMAGE_DIRECTORY_ENTRY_IAT', 12), ('IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT', 13), ('IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR',14), ('IMAGE_DIRECTORY_ENTRY_RESERVED', 15) ] DIRECTORY_ENTRY = dict([(e[1], e[0]) for e in directory_entry_types]+directory_entry_types) image_characteristics = [ ('IMAGE_FILE_RELOCS_STRIPPED', 0x0001), ('IMAGE_FILE_EXECUTABLE_IMAGE', 0x0002), ('IMAGE_FILE_LINE_NUMS_STRIPPED', 0x0004), ('IMAGE_FILE_LOCAL_SYMS_STRIPPED', 0x0008), ('IMAGE_FILE_AGGRESIVE_WS_TRIM', 0x0010), ('IMAGE_FILE_LARGE_ADDRESS_AWARE', 0x0020), ('IMAGE_FILE_16BIT_MACHINE', 0x0040), ('IMAGE_FILE_BYTES_REVERSED_LO', 0x0080), ('IMAGE_FILE_32BIT_MACHINE', 0x0100), ('IMAGE_FILE_DEBUG_STRIPPED', 0x0200), ('IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP', 0x0400), ('IMAGE_FILE_NET_RUN_FROM_SWAP', 0x0800), ('IMAGE_FILE_SYSTEM', 0x1000), ('IMAGE_FILE_DLL', 0x2000), ('IMAGE_FILE_UP_SYSTEM_ONLY', 0x4000), ('IMAGE_FILE_BYTES_REVERSED_HI', 0x8000) ] IMAGE_CHARACTERISTICS = dict([(e[1], e[0]) for e in image_characteristics]+image_characteristics) section_characteristics = [ ('IMAGE_SCN_CNT_CODE', 0x00000020), ('IMAGE_SCN_CNT_INITIALIZED_DATA', 0x00000040), ('IMAGE_SCN_CNT_UNINITIALIZED_DATA', 0x00000080), ('IMAGE_SCN_LNK_OTHER', 0x00000100), ('IMAGE_SCN_LNK_INFO', 0x00000200), ('IMAGE_SCN_LNK_REMOVE', 0x00000800), ('IMAGE_SCN_LNK_COMDAT', 0x00001000), ('IMAGE_SCN_MEM_FARDATA', 0x00008000), ('IMAGE_SCN_MEM_PURGEABLE', 0x00020000), ('IMAGE_SCN_MEM_16BIT', 0x00020000), ('IMAGE_SCN_MEM_LOCKED', 0x00040000), ('IMAGE_SCN_MEM_PRELOAD', 0x00080000), ('IMAGE_SCN_ALIGN_1BYTES', 0x00100000), ('IMAGE_SCN_ALIGN_2BYTES', 0x00200000), ('IMAGE_SCN_ALIGN_4BYTES', 0x00300000), ('IMAGE_SCN_ALIGN_8BYTES', 0x00400000), ('IMAGE_SCN_ALIGN_16BYTES', 0x00500000), ('IMAGE_SCN_ALIGN_32BYTES', 0x00600000), ('IMAGE_SCN_ALIGN_64BYTES', 0x00700000), ('IMAGE_SCN_ALIGN_128BYTES', 0x00800000), ('IMAGE_SCN_ALIGN_256BYTES', 0x00900000), ('IMAGE_SCN_ALIGN_512BYTES', 0x00A00000), ('IMAGE_SCN_ALIGN_1024BYTES', 0x00B00000), ('IMAGE_SCN_ALIGN_2048BYTES', 0x00C00000), ('IMAGE_SCN_ALIGN_4096BYTES', 0x00D00000), ('IMAGE_SCN_ALIGN_8192BYTES', 0x00E00000), ('IMAGE_SCN_ALIGN_MASK', 0x00F00000), ('IMAGE_SCN_LNK_NRELOC_OVFL', 0x01000000), ('IMAGE_SCN_MEM_DISCARDABLE', 0x02000000), ('IMAGE_SCN_MEM_NOT_CACHED', 0x04000000), ('IMAGE_SCN_MEM_NOT_PAGED', 0x08000000), ('IMAGE_SCN_MEM_SHARED', 0x10000000), ('IMAGE_SCN_MEM_EXECUTE', 0x20000000), ('IMAGE_SCN_MEM_READ', 0x40000000), ('IMAGE_SCN_MEM_WRITE', 0x80000000L) ] SECTION_CHARACTERISTICS = dict([(e[1], e[0]) for e in section_characteristics]+section_characteristics) debug_types = [ ('IMAGE_DEBUG_TYPE_UNKNOWN', 0), ('IMAGE_DEBUG_TYPE_COFF', 1), ('IMAGE_DEBUG_TYPE_CODEVIEW', 2), ('IMAGE_DEBUG_TYPE_FPO', 3), ('IMAGE_DEBUG_TYPE_MISC', 4), ('IMAGE_DEBUG_TYPE_EXCEPTION', 5), ('IMAGE_DEBUG_TYPE_FIXUP', 6), ('IMAGE_DEBUG_TYPE_OMAP_TO_SRC', 7), ('IMAGE_DEBUG_TYPE_OMAP_FROM_SRC', 8), ('IMAGE_DEBUG_TYPE_BORLAND', 9), ('IMAGE_DEBUG_TYPE_RESERVED10', 10) ] DEBUG_TYPE = dict([(e[1], e[0]) for e in debug_types]+debug_types) subsystem_types = [ ('IMAGE_SUBSYSTEM_UNKNOWN', 0), ('IMAGE_SUBSYSTEM_NATIVE', 1), ('IMAGE_SUBSYSTEM_WINDOWS_GUI', 2), ('IMAGE_SUBSYSTEM_WINDOWS_CUI', 3), ('IMAGE_SUBSYSTEM_OS2_CUI', 5), ('IMAGE_SUBSYSTEM_POSIX_CUI', 7), ('IMAGE_SUBSYSTEM_WINDOWS_CE_GUI', 9), ('IMAGE_SUBSYSTEM_EFI_APPLICATION', 10), ('IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER', 11), ('IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER', 12), ('IMAGE_SUBSYSTEM_EFI_ROM', 13), ('IMAGE_SUBSYSTEM_XBOX', 14)] SUBSYSTEM_TYPE = dict([(e[1], e[0]) for e in subsystem_types]+subsystem_types) machine_types = [ ('IMAGE_FILE_MACHINE_UNKNOWN', 0), ('IMAGE_FILE_MACHINE_AM33', 0x1d3), ('IMAGE_FILE_MACHINE_AMD64', 0x8664), ('IMAGE_FILE_MACHINE_ARM', 0x1c0), ('IMAGE_FILE_MACHINE_EBC', 0xebc), ('IMAGE_FILE_MACHINE_I386', 0x14c), ('IMAGE_FILE_MACHINE_IA64', 0x200), ('IMAGE_FILE_MACHINE_MR32', 0x9041), ('IMAGE_FILE_MACHINE_MIPS16', 0x266), ('IMAGE_FILE_MACHINE_MIPSFPU', 0x366), ('IMAGE_FILE_MACHINE_MIPSFPU16',0x466), ('IMAGE_FILE_MACHINE_POWERPC', 0x1f0), ('IMAGE_FILE_MACHINE_POWERPCFP',0x1f1), ('IMAGE_FILE_MACHINE_R4000', 0x166), ('IMAGE_FILE_MACHINE_SH3', 0x1a2), ('IMAGE_FILE_MACHINE_SH3DSP', 0x1a3), ('IMAGE_FILE_MACHINE_SH4', 0x1a6), ('IMAGE_FILE_MACHINE_SH5', 0x1a8), ('IMAGE_FILE_MACHINE_THUMB', 0x1c2), ('IMAGE_FILE_MACHINE_WCEMIPSV2',0x169), ] MACHINE_TYPE = dict([(e[1], e[0]) for e in machine_types]+machine_types) relocation_types = [ ('IMAGE_REL_BASED_ABSOLUTE', 0), ('IMAGE_REL_BASED_HIGH', 1), ('IMAGE_REL_BASED_LOW', 2), ('IMAGE_REL_BASED_HIGHLOW', 3), ('IMAGE_REL_BASED_HIGHADJ', 4), ('IMAGE_REL_BASED_MIPS_JMPADDR', 5), ('IMAGE_REL_BASED_SECTION', 6), ('IMAGE_REL_BASED_REL', 7), ('IMAGE_REL_BASED_MIPS_JMPADDR16', 9), ('IMAGE_REL_BASED_IA64_IMM64', 9), ('IMAGE_REL_BASED_DIR64', 10), ('IMAGE_REL_BASED_HIGH3ADJ', 11) ] RELOCATION_TYPE = dict([(e[1], e[0]) for e in relocation_types]+relocation_types) dll_characteristics = [ ('IMAGE_DLL_CHARACTERISTICS_RESERVED_0x0001', 0x0001), ('IMAGE_DLL_CHARACTERISTICS_RESERVED_0x0002', 0x0002), ('IMAGE_DLL_CHARACTERISTICS_RESERVED_0x0004', 0x0004), ('IMAGE_DLL_CHARACTERISTICS_RESERVED_0x0008', 0x0008), ('IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE', 0x0040), ('IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY', 0x0080), ('IMAGE_DLL_CHARACTERISTICS_NX_COMPAT', 0x0100), ('IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION', 0x0200), ('IMAGE_DLL_CHARACTERISTICS_NO_SEH', 0x0400), ('IMAGE_DLL_CHARACTERISTICS_NO_BIND', 0x0800), ('IMAGE_DLL_CHARACTERISTICS_RESERVED_0x1000', 0x1000), ('IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER', 0x2000), ('IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE', 0x8000) ] DLL_CHARACTERISTICS = dict([(e[1], e[0]) for e in dll_characteristics]+dll_characteristics) # Resource types resource_type = [ ('RT_CURSOR', 1), ('RT_BITMAP', 2), ('RT_ICON', 3), ('RT_MENU', 4), ('RT_DIALOG', 5), ('RT_STRING', 6), ('RT_FONTDIR', 7), ('RT_FONT', 8), ('RT_ACCELERATOR', 9), ('RT_RCDATA', 10), ('RT_MESSAGETABLE', 11), ('RT_GROUP_CURSOR', 12), ('RT_GROUP_ICON', 14), ('RT_VERSION', 16), ('RT_DLGINCLUDE', 17), ('RT_PLUGPLAY', 19), ('RT_VXD', 20), ('RT_ANICURSOR', 21), ('RT_ANIICON', 22), ('RT_HTML', 23), ('RT_MANIFEST', 24) ] RESOURCE_TYPE = dict([(e[1], e[0]) for e in resource_type]+resource_type) # Language definitions lang = [ ('LANG_NEUTRAL', 0x00), ('LANG_INVARIANT', 0x7f), ('LANG_AFRIKAANS', 0x36), ('LANG_ALBANIAN', 0x1c), ('LANG_ARABIC', 0x01), ('LANG_ARMENIAN', 0x2b), ('LANG_ASSAMESE', 0x4d), ('LANG_AZERI', 0x2c), ('LANG_BASQUE', 0x2d), ('LANG_BELARUSIAN', 0x23), ('LANG_BENGALI', 0x45), ('LANG_BULGARIAN', 0x02), ('LANG_CATALAN', 0x03), ('LANG_CHINESE', 0x04), ('LANG_CROATIAN', 0x1a), ('LANG_CZECH', 0x05), ('LANG_DANISH', 0x06), ('LANG_DIVEHI', 0x65), ('LANG_DUTCH', 0x13), ('LANG_ENGLISH', 0x09), ('LANG_ESTONIAN', 0x25), ('LANG_FAEROESE', 0x38), ('LANG_FARSI', 0x29), ('LANG_FINNISH', 0x0b), ('LANG_FRENCH', 0x0c), ('LANG_GALICIAN', 0x56), ('LANG_GEORGIAN', 0x37), ('LANG_GERMAN', 0x07), ('LANG_GREEK', 0x08), ('LANG_GUJARATI', 0x47), ('LANG_HEBREW', 0x0d), ('LANG_HINDI', 0x39), ('LANG_HUNGARIAN', 0x0e), ('LANG_ICELANDIC', 0x0f), ('LANG_INDONESIAN', 0x21), ('LANG_ITALIAN', 0x10), ('LANG_JAPANESE', 0x11), ('LANG_KANNADA', 0x4b), ('LANG_KASHMIRI', 0x60), ('LANG_KAZAK', 0x3f), ('LANG_KONKANI', 0x57), ('LANG_KOREAN', 0x12), ('LANG_KYRGYZ', 0x40), ('LANG_LATVIAN', 0x26), ('LANG_LITHUANIAN', 0x27), ('LANG_MACEDONIAN', 0x2f), ('LANG_MALAY', 0x3e), ('LANG_MALAYALAM', 0x4c), ('LANG_MANIPURI', 0x58), ('LANG_MARATHI', 0x4e), ('LANG_MONGOLIAN', 0x50), ('LANG_NEPALI', 0x61), ('LANG_NORWEGIAN', 0x14), ('LANG_ORIYA', 0x48), ('LANG_POLISH', 0x15), ('LANG_PORTUGUESE', 0x16), ('LANG_PUNJABI', 0x46), ('LANG_ROMANIAN', 0x18), ('LANG_RUSSIAN', 0x19), ('LANG_SANSKRIT', 0x4f), ('LANG_SERBIAN', 0x1a), ('LANG_SINDHI', 0x59), ('LANG_SLOVAK', 0x1b), ('LANG_SLOVENIAN', 0x24), ('LANG_SPANISH', 0x0a), ('LANG_SWAHILI', 0x41), ('LANG_SWEDISH', 0x1d), ('LANG_SYRIAC', 0x5a), ('LANG_TAMIL', 0x49), ('LANG_TATAR', 0x44), ('LANG_TELUGU', 0x4a), ('LANG_THAI', 0x1e), ('LANG_TURKISH', 0x1f), ('LANG_UKRAINIAN', 0x22), ('LANG_URDU', 0x20), ('LANG_UZBEK', 0x43), ('LANG_VIETNAMESE', 0x2a), ('LANG_GAELIC', 0x3c), ('LANG_MALTESE', 0x3a), ('LANG_MAORI', 0x28), ('LANG_RHAETO_ROMANCE',0x17), ('LANG_SAAMI', 0x3b), ('LANG_SORBIAN', 0x2e), ('LANG_SUTU', 0x30), ('LANG_TSONGA', 0x31), ('LANG_TSWANA', 0x32), ('LANG_VENDA', 0x33), ('LANG_XHOSA', 0x34), ('LANG_ZULU', 0x35), ('LANG_ESPERANTO', 0x8f), ('LANG_WALON', 0x90), ('LANG_CORNISH', 0x91), ('LANG_WELSH', 0x92), ('LANG_BRETON', 0x93) ] LANG = dict(lang+[(e[1], e[0]) for e in lang]) # Sublanguage definitions sublang = [ ('SUBLANG_NEUTRAL', 0x00), ('SUBLANG_DEFAULT', 0x01), ('SUBLANG_SYS_DEFAULT', 0x02), ('SUBLANG_ARABIC_SAUDI_ARABIA', 0x01), ('SUBLANG_ARABIC_IRAQ', 0x02), ('SUBLANG_ARABIC_EGYPT', 0x03), ('SUBLANG_ARABIC_LIBYA', 0x04), ('SUBLANG_ARABIC_ALGERIA', 0x05), ('SUBLANG_ARABIC_MOROCCO', 0x06), ('SUBLANG_ARABIC_TUNISIA', 0x07), ('SUBLANG_ARABIC_OMAN', 0x08), ('SUBLANG_ARABIC_YEMEN', 0x09), ('SUBLANG_ARABIC_SYRIA', 0x0a), ('SUBLANG_ARABIC_JORDAN', 0x0b), ('SUBLANG_ARABIC_LEBANON', 0x0c), ('SUBLANG_ARABIC_KUWAIT', 0x0d), ('SUBLANG_ARABIC_UAE', 0x0e), ('SUBLANG_ARABIC_BAHRAIN', 0x0f), ('SUBLANG_ARABIC_QATAR', 0x10), ('SUBLANG_AZERI_LATIN', 0x01), ('SUBLANG_AZERI_CYRILLIC', 0x02), ('SUBLANG_CHINESE_TRADITIONAL', 0x01), ('SUBLANG_CHINESE_SIMPLIFIED', 0x02), ('SUBLANG_CHINESE_HONGKONG', 0x03), ('SUBLANG_CHINESE_SINGAPORE', 0x04), ('SUBLANG_CHINESE_MACAU', 0x05), ('SUBLANG_DUTCH', 0x01), ('SUBLANG_DUTCH_BELGIAN', 0x02), ('SUBLANG_ENGLISH_US', 0x01), ('SUBLANG_ENGLISH_UK', 0x02), ('SUBLANG_ENGLISH_AUS', 0x03), ('SUBLANG_ENGLISH_CAN', 0x04), ('SUBLANG_ENGLISH_NZ', 0x05), ('SUBLANG_ENGLISH_EIRE', 0x06), ('SUBLANG_ENGLISH_SOUTH_AFRICA', 0x07), ('SUBLANG_ENGLISH_JAMAICA', 0x08), ('SUBLANG_ENGLISH_CARIBBEAN', 0x09), ('SUBLANG_ENGLISH_BELIZE', 0x0a), ('SUBLANG_ENGLISH_TRINIDAD', 0x0b), ('SUBLANG_ENGLISH_ZIMBABWE', 0x0c), ('SUBLANG_ENGLISH_PHILIPPINES', 0x0d), ('SUBLANG_FRENCH', 0x01), ('SUBLANG_FRENCH_BELGIAN', 0x02), ('SUBLANG_FRENCH_CANADIAN', 0x03), ('SUBLANG_FRENCH_SWISS', 0x04), ('SUBLANG_FRENCH_LUXEMBOURG', 0x05), ('SUBLANG_FRENCH_MONACO', 0x06), ('SUBLANG_GERMAN', 0x01), ('SUBLANG_GERMAN_SWISS', 0x02), ('SUBLANG_GERMAN_AUSTRIAN', 0x03), ('SUBLANG_GERMAN_LUXEMBOURG', 0x04), ('SUBLANG_GERMAN_LIECHTENSTEIN', 0x05), ('SUBLANG_ITALIAN', 0x01), ('SUBLANG_ITALIAN_SWISS', 0x02), ('SUBLANG_KASHMIRI_SASIA', 0x02), ('SUBLANG_KASHMIRI_INDIA', 0x02), ('SUBLANG_KOREAN', 0x01), ('SUBLANG_LITHUANIAN', 0x01), ('SUBLANG_MALAY_MALAYSIA', 0x01), ('SUBLANG_MALAY_BRUNEI_DARUSSALAM', 0x02), ('SUBLANG_NEPALI_INDIA', 0x02), ('SUBLANG_NORWEGIAN_BOKMAL', 0x01), ('SUBLANG_NORWEGIAN_NYNORSK', 0x02), ('SUBLANG_PORTUGUESE', 0x02), ('SUBLANG_PORTUGUESE_BRAZILIAN', 0x01), ('SUBLANG_SERBIAN_LATIN', 0x02), ('SUBLANG_SERBIAN_CYRILLIC', 0x03), ('SUBLANG_SPANISH', 0x01), ('SUBLANG_SPANISH_MEXICAN', 0x02), ('SUBLANG_SPANISH_MODERN', 0x03), ('SUBLANG_SPANISH_GUATEMALA', 0x04), ('SUBLANG_SPANISH_COSTA_RICA', 0x05), ('SUBLANG_SPANISH_PANAMA', 0x06), ('SUBLANG_SPANISH_DOMINICAN_REPUBLIC', 0x07), ('SUBLANG_SPANISH_VENEZUELA', 0x08), ('SUBLANG_SPANISH_COLOMBIA', 0x09), ('SUBLANG_SPANISH_PERU', 0x0a), ('SUBLANG_SPANISH_ARGENTINA', 0x0b), ('SUBLANG_SPANISH_ECUADOR', 0x0c), ('SUBLANG_SPANISH_CHILE', 0x0d), ('SUBLANG_SPANISH_URUGUAY', 0x0e), ('SUBLANG_SPANISH_PARAGUAY', 0x0f), ('SUBLANG_SPANISH_BOLIVIA', 0x10), ('SUBLANG_SPANISH_EL_SALVADOR', 0x11), ('SUBLANG_SPANISH_HONDURAS', 0x12), ('SUBLANG_SPANISH_NICARAGUA', 0x13), ('SUBLANG_SPANISH_PUERTO_RICO', 0x14), ('SUBLANG_SWEDISH', 0x01), ('SUBLANG_SWEDISH_FINLAND', 0x02), ('SUBLANG_URDU_PAKISTAN', 0x01), ('SUBLANG_URDU_INDIA', 0x02), ('SUBLANG_UZBEK_LATIN', 0x01), ('SUBLANG_UZBEK_CYRILLIC', 0x02), ('SUBLANG_DUTCH_SURINAM', 0x03), ('SUBLANG_ROMANIAN', 0x01), ('SUBLANG_ROMANIAN_MOLDAVIA', 0x02), ('SUBLANG_RUSSIAN', 0x01), ('SUBLANG_RUSSIAN_MOLDAVIA', 0x02), ('SUBLANG_CROATIAN', 0x01), ('SUBLANG_LITHUANIAN_CLASSIC', 0x02), ('SUBLANG_GAELIC', 0x01), ('SUBLANG_GAELIC_SCOTTISH', 0x02), ('SUBLANG_GAELIC_MANX', 0x03) ] SUBLANG = dict(sublang+[(e[1], e[0]) for e in sublang]) class UnicodeStringWrapperPostProcessor: """This class attemps to help the process of identifying strings that might be plain Unicode or Pascal. A list of strings will be wrapped on it with the hope the overlappings will help make the decission about their type.""" def __init__(self, pe, rva_ptr): self.pe = pe self.rva_ptr = rva_ptr self.string = None def get_rva(self): """Get the RVA of the string.""" return self.rva_ptr def __str__(self): """Return the escaped ASCII representation of the string.""" def convert_char(char): if char in string.printable: return char else: return r'\x%02x' % ord(char) if self.string: return ''.join([convert_char(c) for c in self.string]) return '' def invalidate(self): """Make this instance None, to express it's no known string type.""" self = None def render_pascal_16(self): self.string = self.pe.get_string_u_at_rva( self.rva_ptr+2, max_length=self.__get_pascal_16_length()) def ask_pascal_16(self, next_rva_ptr): """The next RVA is taken to be the one immediately following this one. Such RVA could indicate the natural end of the string and will be checked with the possible length contained in the first word. """ length = self.__get_pascal_16_length() if length == (next_rva_ptr - (self.rva_ptr+2)) / 2: self.length = length return True return False def __get_pascal_16_length(self): return self.__get_word_value_at_rva(self.rva_ptr) def __get_word_value_at_rva(self, rva): try: data = self.pe.get_data(self.rva_ptr, 2) except PEFormatError, e: return False if len(data)<2: return False return struct.unpack('<H', data)[0] #def render_pascal_8(self): # """""" def ask_unicode_16(self, next_rva_ptr): """The next RVA is taken to be the one immediately following this one. Such RVA could indicate the natural end of the string and will be checked to see if there's a Unicode NULL character there. """ if self.__get_word_value_at_rva(next_rva_ptr-2) == 0: self.length = next_rva_ptr - self.rva_ptr return True return False def render_unicode_16(self): """""" self.string = self.pe.get_string_u_at_rva(self.rva_ptr) class PEFormatError(Exception): """Generic PE format error exception.""" def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Dump: """Convenience class for dumping the PE information.""" def __init__(self): self.text = list() def add_lines(self, txt, indent=0): """Adds a list of lines. The list can be indented with the optional argument 'indent'. """ for line in txt: self.add_line(line, indent) def add_line(self, txt, indent=0): """Adds a line. The line can be indented with the optional argument 'indent'. """ self.add(txt+'\n', indent) def add(self, txt, indent=0): """Adds some text, no newline will be appended. The text can be indented with the optional argument 'indent'. """ if isinstance(txt, unicode): try: txt = str(txt) except UnicodeEncodeError: s = [] for c in txt: try: s.append(str(c)) except UnicodeEncodeError: s.append(repr(c)) txt = ''.join(s) self.text.append( ' '*indent + txt ) def add_header(self, txt): """Adds a header element.""" self.add_line('-'*10+txt+'-'*10+'\n') def add_newline(self): """Adds a newline.""" self.text.append( '\n' ) def get_text(self): """Get the text in its current state.""" return ''.join( self.text ) class Structure: """Prepare structure object to extract members from data. Format is a list containing definitions for the elements of the structure. """ def __init__(self, format, name=None, file_offset=None): # Format is forced little endian, for big endian non Intel platforms self.__format__ = '<' self.__keys__ = [] #self.values = {} self.__format_length__ = 0 self.__set_format__(format[1]) self.__all_zeroes__ = False self.__unpacked_data_elms__ = None self.__file_offset__ = file_offset if name: self.name = name else: self.name = format[0] def __get_format__(self): return self.__format__ def get_file_offset(self): return self.__file_offset__ def set_file_offset(self, offset): self.__file_offset__ = offset def all_zeroes(self): """Returns true is the unpacked data is all zeroes.""" return self.__all_zeroes__ def __set_format__(self, format): for elm in format: if ',' in elm: elm_type, elm_name = elm.split(',', 1) self.__format__ += elm_type elm_names = elm_name.split(',') names = [] for elm_name in elm_names: if elm_name in self.__keys__: search_list = [x[:len(elm_name)] for x in self.__keys__] occ_count = search_list.count(elm_name) elm_name = elm_name+'_'+str(occ_count) names.append(elm_name) # Some PE header structures have unions on them, so a certain # value might have different names, so each key has a list of # all the possible members referring to the data. self.__keys__.append(names) self.__format_length__ = struct.calcsize(self.__format__) def sizeof(self): """Return size of the structure.""" return self.__format_length__ def __unpack__(self, data): if len(data) > self.__format_length__: data = data[:self.__format_length__] # OC Patch: # Some malware have incorrect header lengths. # Fail gracefully if this occurs # Buggy malware: a29b0118af8b7408444df81701ad5a7f # elif len(data)<self.__format_length__: raise PEFormatError('Data length less than expected header length.') if data.count(chr(0)) == len(data): self.__all_zeroes__ = True self.__unpacked_data_elms__ = struct.unpack(self.__format__, data) for i in xrange(len(self.__unpacked_data_elms__)): for key in self.__keys__[i]: #self.values[key] = self.__unpacked_data_elms__[i] setattr(self, key, self.__unpacked_data_elms__[i]) def __pack__(self): new_values = [] for i in xrange(len(self.__unpacked_data_elms__)): for key in self.__keys__[i]: new_val = getattr(self, key) old_val = self.__unpacked_data_elms__[i] # In the case of Unions, when the first changed value # is picked the loop is exited if new_val != old_val: break new_values.append(new_val) return struct.pack(self.__format__, *new_values) def __str__(self): return '\n'.join( self.dump() ) def __repr__(self): return '<Structure: %s>' % (' '.join( [' '.join(s.split()) for s in self.dump()] )) def dump(self, indentation=0): """Returns a string representation of the structure.""" dump = [] dump.append('[%s]' % self.name) # Refer to the __set_format__ method for an explanation # of the following construct. for keys in self.__keys__: for key in keys: val = getattr(self, key) if isinstance(val, int) or isinstance(val, long): val_str = '0x%-8X' % (val) if key == 'TimeDateStamp' or key == 'dwTimeStamp': try: val_str += ' [%s UTC]' % time.asctime(time.gmtime(val)) except exceptions.ValueError, e: val_str += ' [INVALID TIME]' else: val_str = ''.join(filter(lambda c:c != '\0', str(val))) dump.append('%-30s %s' % (key+':', val_str)) return dump class SectionStructure(Structure): """Convenience section handling class.""" def get_data(self, start, length=None): """Get data chunk from a section. Allows to query data from the section by passing the addresses where the PE file would be loaded by default. It is then possible to retrieve code and data by its real addresses as it would be if loaded. """ offset = start - self.VirtualAddress if length: end = offset+length else: end = len(self.data) return self.data[offset:end] def get_rva_from_offset(self, offset): return offset - self.PointerToRawData + self.VirtualAddress def get_offset_from_rva(self, rva): return (rva - self.VirtualAddress) + self.PointerToRawData def contains_offset(self, offset): """Check whether the section contains the file offset provided.""" if not self.PointerToRawData: # bss and other sections containing only uninitialized data must have 0 # and do not take space in the file return False return self.PointerToRawData <= offset < self.PointerToRawData + self.SizeOfRawData def contains_rva(self, rva): """Check whether the section contains the address provided.""" # PECOFF documentation v8 says: # The total size of the section when loaded into memory. # If this value is greater than SizeOfRawData, the section is zero-padded. # This field is valid only for executable images and should be set to zero # for object files. if len(self.data) < self.SizeOfRawData: size = self.Misc_VirtualSize else: size = max(self.SizeOfRawData, self.Misc_VirtualSize) return self.VirtualAddress <= rva < self.VirtualAddress + size def contains(self, rva): #print "DEPRECATION WARNING: you should use contains_rva() instead of contains()" return self.contains_rva(rva) def set_data(self, data): """Set the data belonging to the section.""" self.data = data def get_entropy(self): """Calculate and return the entropy for the section.""" return self.entropy_H( self.data ) def get_hash_sha1(self): """Get the SHA-1 hex-digest of the section's data.""" if sha1 is not None: return sha1( self.data ).hexdigest() def get_hash_sha256(self): """Get the SHA-256 hex-digest of the section's data.""" if sha256 is not None: return sha256( self.data ).hexdigest() def get_hash_sha512(self): """Get the SHA-512 hex-digest of the section's data.""" if sha512 is not None: return sha512( self.data ).hexdigest() def get_hash_md5(self): """Get the MD5 hex-digest of the section's data.""" if md5 is not None: return md5( self.data ).hexdigest() def entropy_H(self, data): """Calculate the entropy of a chunk of data.""" if len(data) == 0: return 0.0 occurences = array.array('L', [0]*256) for x in data: occurences[ord(x)] += 1 entropy = 0 for x in occurences: if x: p_x = float(x) / len(data) entropy -= p_x*math.log(p_x, 2) return entropy class DataContainer: """Generic data container.""" def __init__(self, **args): for key, value in args.items(): setattr(self, key, value) class ImportDescData(DataContainer): """Holds import descriptor information. dll: name of the imported DLL imports: list of imported symbols (ImportData instances) struct: IMAGE_IMPORT_DESCRIPTOR sctruture """ class ImportData(DataContainer): """Holds imported symbol's information. ordinal: Ordinal of the symbol name: Name of the symbol bound: If the symbol is bound, this contains the address. """ class ExportDirData(DataContainer): """Holds export directory information. struct: IMAGE_EXPORT_DIRECTORY structure symbols: list of exported symbols (ExportData instances) """ class ExportData(DataContainer): """Holds exported symbols' information. ordinal: ordinal of the symbol address: address of the symbol name: name of the symbol (None if the symbol is exported by ordinal only) forwarder: if the symbol is forwarded it will contain the name of the target symbol, None otherwise. """ class ResourceDirData(DataContainer): """Holds resource directory information. struct: IMAGE_RESOURCE_DIRECTORY structure entries: list of entries (ResourceDirEntryData instances) """ class ResourceDirEntryData(DataContainer): """Holds resource directory entry data. struct: IMAGE_RESOURCE_DIRECTORY_ENTRY structure name: If the resource is identified by name this attribute will contain the name string. None otherwise. If identified by id, the id is availabe at 'struct.Id' id: the id, also in struct.Id directory: If this entry has a lower level directory this attribute will point to the ResourceDirData instance representing it. data: If this entry has no futher lower directories and points to the actual resource data, this attribute will reference the corresponding ResourceDataEntryData instance. (Either of the 'directory' or 'data' attribute will exist, but not both.) """ class ResourceDataEntryData(DataContainer): """Holds resource data entry information. struct: IMAGE_RESOURCE_DATA_ENTRY structure lang: Primary language ID sublang: Sublanguage ID """ class DebugData(DataContainer): """Holds debug information. struct: IMAGE_DEBUG_DIRECTORY structure """ class BaseRelocationData(DataContainer): """Holds base relocation information. struct: IMAGE_BASE_RELOCATION structure entries: list of relocation data (RelocationData instances) """ class RelocationData(DataContainer): """Holds relocation information. type: Type of relocation The type string is can be obtained by RELOCATION_TYPE[type] rva: RVA of the relocation """ class TlsData(DataContainer): """Holds TLS information. struct: IMAGE_TLS_DIRECTORY structure """ class BoundImportDescData(DataContainer): """Holds bound import descriptor data. This directory entry will provide with information on the DLLs this PE files has been bound to (if bound at all). The structure will contain the name and timestamp of the DLL at the time of binding so that the loader can know whether it differs from the one currently present in the system and must, therefore, re-bind the PE's imports. struct: IMAGE_BOUND_IMPORT_DESCRIPTOR structure name: DLL name entries: list of entries (BoundImportRefData instances) the entries will exist if this DLL has forwarded symbols. If so, the destination DLL will have an entry in this list. """ class LoadConfigData(DataContainer): """Holds Load Config data. struct: IMAGE_LOAD_CONFIG_DIRECTORY structure name: dll name """ class BoundImportRefData(DataContainer): """Holds bound import forwader reference data. Contains the same information as the bound descriptor but for forwarded DLLs, if any. struct: IMAGE_BOUND_FORWARDER_REF structure name: dll name """ class PE: """A Portable Executable representation. This class provides access to most of the information in a PE file. It expects to be supplied the name of the file to load or PE data to process and an optional argument 'fast_load' (False by default) which controls whether to load all the directories information, which can be quite time consuming. pe = pefile.PE('module.dll') pe = pefile.PE(name='module.dll') would load 'module.dll' and process it. If the data would be already available in a buffer the same could be achieved with: pe = pefile.PE(data=module_dll_data) The "fast_load" can be set to a default by setting its value in the module itself by means,for instance, of a "pefile.fast_load = True". That will make all the subsequent instances not to load the whole PE structure. The "full_load" method can be used to parse the missing data at a later stage. Basic headers information will be available in the attributes: DOS_HEADER NT_HEADERS FILE_HEADER OPTIONAL_HEADER All of them will contain among their attrbitues the members of the corresponding structures as defined in WINNT.H The raw data corresponding to the header (from the beginning of the file up to the start of the first section) will be avaiable in the instance's attribute 'header' as a string. The sections will be available as a list in the 'sections' attribute. Each entry will contain as attributes all the structure's members. Directory entries will be available as attributes (if they exist): (no other entries are processed at this point) DIRECTORY_ENTRY_IMPORT (list of ImportDescData instances) DIRECTORY_ENTRY_EXPORT (ExportDirData instance) DIRECTORY_ENTRY_RESOURCE (ResourceDirData instance) DIRECTORY_ENTRY_DEBUG (list of DebugData instances) DIRECTORY_ENTRY_BASERELOC (list of BaseRelocationData instances) DIRECTORY_ENTRY_TLS DIRECTORY_ENTRY_BOUND_IMPORT (list of BoundImportData instances) The following dictionary attributes provide ways of mapping different constants. They will accept the numeric value and return the string representation and the opposite, feed in the string and get the numeric constant: DIRECTORY_ENTRY IMAGE_CHARACTERISTICS SECTION_CHARACTERISTICS DEBUG_TYPE SUBSYSTEM_TYPE MACHINE_TYPE RELOCATION_TYPE RESOURCE_TYPE LANG SUBLANG """ # # Format specifications for PE structures. # __IMAGE_DOS_HEADER_format__ = ('IMAGE_DOS_HEADER', ('H,e_magic', 'H,e_cblp', 'H,e_cp', 'H,e_crlc', 'H,e_cparhdr', 'H,e_minalloc', 'H,e_maxalloc', 'H,e_ss', 'H,e_sp', 'H,e_csum', 'H,e_ip', 'H,e_cs', 'H,e_lfarlc', 'H,e_ovno', '8s,e_res', 'H,e_oemid', 'H,e_oeminfo', '20s,e_res2', 'I,e_lfanew')) __IMAGE_FILE_HEADER_format__ = ('IMAGE_FILE_HEADER', ('H,Machine', 'H,NumberOfSections', 'I,TimeDateStamp', 'I,PointerToSymbolTable', 'I,NumberOfSymbols', 'H,SizeOfOptionalHeader', 'H,Characteristics')) __IMAGE_DATA_DIRECTORY_format__ = ('IMAGE_DATA_DIRECTORY', ('I,VirtualAddress', 'I,Size')) __IMAGE_OPTIONAL_HEADER_format__ = ('IMAGE_OPTIONAL_HEADER', ('H,Magic', 'B,MajorLinkerVersion', 'B,MinorLinkerVersion', 'I,SizeOfCode', 'I,SizeOfInitializedData', 'I,SizeOfUninitializedData', 'I,AddressOfEntryPoint', 'I,BaseOfCode', 'I,BaseOfData', 'I,ImageBase', 'I,SectionAlignment', 'I,FileAlignment', 'H,MajorOperatingSystemVersion', 'H,MinorOperatingSystemVersion', 'H,MajorImageVersion', 'H,MinorImageVersion', 'H,MajorSubsystemVersion', 'H,MinorSubsystemVersion', 'I,Reserved1', 'I,SizeOfImage', 'I,SizeOfHeaders', 'I,CheckSum', 'H,Subsystem', 'H,DllCharacteristics', 'I,SizeOfStackReserve', 'I,SizeOfStackCommit', 'I,SizeOfHeapReserve', 'I,SizeOfHeapCommit', 'I,LoaderFlags', 'I,NumberOfRvaAndSizes' )) __IMAGE_OPTIONAL_HEADER64_format__ = ('IMAGE_OPTIONAL_HEADER64', ('H,Magic', 'B,MajorLinkerVersion', 'B,MinorLinkerVersion', 'I,SizeOfCode', 'I,SizeOfInitializedData', 'I,SizeOfUninitializedData', 'I,AddressOfEntryPoint', 'I,BaseOfCode', 'Q,ImageBase', 'I,SectionAlignment', 'I,FileAlignment', 'H,MajorOperatingSystemVersion', 'H,MinorOperatingSystemVersion', 'H,MajorImageVersion', 'H,MinorImageVersion', 'H,MajorSubsystemVersion', 'H,MinorSubsystemVersion', 'I,Reserved1', 'I,SizeOfImage', 'I,SizeOfHeaders', 'I,CheckSum', 'H,Subsystem', 'H,DllCharacteristics', 'Q,SizeOfStackReserve', 'Q,SizeOfStackCommit', 'Q,SizeOfHeapReserve', 'Q,SizeOfHeapCommit', 'I,LoaderFlags', 'I,NumberOfRvaAndSizes' )) __IMAGE_NT_HEADERS_format__ = ('IMAGE_NT_HEADERS', ('I,Signature',)) __IMAGE_SECTION_HEADER_format__ = ('IMAGE_SECTION_HEADER', ('8s,Name', 'I,Misc,Misc_PhysicalAddress,Misc_VirtualSize', 'I,VirtualAddress', 'I,SizeOfRawData', 'I,PointerToRawData', 'I,PointerToRelocations', 'I,PointerToLinenumbers', 'H,NumberOfRelocations', 'H,NumberOfLinenumbers', 'I,Characteristics')) __IMAGE_DELAY_IMPORT_DESCRIPTOR_format__ = ('IMAGE_DELAY_IMPORT_DESCRIPTOR', ('I,grAttrs', 'I,szName', 'I,phmod', 'I,pIAT', 'I,pINT', 'I,pBoundIAT', 'I,pUnloadIAT', 'I,dwTimeStamp')) __IMAGE_IMPORT_DESCRIPTOR_format__ = ('IMAGE_IMPORT_DESCRIPTOR', ('I,OriginalFirstThunk,Characteristics', 'I,TimeDateStamp', 'I,ForwarderChain', 'I,Name', 'I,FirstThunk')) __IMAGE_EXPORT_DIRECTORY_format__ = ('IMAGE_EXPORT_DIRECTORY', ('I,Characteristics', 'I,TimeDateStamp', 'H,MajorVersion', 'H,MinorVersion', 'I,Name', 'I,Base', 'I,NumberOfFunctions', 'I,NumberOfNames', 'I,AddressOfFunctions', 'I,AddressOfNames', 'I,AddressOfNameOrdinals')) __IMAGE_RESOURCE_DIRECTORY_format__ = ('IMAGE_RESOURCE_DIRECTORY', ('I,Characteristics', 'I,TimeDateStamp', 'H,MajorVersion', 'H,MinorVersion', 'H,NumberOfNamedEntries', 'H,NumberOfIdEntries')) __IMAGE_RESOURCE_DIRECTORY_ENTRY_format__ = ('IMAGE_RESOURCE_DIRECTORY_ENTRY', ('I,Name', 'I,OffsetToData')) __IMAGE_RESOURCE_DATA_ENTRY_format__ = ('IMAGE_RESOURCE_DATA_ENTRY', ('I,OffsetToData', 'I,Size', 'I,CodePage', 'I,Reserved')) __VS_VERSIONINFO_format__ = ( 'VS_VERSIONINFO', ('H,Length', 'H,ValueLength', 'H,Type' )) __VS_FIXEDFILEINFO_format__ = ( 'VS_FIXEDFILEINFO', ('I,Signature', 'I,StrucVersion', 'I,FileVersionMS', 'I,FileVersionLS', 'I,ProductVersionMS', 'I,ProductVersionLS', 'I,FileFlagsMask', 'I,FileFlags', 'I,FileOS', 'I,FileType', 'I,FileSubtype', 'I,FileDateMS', 'I,FileDateLS')) __StringFileInfo_format__ = ( 'StringFileInfo', ('H,Length', 'H,ValueLength', 'H,Type' )) __StringTable_format__ = ( 'StringTable', ('H,Length', 'H,ValueLength', 'H,Type' )) __String_format__ = ( 'String', ('H,Length', 'H,ValueLength', 'H,Type' )) __Var_format__ = ( 'Var', ('H,Length', 'H,ValueLength', 'H,Type' )) __IMAGE_THUNK_DATA_format__ = ('IMAGE_THUNK_DATA', ('I,ForwarderString,Function,Ordinal,AddressOfData',)) __IMAGE_THUNK_DATA64_format__ = ('IMAGE_THUNK_DATA', ('Q,ForwarderString,Function,Ordinal,AddressOfData',)) __IMAGE_DEBUG_DIRECTORY_format__ = ('IMAGE_DEBUG_DIRECTORY', ('I,Characteristics', 'I,TimeDateStamp', 'H,MajorVersion', 'H,MinorVersion', 'I,Type', 'I,SizeOfData', 'I,AddressOfRawData', 'I,PointerToRawData')) __IMAGE_BASE_RELOCATION_format__ = ('IMAGE_BASE_RELOCATION', ('I,VirtualAddress', 'I,SizeOfBlock') ) __IMAGE_TLS_DIRECTORY_format__ = ('IMAGE_TLS_DIRECTORY', ('I,StartAddressOfRawData', 'I,EndAddressOfRawData', 'I,AddressOfIndex', 'I,AddressOfCallBacks', 'I,SizeOfZeroFill', 'I,Characteristics' ) ) __IMAGE_TLS_DIRECTORY64_format__ = ('IMAGE_TLS_DIRECTORY', ('Q,StartAddressOfRawData', 'Q,EndAddressOfRawData', 'Q,AddressOfIndex', 'Q,AddressOfCallBacks', 'I,SizeOfZeroFill', 'I,Characteristics' ) ) __IMAGE_LOAD_CONFIG_DIRECTORY_format__ = ('IMAGE_LOAD_CONFIG_DIRECTORY', ('I,Size', 'I,TimeDateStamp', 'H,MajorVersion', 'H,MinorVersion', 'I,GlobalFlagsClear', 'I,GlobalFlagsSet', 'I,CriticalSectionDefaultTimeout', 'I,DeCommitFreeBlockThreshold', 'I,DeCommitTotalFreeThreshold', 'I,LockPrefixTable', 'I,MaximumAllocationSize', 'I,VirtualMemoryThreshold', 'I,ProcessHeapFlags', 'I,ProcessAffinityMask', 'H,CSDVersion', 'H,Reserved1', 'I,EditList', 'I,SecurityCookie', 'I,SEHandlerTable', 'I,SEHandlerCount' ) ) __IMAGE_LOAD_CONFIG_DIRECTORY64_format__ = ('IMAGE_LOAD_CONFIG_DIRECTORY', ('I,Size', 'I,TimeDateStamp', 'H,MajorVersion', 'H,MinorVersion', 'I,GlobalFlagsClear', 'I,GlobalFlagsSet', 'I,CriticalSectionDefaultTimeout', 'Q,DeCommitFreeBlockThreshold', 'Q,DeCommitTotalFreeThreshold', 'Q,LockPrefixTable', 'Q,MaximumAllocationSize', 'Q,VirtualMemoryThreshold', 'Q,ProcessAffinityMask', 'I,ProcessHeapFlags', 'H,CSDVersion', 'H,Reserved1', 'Q,EditList', 'Q,SecurityCookie', 'Q,SEHandlerTable', 'Q,SEHandlerCount' ) ) __IMAGE_BOUND_IMPORT_DESCRIPTOR_format__ = ('IMAGE_BOUND_IMPORT_DESCRIPTOR', ('I,TimeDateStamp', 'H,OffsetModuleName', 'H,NumberOfModuleForwarderRefs')) __IMAGE_BOUND_FORWARDER_REF_format__ = ('IMAGE_BOUND_FORWARDER_REF', ('I,TimeDateStamp', 'H,OffsetModuleName', 'H,Reserved') ) def __init__(self, name=None, data=None, fast_load=None): self.sections = [] self.__warnings = [] self.PE_TYPE = None if not name and not data: return # This list will keep track of all the structures created. # That will allow for an easy iteration through the list # in order to save the modifications made self.__structures__ = [] if not fast_load: fast_load = globals()['fast_load'] self.__parse__(name, data, fast_load) def __unpack_data__(self, format, data, file_offset): """Apply structure format to raw data. Returns and unpacked structure object if successful, None otherwise. """ structure = Structure(format, file_offset=file_offset) #if len(data) < structure.sizeof(): # return None try: structure.__unpack__(data) except PEFormatError, err: self.__warnings.append( 'Corrupt header "%s" at file offset %d. Exception: %s' % ( format[0], file_offset, str(err)) ) return None self.__structures__.append(structure) return structure def __parse__(self, fname, data, fast_load): """Parse a Portable Executable file. Loads a PE file, parsing all its structures and making them available through the instance's attributes. """ if fname: fd = file(fname, 'rb') self.__data__ = fd.read() fd.close() elif data: self.__data__ = data self.DOS_HEADER = self.__unpack_data__( self.__IMAGE_DOS_HEADER_format__, self.__data__, file_offset=0) if not self.DOS_HEADER or self.DOS_HEADER.e_magic != IMAGE_DOS_SIGNATURE: raise PEFormatError('DOS Header magic not found.') # OC Patch: # Check for sane value in e_lfanew # if self.DOS_HEADER.e_lfanew > len(self.__data__): raise PEFormatError('Invalid e_lfanew value, probably not a PE file') nt_headers_offset = self.DOS_HEADER.e_lfanew self.NT_HEADERS = self.__unpack_data__( self.__IMAGE_NT_HEADERS_format__, self.__data__[nt_headers_offset:], file_offset = nt_headers_offset) # We better check the signature right here, before the file screws # around with sections: # OC Patch: # Some malware will cause the Signature value to not exist at all if not self.NT_HEADERS or not self.NT_HEADERS.Signature: raise PEFormatError('NT Headers not found.') if self.NT_HEADERS.Signature != IMAGE_NT_SIGNATURE: raise PEFormatError('Invalid NT Headers signature.') self.FILE_HEADER = self.__unpack_data__( self.__IMAGE_FILE_HEADER_format__, self.__data__[nt_headers_offset+4:], file_offset = nt_headers_offset+4) image_flags = self.retrieve_flags(IMAGE_CHARACTERISTICS, 'IMAGE_FILE_') if not self.FILE_HEADER: raise PEFormatError('File Header missing') # Set the image's flags according the the Characteristics member self.set_flags(self.FILE_HEADER, self.FILE_HEADER.Characteristics, image_flags) optional_header_offset = \ nt_headers_offset+4+self.FILE_HEADER.sizeof() # Note: location of sections can be controlled from PE header: sections_offset = optional_header_offset + self.FILE_HEADER.SizeOfOptionalHeader self.OPTIONAL_HEADER = self.__unpack_data__( self.__IMAGE_OPTIONAL_HEADER_format__, self.__data__[optional_header_offset:], file_offset = optional_header_offset) # According to solardesigner's findings for his # Tiny PE project, the optional header does not # need fields beyond "Subsystem" in order to be # loadable by the Windows loader (given that zeroes # are acceptable values and the header is loaded # in a zeroed memory page) # If trying to parse a full Optional Header fails # we try to parse it again with some 0 padding # MINIMUM_VALID_OPTIONAL_HEADER_RAW_SIZE = 69 if ( self.OPTIONAL_HEADER is None and len(self.__data__[optional_header_offset:]) >= MINIMUM_VALID_OPTIONAL_HEADER_RAW_SIZE ): # Add enough zeroes to make up for the unused fields # padding_length = 128 # Create padding # padded_data = self.__data__[optional_header_offset:] + ( '\0' * padding_length) self.OPTIONAL_HEADER = self.__unpack_data__( self.__IMAGE_OPTIONAL_HEADER_format__, padded_data, file_offset = optional_header_offset) # Check the Magic in the OPTIONAL_HEADER and set the PE file # type accordingly # if self.OPTIONAL_HEADER is not None: if self.OPTIONAL_HEADER.Magic == OPTIONAL_HEADER_MAGIC_PE: self.PE_TYPE = OPTIONAL_HEADER_MAGIC_PE elif self.OPTIONAL_HEADER.Magic == OPTIONAL_HEADER_MAGIC_PE_PLUS: self.PE_TYPE = OPTIONAL_HEADER_MAGIC_PE_PLUS self.OPTIONAL_HEADER = self.__unpack_data__( self.__IMAGE_OPTIONAL_HEADER64_format__, self.__data__[optional_header_offset:], file_offset = optional_header_offset) # Again, as explained above, we try to parse # a reduced form of the Optional Header which # is still valid despite not including all # structure members # MINIMUM_VALID_OPTIONAL_HEADER_RAW_SIZE = 69+4 if ( self.OPTIONAL_HEADER is None and len(self.__data__[optional_header_offset:]) >= MINIMUM_VALID_OPTIONAL_HEADER_RAW_SIZE ): padding_length = 128 padded_data = self.__data__[optional_header_offset:] + ( '\0' * padding_length) self.OPTIONAL_HEADER = self.__unpack_data__( self.__IMAGE_OPTIONAL_HEADER64_format__, padded_data, file_offset = optional_header_offset) if not self.FILE_HEADER: raise PEFormatError('File Header missing') # OC Patch: # Die gracefully if there is no OPTIONAL_HEADER field # 975440f5ad5e2e4a92c4d9a5f22f75c1 if self.PE_TYPE is None or self.OPTIONAL_HEADER is None: raise PEFormatError("No Optional Header found, invalid PE32 or PE32+ file") dll_characteristics_flags = self.retrieve_flags(DLL_CHARACTERISTICS, 'IMAGE_DLL_CHARACTERISTICS_') # Set the Dll Characteristics flags according the the DllCharacteristics member self.set_flags( self.OPTIONAL_HEADER, self.OPTIONAL_HEADER.DllCharacteristics, dll_characteristics_flags) self.OPTIONAL_HEADER.DATA_DIRECTORY = [] #offset = (optional_header_offset + self.FILE_HEADER.SizeOfOptionalHeader) offset = (optional_header_offset + self.OPTIONAL_HEADER.sizeof()) self.NT_HEADERS.FILE_HEADER = self.FILE_HEADER self.NT_HEADERS.OPTIONAL_HEADER = self.OPTIONAL_HEADER # The NumberOfRvaAndSizes is sanitized to stay within # reasonable limits so can be casted to an int # if self.OPTIONAL_HEADER.NumberOfRvaAndSizes > 0x10: self.__warnings.append( 'Suspicious NumberOfRvaAndSizes in the Optional Header. ' + 'Normal values are never larger than 0x10, the value is: 0x%x' % self.OPTIONAL_HEADER.NumberOfRvaAndSizes ) for i in xrange(int(0x7fffffffL & self.OPTIONAL_HEADER.NumberOfRvaAndSizes)): if len(self.__data__[offset:]) == 0: break if len(self.__data__[offset:]) < 8: data = self.__data__[offset:]+'\0'*8 else: data = self.__data__[offset:] dir_entry = self.__unpack_data__( self.__IMAGE_DATA_DIRECTORY_format__, data, file_offset = offset) if dir_entry is None: break # Would fail if missing an entry # 1d4937b2fa4d84ad1bce0309857e70ca offending sample try: dir_entry.name = DIRECTORY_ENTRY[i] except (KeyError, AttributeError): break offset += dir_entry.sizeof() self.OPTIONAL_HEADER.DATA_DIRECTORY.append(dir_entry) # If the offset goes outside the optional header, # the loop is broken, regardless of how many directories # NumberOfRvaAndSizes says there are # # We assume a normally sized optional header, hence that we do # a sizeof() instead of reading SizeOfOptionalHeader. # Then we add a default number of drectories times their size, # if we go beyond that, we assume the number of directories # is wrong and stop processing if offset >= (optional_header_offset + self.OPTIONAL_HEADER.sizeof() + 8*16) : break offset = self.parse_sections(sections_offset) # OC Patch: # There could be a problem if there are no raw data sections # greater than 0 # fc91013eb72529da005110a3403541b6 example # Should this throw an exception in the minimum header offset # can't be found? # rawDataPointers = [ s.PointerToRawData for s in self.sections if s.PointerToRawData>0] if len(rawDataPointers) > 0: lowest_section_offset = min(rawDataPointers) else: lowest_section_offset = None if not lowest_section_offset or lowest_section_offset<offset: self.header = self.__data__[:offset] else: self.header = self.__data__[:lowest_section_offset] # Check whether the entry point lies within a section # if self.get_section_by_rva(self.OPTIONAL_HEADER.AddressOfEntryPoint) is not None: # Check whether the entry point lies within the file # ep_offset = self.get_offset_from_rva(self.OPTIONAL_HEADER.AddressOfEntryPoint) if ep_offset > len(self.__data__): self.__warnings.append( 'Possibly corrupt file. AddressOfEntryPoint lies outside the file. ' + 'AddressOfEntryPoint: 0x%x' % self.OPTIONAL_HEADER.AddressOfEntryPoint ) else: self.__warnings.append( 'AddressOfEntryPoint lies outside the sections\' boundaries. ' + 'AddressOfEntryPoint: 0x%x' % self.OPTIONAL_HEADER.AddressOfEntryPoint ) if not fast_load: self.parse_data_directories() def get_warnings(self): """Return the list of warnings. Non-critical problems found when parsing the PE file are appended to a list of warnings. This method returns the full list. """ return self.__warnings def show_warnings(self): """Print the list of warnings. Non-critical problems found when parsing the PE file are appended to a list of warnings. This method prints the full list to standard output. """ for warning in self.__warnings: print '>', warning def full_load(self): """Process the data directories. This mathod will load the data directories which might not have been loaded if the "fast_load" option was used. """ self.parse_data_directories() def write(self, filename=None): """Write the PE file. This function will process all headers and components of the PE file and include all changes made (by just assigning to attributes in the PE objects) and write the changes back to a file whose name is provided as an argument. The filename is optional, if not provided the data will be returned as a 'str' object. """ file_data = list(self.__data__) for structure in self.__structures__: struct_data = list(structure.__pack__()) offset = structure.get_file_offset() file_data[offset:offset+len(struct_data)] = struct_data if hasattr(self, 'VS_VERSIONINFO'): if hasattr(self, 'FileInfo'): for entry in self.FileInfo: if hasattr(entry, 'StringTable'): for st_entry in entry.StringTable: for key, entry in st_entry.entries.items(): offsets = st_entry.entries_offsets[key] lengths = st_entry.entries_lengths[key] if len( entry ) > lengths[1]: l = list() for idx, c in enumerate(entry): if ord(c) > 256: l.extend( [ chr(ord(c) & 0xff), chr( (ord(c) & 0xff00) >>8) ] ) else: l.extend( [chr( ord(c) ), '\0'] ) file_data[ offsets[1] : offsets[1] + lengths[1]*2 ] = l else: l = list() for idx, c in enumerate(entry): if ord(c) > 256: l.extend( [ chr(ord(c) & 0xff), chr( (ord(c) & 0xff00) >>8) ] ) else: l.extend( [chr( ord(c) ), '\0'] ) file_data[ offsets[1] : offsets[1] + len(entry)*2 ] = l remainder = lengths[1] - len(entry) file_data[ offsets[1] + len(entry)*2 : offsets[1] + lengths[1]*2 ] = [ u'\0' ] * remainder*2 new_file_data = ''.join( [ chr(ord(c)) for c in file_data] ) if filename: f = file(filename, 'wb+') f.write(new_file_data) f.close() else: return new_file_data def parse_sections(self, offset): """Fetch the PE file sections. The sections will be readily available in the "sections" attribute. Its attributes will contain all the section information plus "data" a buffer containing the section's data. The "Characteristics" member will be processed and attributes representing the section characteristics (with the 'IMAGE_SCN_' string trimmed from the constant's names) will be added to the section instance. Refer to the SectionStructure class for additional info. """ self.sections = [] for i in xrange(self.FILE_HEADER.NumberOfSections): section = SectionStructure(self.__IMAGE_SECTION_HEADER_format__) if not section: break section_offset = offset + section.sizeof() * i section.set_file_offset(section_offset) section.__unpack__(self.__data__[section_offset:]) self.__structures__.append(section) if section.SizeOfRawData > len(self.__data__): self.__warnings.append( ('Error parsing section %d. ' % i) + 'SizeOfRawData is larger than file.') if section.PointerToRawData > len(self.__data__): self.__warnings.append( ('Error parsing section %d. ' % i) + 'PointerToRawData points beyond the end of the file.') if section.Misc_VirtualSize > 0x10000000: self.__warnings.append( ('Suspicious value found parsing section %d. ' % i) + 'VirtualSize is extremely large > 256MiB.') if section.VirtualAddress > 0x10000000: self.__warnings.append( ('Suspicious value found parsing section %d. ' % i) + 'VirtualAddress is beyond 0x10000000.') # # Some packer used a non-aligned PointerToRawData in the sections, # which causes several common tools not to load the section data # properly as they blindly read from the indicated offset. # It seems that Windows will round the offset down to the largest # offset multiple of FileAlignment which is smaller than # PointerToRawData. The following code will do the same. # #alignment = self.OPTIONAL_HEADER.FileAlignment self.update_section_data(section) if ( self.OPTIONAL_HEADER.FileAlignment != 0 and (section.PointerToRawData % self.OPTIONAL_HEADER.FileAlignment) != 0): self.__warnings.append( ('Error parsing section %d. ' % i) + 'Suspicious value for FileAlignment in the Optional Header. ' + 'Normally the PointerToRawData entry of the sections\' structures ' + 'is a multiple of FileAlignment, this might imply the file ' + 'is trying to confuse tools which parse this incorrectly') section_flags = self.retrieve_flags(SECTION_CHARACTERISTICS, 'IMAGE_SCN_') # Set the section's flags according the the Characteristics member self.set_flags(section, section.Characteristics, section_flags) if ( section.__dict__.get('IMAGE_SCN_MEM_WRITE', False) and section.__dict__.get('IMAGE_SCN_MEM_EXECUTE', False) ): self.__warnings.append( ('Suspicious flags set for section %d. ' % i) + 'Both IMAGE_SCN_MEM_WRITE and IMAGE_SCN_MEM_EXECUTE are set.' + 'This might indicate a packed executable.') self.sections.append(section) if self.FILE_HEADER.NumberOfSections > 0 and self.sections: return offset + self.sections[0].sizeof()*self.FILE_HEADER.NumberOfSections else: return offset def retrieve_flags(self, flag_dict, flag_filter): """Read the flags from a dictionary and return them in a usable form. Will return a list of (flag, value) for all flags in "flag_dict" matching the filter "flag_filter". """ return [(f[0], f[1]) for f in flag_dict.items() if isinstance(f[0], str) and f[0].startswith(flag_filter)] def set_flags(self, obj, flag_field, flags): """Will process the flags and set attributes in the object accordingly. The object "obj" will gain attritutes named after the flags provided in "flags" and valued True/False, matching the results of applyin each flag value from "flags" to flag_field. """ for flag in flags: if flag[1] & flag_field: setattr(obj, flag[0], True) else: setattr(obj, flag[0], False) def parse_data_directories(self, directories=None): """Parse and process the PE file's data directories. If the optional argument 'directories' is given, only the directories at the specified indices will be parsed. Such funcionality allows parsing of areas of interest without the burden of having to parse all others. The directories can then be specified as: For export/import only: directories = [ 0, 1 ] or (more verbosely): directories = [ DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT'], DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_EXPORT'] ] If 'directories' is a list, the ones that are processed will be removed, leaving only the ones that are not present in the image. """ directory_parsing = ( ('IMAGE_DIRECTORY_ENTRY_IMPORT', self.parse_import_directory), ('IMAGE_DIRECTORY_ENTRY_EXPORT', self.parse_export_directory), ('IMAGE_DIRECTORY_ENTRY_RESOURCE', self.parse_resources_directory), ('IMAGE_DIRECTORY_ENTRY_DEBUG', self.parse_debug_directory), ('IMAGE_DIRECTORY_ENTRY_BASERELOC', self.parse_relocations_directory), ('IMAGE_DIRECTORY_ENTRY_TLS', self.parse_directory_tls), ('IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG', self.parse_directory_load_config), ('IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT', self.parse_delay_import_directory), ('IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT', self.parse_directory_bound_imports) ) if directories is not None: if not isinstance(directories, (tuple, list)): directories = [directories] for entry in directory_parsing: # OC Patch: # try: directory_index = DIRECTORY_ENTRY[entry[0]] dir_entry = self.OPTIONAL_HEADER.DATA_DIRECTORY[directory_index] except IndexError: break # Only process all the directories if no individual ones have # been chosen # if directories is None or directory_index in directories: if dir_entry.VirtualAddress: value = entry[1](dir_entry.VirtualAddress, dir_entry.Size) if value: setattr(self, entry[0][6:], value) if (directories is not None) and isinstance(directories, list) and (entry[0] in directories): directories.remove(directory_index) def parse_directory_bound_imports(self, rva, size): """""" bnd_descr = Structure(self.__IMAGE_BOUND_IMPORT_DESCRIPTOR_format__) bnd_descr_size = bnd_descr.sizeof() start = rva bound_imports = [] while True: bnd_descr = self.__unpack_data__( self.__IMAGE_BOUND_IMPORT_DESCRIPTOR_format__, self.__data__[rva:rva+bnd_descr_size], file_offset = rva) if bnd_descr is None: # If can't parse directory then silently return. # This directory does not necesarily have to be valid to # still have a valid PE file self.__warnings.append( 'The Bound Imports directory exists but can\'t be parsed.') return if bnd_descr.all_zeroes(): break rva += bnd_descr.sizeof() forwarder_refs = [] for idx in xrange(bnd_descr.NumberOfModuleForwarderRefs): # Both structures IMAGE_BOUND_IMPORT_DESCRIPTOR and # IMAGE_BOUND_FORWARDER_REF have the same size. bnd_frwd_ref = self.__unpack_data__( self.__IMAGE_BOUND_FORWARDER_REF_format__, self.__data__[rva:rva+bnd_descr_size], file_offset = rva) # OC Patch: if not bnd_frwd_ref: raise PEFormatError( "IMAGE_BOUND_FORWARDER_REF cannot be read") rva += bnd_frwd_ref.sizeof() name_str = self.get_string_from_data( start+bnd_frwd_ref.OffsetModuleName, self.__data__) if not name_str: break forwarder_refs.append(BoundImportRefData( struct = bnd_frwd_ref, name = name_str)) name_str = self.get_string_from_data( start+bnd_descr.OffsetModuleName, self.__data__) if not name_str: break bound_imports.append( BoundImportDescData( struct = bnd_descr, name = name_str, entries = forwarder_refs)) return bound_imports def parse_directory_tls(self, rva, size): """""" if self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE: format = self.__IMAGE_TLS_DIRECTORY_format__ elif self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE_PLUS: format = self.__IMAGE_TLS_DIRECTORY64_format__ try: tls_struct = self.__unpack_data__( format, self.get_data( rva, Structure(format).sizeof() ), file_offset = self.get_offset_from_rva(rva)) except PEFormatError: self.__warnings.append( 'Invalid TLS information. Can\'t read ' + 'data at RVA: 0x%x' % rva) tls_struct = None if not tls_struct: return None return TlsData( struct = tls_struct ) def parse_directory_load_config(self, rva, size): """""" if self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE: format = self.__IMAGE_LOAD_CONFIG_DIRECTORY_format__ elif self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE_PLUS: format = self.__IMAGE_LOAD_CONFIG_DIRECTORY64_format__ try: load_config_struct = self.__unpack_data__( format, self.get_data( rva, Structure(format).sizeof() ), file_offset = self.get_offset_from_rva(rva)) except PEFormatError: self.__warnings.append( 'Invalid LOAD_CONFIG information. Can\'t read ' + 'data at RVA: 0x%x' % rva) load_config_struct = None if not load_config_struct: return None return LoadConfigData( struct = load_config_struct ) def parse_relocations_directory(self, rva, size): """""" rlc_size = Structure(self.__IMAGE_BASE_RELOCATION_format__).sizeof() end = rva+size relocations = [] while rva<end: # OC Patch: # Malware that has bad rva entries will cause an error. # Just continue on after an exception # try: rlc = self.__unpack_data__( self.__IMAGE_BASE_RELOCATION_format__, self.get_data(rva, rlc_size), file_offset = self.get_offset_from_rva(rva) ) except PEFormatError: self.__warnings.append( 'Invalid relocation information. Can\'t read ' + 'data at RVA: 0x%x' % rva) rlc = None if not rlc: break reloc_entries = self.parse_relocations( rva+rlc_size, rlc.VirtualAddress, rlc.SizeOfBlock-rlc_size) relocations.append( BaseRelocationData( struct = rlc, entries = reloc_entries)) if not rlc.SizeOfBlock: break rva += rlc.SizeOfBlock return relocations def parse_relocations(self, data_rva, rva, size): """""" data = self.get_data(data_rva, size) entries = [] for idx in xrange(len(data)/2): word = struct.unpack('<H', data[idx*2:(idx+1)*2])[0] reloc_type = (word>>12) reloc_offset = (word&0x0fff) entries.append( RelocationData( type = reloc_type, rva = reloc_offset+rva)) return entries def parse_debug_directory(self, rva, size): """""" dbg_size = Structure(self.__IMAGE_DEBUG_DIRECTORY_format__).sizeof() debug = [] for idx in xrange(size/dbg_size): try: data = self.get_data(rva+dbg_size*idx, dbg_size) except PEFormatError, e: self.__warnings.append( 'Invalid debug information. Can\'t read ' + 'data at RVA: 0x%x' % rva) return None dbg = self.__unpack_data__( self.__IMAGE_DEBUG_DIRECTORY_format__, data, file_offset = self.get_offset_from_rva(rva+dbg_size*idx)) if not dbg: return None debug.append( DebugData( struct = dbg)) return debug def parse_resources_directory(self, rva, size=0, base_rva = None, level = 0): """Parse the resources directory. Given the rva of the resources directory, it will process all its entries. The root will have the corresponding member of its structure, IMAGE_RESOURCE_DIRECTORY plus 'entries', a list of all the entries in the directory. Those entries will have, correspondingly, all the structure's members (IMAGE_RESOURCE_DIRECTORY_ENTRY) and an additional one, "directory", pointing to the IMAGE_RESOURCE_DIRECTORY structure representing upper layers of the tree. This one will also have an 'entries' attribute, pointing to the 3rd, and last, level. Another directory with more entries. Those last entries will have a new atribute (both 'leaf' or 'data_entry' can be used to access it). This structure finally points to the resource data. All the members of this structure, IMAGE_RESOURCE_DATA_ENTRY, are available as its attributes. """ # OC Patch: original_rva = rva if base_rva is None: base_rva = rva resources_section = self.get_section_by_rva(rva) try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. data = self.get_data(rva, Structure(self.__IMAGE_RESOURCE_DIRECTORY_format__).sizeof() ) except PEFormatError, e: self.__warnings.append( 'Invalid resources directory. Can\'t read ' + 'directory data at RVA: 0x%x' % rva) return None # Get the resource directory structure, that is, the header # of the table preceding the actual entries # resource_dir = self.__unpack_data__( self.__IMAGE_RESOURCE_DIRECTORY_format__, data, file_offset = self.get_offset_from_rva(rva) ) if resource_dir is None: # If can't parse resources directory then silently return. # This directory does not necesarily have to be valid to # still have a valid PE file self.__warnings.append( 'Invalid resources directory. Can\'t parse ' + 'directory data at RVA: 0x%x' % rva) return None dir_entries = [] # Advance the rva to the positon immediately following the directory # table header and pointing to the first entry in the table # rva += resource_dir.sizeof() number_of_entries = ( resource_dir.NumberOfNamedEntries + resource_dir.NumberOfIdEntries ) strings_to_postprocess = list() for idx in xrange(number_of_entries): res = self.parse_resource_entry(rva) if res is None: self.__warnings.append( 'Error parsing the resources directory, ' + 'Entry %d is invalid, RVA = 0x%x. ' % (idx, rva) ) break entry_name = None entry_id = None # If all named entries have been processed, only Id ones # remain if idx >= resource_dir.NumberOfNamedEntries: entry_id = res.Name else: ustr_offset = base_rva+res.NameOffset try: #entry_name = self.get_string_u_at_rva(ustr_offset, max_length=16) entry_name = UnicodeStringWrapperPostProcessor(self, ustr_offset) strings_to_postprocess.append(entry_name) except PEFormatError, excp: self.__warnings.append( 'Error parsing the resources directory, ' + 'attempting to read entry name. ' + 'Can\'t read unicode string at offset 0x%x' % (ustr_offset) ) if res.DataIsDirectory: # OC Patch: # # One trick malware can do is to recursively reference # the next directory. This causes hilarity to ensue when # trying to parse everything correctly. # If the original RVA given to this function is equal to # the next one to parse, we assume that it's a trick. # Instead of raising a PEFormatError this would skip some # reasonable data so we just break. # # 9ee4d0a0caf095314fd7041a3e4404dc is the offending sample if original_rva == (base_rva + res.OffsetToDirectory): break else: entry_directory = self.parse_resources_directory( base_rva+res.OffsetToDirectory, base_rva=base_rva, level = level+1) if not entry_directory: break dir_entries.append( ResourceDirEntryData( struct = res, name = entry_name, id = entry_id, directory = entry_directory)) else: struct = self.parse_resource_data_entry( base_rva + res.OffsetToDirectory) if struct: entry_data = ResourceDataEntryData( struct = struct, lang = res.Name & 0xff, sublang = (res.Name>>8) & 0xff) dir_entries.append( ResourceDirEntryData( struct = res, name = entry_name, id = entry_id, data = entry_data)) else: break # Check if this entry contains version information # if level == 0 and res.Id == RESOURCE_TYPE['RT_VERSION']: if len(dir_entries)>0: last_entry = dir_entries[-1] rt_version_struct = None try: rt_version_struct = last_entry.directory.entries[0].directory.entries[0].data.struct except: # Maybe a malformed directory structure...? # Lets ignore it pass if rt_version_struct is not None: self.parse_version_information(rt_version_struct) rva += res.sizeof() string_rvas = [s.get_rva() for s in strings_to_postprocess] string_rvas.sort() for idx, s in enumerate(strings_to_postprocess): s.render_pascal_16() resource_directory_data = ResourceDirData( struct = resource_dir, entries = dir_entries) return resource_directory_data def parse_resource_data_entry(self, rva): """Parse a data entry from the resources directory.""" try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. data = self.get_data(rva, Structure(self.__IMAGE_RESOURCE_DATA_ENTRY_format__).sizeof() ) except PEFormatError, excp: self.__warnings.append( 'Error parsing a resource directory data entry, ' + 'the RVA is invalid: 0x%x' % ( rva ) ) return None data_entry = self.__unpack_data__( self.__IMAGE_RESOURCE_DATA_ENTRY_format__, data, file_offset = self.get_offset_from_rva(rva) ) return data_entry def parse_resource_entry(self, rva): """Parse a directory entry from the resources directory.""" resource = self.__unpack_data__( self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__, self.get_data( rva, Structure(self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__).sizeof() ), file_offset = self.get_offset_from_rva(rva) ) if resource is None: return None #resource.NameIsString = (resource.Name & 0x80000000L) >> 31 resource.NameOffset = resource.Name & 0x7FFFFFFFL resource.__pad = resource.Name & 0xFFFF0000L resource.Id = resource.Name & 0x0000FFFFL resource.DataIsDirectory = (resource.OffsetToData & 0x80000000L) >> 31 resource.OffsetToDirectory = resource.OffsetToData & 0x7FFFFFFFL return resource def parse_version_information(self, version_struct): """Parse version information structure. The date will be made available in three attributes of the PE object. VS_VERSIONINFO will contain the first three fields of the main structure: 'Length', 'ValueLength', and 'Type' VS_FIXEDFILEINFO will hold the rest of the fields, accessible as sub-attributes: 'Signature', 'StrucVersion', 'FileVersionMS', 'FileVersionLS', 'ProductVersionMS', 'ProductVersionLS', 'FileFlagsMask', 'FileFlags', 'FileOS', 'FileType', 'FileSubtype', 'FileDateMS', 'FileDateLS' FileInfo is a list of all StringFileInfo and VarFileInfo structures. StringFileInfo structures will have a list as an attribute named 'StringTable' containing all the StringTable structures. Each of those structures contains a dictionary 'entries' with all the key/value version information string pairs. VarFileInfo structures will have a list as an attribute named 'Var' containing all Var structures. Each Var structure will have a dictionary as an attribute named 'entry' which will contain the name and value of the Var. """ # Retrieve the data for the version info resource # start_offset = self.get_offset_from_rva( version_struct.OffsetToData ) raw_data = self.__data__[ start_offset : start_offset+version_struct.Size ] # Map the main structure and the subsequent string # versioninfo_struct = self.__unpack_data__( self.__VS_VERSIONINFO_format__, raw_data, file_offset = start_offset ) if versioninfo_struct is None: return ustr_offset = version_struct.OffsetToData + versioninfo_struct.sizeof() try: versioninfo_string = self.get_string_u_at_rva( ustr_offset ) except PEFormatError, excp: self.__warnings.append( 'Error parsing the version information, ' + 'attempting to read VS_VERSION_INFO string. Can\'t ' + 'read unicode string at offset 0x%x' % ( ustr_offset ) ) versioninfo_string = None # If the structure does not contain the expected name, it's assumed to be invalid # if versioninfo_string != u'VS_VERSION_INFO': self.__warnings.append('Invalid VS_VERSION_INFO block') return # Set the PE object's VS_VERSIONINFO to this one # self.VS_VERSIONINFO = versioninfo_struct # The the Key attribute to point to the unicode string identifying the structure # self.VS_VERSIONINFO.Key = versioninfo_string # Process the fixed version information, get the offset and structure # fixedfileinfo_offset = self.dword_align( versioninfo_struct.sizeof() + 2 * (len(versioninfo_string) + 1), version_struct.OffsetToData) fixedfileinfo_struct = self.__unpack_data__( self.__VS_FIXEDFILEINFO_format__, raw_data[fixedfileinfo_offset:], file_offset = start_offset+fixedfileinfo_offset ) if not fixedfileinfo_struct: return # Set the PE object's VS_FIXEDFILEINFO to this one # self.VS_FIXEDFILEINFO = fixedfileinfo_struct # Start parsing all the StringFileInfo and VarFileInfo structures # # Get the first one # stringfileinfo_offset = self.dword_align( fixedfileinfo_offset + fixedfileinfo_struct.sizeof(), version_struct.OffsetToData) original_stringfileinfo_offset = stringfileinfo_offset # Set the PE object's attribute that will contain them all. # self.FileInfo = list() while True: # Process the StringFileInfo/VarFileInfo struct # stringfileinfo_struct = self.__unpack_data__( self.__StringFileInfo_format__, raw_data[stringfileinfo_offset:], file_offset = start_offset+stringfileinfo_offset ) if stringfileinfo_struct is None: self.__warnings.append( 'Error parsing StringFileInfo/VarFileInfo struct' ) return None # Get the subsequent string defining the structure. # ustr_offset = ( version_struct.OffsetToData + stringfileinfo_offset + versioninfo_struct.sizeof() ) try: stringfileinfo_string = self.get_string_u_at_rva( ustr_offset ) except PEFormatError, excp: self.__warnings.append( 'Error parsing the version information, ' + 'attempting to read StringFileInfo string. Can\'t ' + 'read unicode string at offset 0x%x' % ( ustr_offset ) ) break # Set such string as the Key attribute # stringfileinfo_struct.Key = stringfileinfo_string # Append the structure to the PE object's list # self.FileInfo.append(stringfileinfo_struct) # Parse a StringFileInfo entry # if stringfileinfo_string.startswith(u'StringFileInfo'): if stringfileinfo_struct.Type == 1 and stringfileinfo_struct.ValueLength == 0: stringtable_offset = self.dword_align( stringfileinfo_offset + stringfileinfo_struct.sizeof() + 2*(len(stringfileinfo_string)+1), version_struct.OffsetToData) stringfileinfo_struct.StringTable = list() # Process the String Table entries # while True: stringtable_struct = self.__unpack_data__( self.__StringTable_format__, raw_data[stringtable_offset:], file_offset = start_offset+stringtable_offset ) if not stringtable_struct: break ustr_offset = ( version_struct.OffsetToData + stringtable_offset + stringtable_struct.sizeof() ) try: stringtable_string = self.get_string_u_at_rva( ustr_offset ) except PEFormatError, excp: self.__warnings.append( 'Error parsing the version information, ' + 'attempting to read StringTable string. Can\'t ' + 'read unicode string at offset 0x%x' % ( ustr_offset ) ) break stringtable_struct.LangID = stringtable_string stringtable_struct.entries = dict() stringtable_struct.entries_offsets = dict() stringtable_struct.entries_lengths = dict() stringfileinfo_struct.StringTable.append(stringtable_struct) entry_offset = self.dword_align( stringtable_offset + stringtable_struct.sizeof() + 2*(len(stringtable_string)+1), version_struct.OffsetToData) # Process all entries in the string table # while entry_offset < stringtable_offset + stringtable_struct.Length: string_struct = self.__unpack_data__( self.__String_format__, raw_data[entry_offset:], file_offset = start_offset+entry_offset ) if not string_struct: break ustr_offset = ( version_struct.OffsetToData + entry_offset + string_struct.sizeof() ) try: key = self.get_string_u_at_rva( ustr_offset ) key_offset = self.get_offset_from_rva( ustr_offset ) except PEFormatError, excp: self.__warnings.append( 'Error parsing the version information, ' + 'attempting to read StringTable Key string. Can\'t ' + 'read unicode string at offset 0x%x' % ( ustr_offset ) ) break value_offset = self.dword_align( 2*(len(key)+1) + entry_offset + string_struct.sizeof(), version_struct.OffsetToData) ustr_offset = version_struct.OffsetToData + value_offset try: value = self.get_string_u_at_rva( ustr_offset, max_length = string_struct.ValueLength ) value_offset = self.get_offset_from_rva( ustr_offset ) except PEFormatError, excp: self.__warnings.append( 'Error parsing the version information, ' + 'attempting to read StringTable Value string. ' + 'Can\'t read unicode string at offset 0x%x' % ( ustr_offset ) ) break if string_struct.Length == 0: entry_offset = stringtable_offset + stringtable_struct.Length else: entry_offset = self.dword_align( string_struct.Length+entry_offset, version_struct.OffsetToData) key_as_char = [] for c in key: if ord(c)>128: key_as_char.append('\\x%02x' %ord(c)) else: key_as_char.append(c) key_as_char = ''.join(key_as_char) setattr(stringtable_struct, key_as_char, value) stringtable_struct.entries[key] = value stringtable_struct.entries_offsets[key] = (key_offset, value_offset) stringtable_struct.entries_lengths[key] = (len(key), len(value)) new_stringtable_offset = self.dword_align( stringtable_struct.Length + stringtable_offset, version_struct.OffsetToData) # check if the entry is crafted in a way that would lead to an infinite # loop and break if so # if new_stringtable_offset == stringtable_offset: break stringtable_offset = new_stringtable_offset if stringtable_offset >= stringfileinfo_struct.Length: break # Parse a VarFileInfo entry # elif stringfileinfo_string.startswith( u'VarFileInfo' ): varfileinfo_struct = stringfileinfo_struct varfileinfo_struct.name = 'VarFileInfo' if varfileinfo_struct.Type == 1 and varfileinfo_struct.ValueLength == 0: var_offset = self.dword_align( stringfileinfo_offset + varfileinfo_struct.sizeof() + 2*(len(stringfileinfo_string)+1), version_struct.OffsetToData) varfileinfo_struct.Var = list() # Process all entries # while True: var_struct = self.__unpack_data__( self.__Var_format__, raw_data[var_offset:], file_offset = start_offset+var_offset ) if not var_struct: break ustr_offset = ( version_struct.OffsetToData + var_offset + var_struct.sizeof() ) try: var_string = self.get_string_u_at_rva( ustr_offset ) except PEFormatError, excp: self.__warnings.append( 'Error parsing the version information, ' + 'attempting to read VarFileInfo Var string. ' + 'Can\'t read unicode string at offset 0x%x' % (ustr_offset)) break varfileinfo_struct.Var.append(var_struct) varword_offset = self.dword_align( 2*(len(var_string)+1) + var_offset + var_struct.sizeof(), version_struct.OffsetToData) orig_varword_offset = varword_offset while varword_offset < orig_varword_offset + var_struct.ValueLength: word1 = self.get_word_from_data( raw_data[varword_offset:varword_offset+2], 0) word2 = self.get_word_from_data( raw_data[varword_offset+2:varword_offset+4], 0) varword_offset += 4 if isinstance(word1, (int, long)) and isinstance(word1, (int, long)): var_struct.entry = {var_string: '0x%04x 0x%04x' % (word1, word2)} var_offset = self.dword_align( var_offset+var_struct.Length, version_struct.OffsetToData) if var_offset <= var_offset+var_struct.Length: break # Increment and align the offset # stringfileinfo_offset = self.dword_align( stringfileinfo_struct.Length+stringfileinfo_offset, version_struct.OffsetToData) # Check if all the StringFileInfo and VarFileInfo items have been processed # if stringfileinfo_struct.Length == 0 or stringfileinfo_offset >= versioninfo_struct.Length: break def parse_export_directory(self, rva, size): """Parse the export directory. Given the rva of the export directory, it will process all its entries. The exports will be made available through a list "exports" containing a tuple with the following elements: (ordinal, symbol_address, symbol_name) And also through a dicionary "exports_by_ordinal" whose keys will be the ordinals and the values tuples of the from: (symbol_address, symbol_name) The symbol addresses are relative, not absolute. """ try: export_dir = self.__unpack_data__( self.__IMAGE_EXPORT_DIRECTORY_format__, self.get_data( rva, Structure(self.__IMAGE_EXPORT_DIRECTORY_format__).sizeof() ), file_offset = self.get_offset_from_rva(rva) ) except PEFormatError: self.__warnings.append( 'Error parsing export directory at RVA: 0x%x' % ( rva ) ) return if not export_dir: return try: address_of_names = self.get_data( export_dir.AddressOfNames, export_dir.NumberOfNames*4) address_of_name_ordinals = self.get_data( export_dir.AddressOfNameOrdinals, export_dir.NumberOfNames*4) address_of_functions = self.get_data( export_dir.AddressOfFunctions, export_dir.NumberOfFunctions*4) except PEFormatError: self.__warnings.append( 'Error parsing export directory at RVA: 0x%x' % ( rva ) ) return exports = [] for i in xrange(export_dir.NumberOfNames): symbol_name = self.get_string_at_rva( self.get_dword_from_data(address_of_names, i)) symbol_ordinal = self.get_word_from_data( address_of_name_ordinals, i) if symbol_ordinal*4<len(address_of_functions): symbol_address = self.get_dword_from_data( address_of_functions, symbol_ordinal) else: # Corrupt? a bad pointer... we assume it's all # useless, no exports return None # If the funcion's rva points within the export directory # it will point to a string with the forwarded symbol's string # instead of pointing the the function start address. if symbol_address>=rva and symbol_address<rva+size: forwarder_str = self.get_string_at_rva(symbol_address) else: forwarder_str = None exports.append( ExportData( ordinal = export_dir.Base+symbol_ordinal, address = symbol_address, name = symbol_name, forwarder = forwarder_str)) ordinals = [exp.ordinal for exp in exports] for idx in xrange(export_dir.NumberOfFunctions): if not idx+export_dir.Base in ordinals: symbol_address = self.get_dword_from_data( address_of_functions, idx) # # Checking for forwarder again. # if symbol_address>=rva and symbol_address<rva+size: forwarder_str = self.get_string_at_rva(symbol_address) else: forwarder_str = None exports.append( ExportData( ordinal = export_dir.Base+idx, address = symbol_address, name = None, forwarder = forwarder_str)) return ExportDirData( struct = export_dir, symbols = exports) def dword_align(self, offset, base): offset += base return (offset+3) - ((offset+3)%4) - base def parse_delay_import_directory(self, rva, size): """Walk and parse the delay import directory.""" import_descs = [] while True: try: # If the RVA is invalid all would blow up. Some PEs seem to be # specially nasty and have an invalid RVA. data = self.get_data( rva, Structure(self.__IMAGE_DELAY_IMPORT_DESCRIPTOR_format__).sizeof() ) except PEFormatError, e: self.__warnings.append( 'Error parsing the Delay import directory at RVA: 0x%x' % ( rva ) ) break import_desc = self.__unpack_data__( self.__IMAGE_DELAY_IMPORT_DESCRIPTOR_format__, data, file_offset = self.get_offset_from_rva(rva) ) # If the structure is all zeores, we reached the end of the list if not import_desc or import_desc.all_zeroes(): break rva += import_desc.sizeof() try: import_data = self.parse_imports( import_desc.pINT, import_desc.pIAT, None) except PEFormatError, e: self.__warnings.append( 'Error parsing the Delay import directory. ' + 'Invalid import data at RVA: 0x%x' % ( rva ) ) break if not import_data: continue dll = self.get_string_at_rva(import_desc.szName) if dll: import_descs.append( ImportDescData( struct = import_desc, imports = import_data, dll = dll)) return import_descs def parse_import_directory(self, rva, size): """Walk and parse the import directory.""" import_descs = [] while True: try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. data = self.get_data(rva, Structure(self.__IMAGE_IMPORT_DESCRIPTOR_format__).sizeof() ) except PEFormatError, e: self.__warnings.append( 'Error parsing the Import directory at RVA: 0x%x' % ( rva ) ) break import_desc = self.__unpack_data__( self.__IMAGE_IMPORT_DESCRIPTOR_format__, data, file_offset = self.get_offset_from_rva(rva) ) # If the structure is all zeores, we reached the end of the list if not import_desc or import_desc.all_zeroes(): break rva += import_desc.sizeof() try: import_data = self.parse_imports( import_desc.OriginalFirstThunk, import_desc.FirstThunk, import_desc.ForwarderChain) except PEFormatError, excp: self.__warnings.append( 'Error parsing the Import directory. ' + 'Invalid Import data at RVA: 0x%x' % ( rva ) ) break #raise excp if not import_data: continue dll = self.get_string_at_rva(import_desc.Name) if dll: import_descs.append( ImportDescData( struct = import_desc, imports = import_data, dll = dll)) return import_descs def parse_imports(self, original_first_thunk, first_thunk, forwarder_chain): """Parse the imported symbols. It will fill a list, which will be avalable as the dictionary attribute "imports". Its keys will be the DLL names and the values all the symbols imported from that object. """ imported_symbols = [] imports_section = self.get_section_by_rva(first_thunk) if not imports_section: raise PEFormatError, 'Invalid/corrupt imports.' # Import Lookup Table. Contains ordinals or pointers to strings. ilt = self.get_import_table(original_first_thunk) # Import Address Table. May have identical content to ILT if # PE file is not bounded, Will contain the address of the # imported symbols once the binary is loaded or if it is already # bound. iat = self.get_import_table(first_thunk) # OC Patch: # Would crash if iat or ilt had None type if not iat and not ilt: raise PEFormatError( 'Invalid Import Table information. ' + 'Both ILT and IAT appear to be broken.') table = None if ilt: table = ilt elif iat: table = iat else: return None for idx in xrange(len(table)): imp_ord = None imp_hint = None imp_name = None hint_name_table_rva = None if table[idx].AddressOfData: if self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE: ordinal_flag = IMAGE_ORDINAL_FLAG elif self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE_PLUS: ordinal_flag = IMAGE_ORDINAL_FLAG64 # If imported by ordinal, we will append the ordinal number # if table[idx].AddressOfData & ordinal_flag: import_by_ordinal = True imp_ord = table[idx].AddressOfData & 0xffff imp_name = None else: import_by_ordinal = False try: hint_name_table_rva = table[idx].AddressOfData & 0x7fffffff data = self.get_data(hint_name_table_rva, 2) # Get the Hint imp_hint = self.get_word_from_data(data, 0) imp_name = self.get_string_at_rva(table[idx].AddressOfData+2) except PEFormatError, e: pass imp_address = first_thunk+self.OPTIONAL_HEADER.ImageBase+idx*4 try: if iat and ilt and ilt[idx].AddressOfData != iat[idx].AddressOfData: imp_bound = iat[idx].AddressOfData else: imp_bound = None except IndexError: imp_bound = None if imp_name != '' and (imp_ord or imp_name): imported_symbols.append( ImportData( import_by_ordinal = import_by_ordinal, ordinal = imp_ord, hint = imp_hint, name = imp_name, bound = imp_bound, address = imp_address, hint_name_table_rva = hint_name_table_rva)) return imported_symbols def get_import_table(self, rva): table = [] while True and rva: if self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE: format = self.__IMAGE_THUNK_DATA_format__ elif self.PE_TYPE == OPTIONAL_HEADER_MAGIC_PE_PLUS: format = self.__IMAGE_THUNK_DATA64_format__ try: data = self.get_data( rva, Structure(format).sizeof() ) except PEFormatError, e: self.__warnings.append( 'Error parsing the import table. ' + 'Invalid data at RVA: 0x%x' % ( rva ) ) return None thunk_data = self.__unpack_data__( format, data, file_offset=self.get_offset_from_rva(rva) ) if not thunk_data or thunk_data.all_zeroes(): break rva += thunk_data.sizeof() table.append(thunk_data) return table def get_memory_mapped_image(self, max_virtual_address=0x10000000, ImageBase=None): """Returns the data corresponding to the memory layout of the PE file. The data includes the PE header and the sections loaded at offsets corresponding to their relative virtual addresses. (the VirtualAddress section header member). Any offset in this data corresponds to the absolute memory address ImageBase+offset. The optional argument 'max_virtual_address' provides with means of limiting which section are processed. Any section with their VirtualAddress beyond this value will be skipped. Normally, sections with values beyond this range are just there to confuse tools. It's a common trick to see in packed executables. If the 'ImageBase' optional argument is supplied, the file's relocations will be applied to the image by calling the 'relocate_image()' method. Beware that the relocation information is applied permanently. """ # Rebase if requested # if ImageBase is not None: # Keep a copy of the image's data before modifying it by rebasing it # original_data = self.__data__ self.relocate_image(ImageBase) # Collect all sections in one code block mapped_data = self.header for section in self.sections: # Miscellanous integrity tests. # Some packer will set these to bogus values to # make tools go nuts. # if section.Misc_VirtualSize == 0 or section.SizeOfRawData == 0: continue if section.SizeOfRawData > len(self.__data__): continue if section.PointerToRawData > len(self.__data__): continue if section.VirtualAddress >= max_virtual_address: continue padding_length = section.VirtualAddress - len(mapped_data) if padding_length>0: mapped_data += '\0'*padding_length elif padding_length<0: mapped_data = mapped_data[:padding_length] mapped_data += section.data # If the image was rebased, restore it to its original form # if ImageBase is not None: self.__data__ = original_data self.update_all_section_data() return mapped_data def get_data(self, rva, length=None): """Get data regardless of the section where it lies on. Given a rva and the size of the chunk to retrieve, this method will find the section where the data lies and return the data. """ s = self.get_section_by_rva(rva) if not s: if rva<len(self.header): if length: end = rva+length else: end = None return self.header[rva:end] raise PEFormatError, 'data at RVA can\'t be fetched. Corrupt header?' return s.get_data(rva, length) def get_rva_from_offset(self, offset): """Get the rva corresponding to this file offset. """ s = self.get_section_by_offset(offset) if not s: raise PEFormatError("specified offset (0x%x) doesn't belong to any section." % offset) return s.get_rva_from_offset(offset) def get_offset_from_rva(self, rva): """Get the file offset corresponding to this rva. Given a rva , this method will find the section where the data lies and return the offset within the file. """ s = self.get_section_by_rva(rva) if not s: raise PEFormatError, 'data at RVA can\'t be fetched. Corrupt header?' return s.get_offset_from_rva(rva) def get_string_at_rva(self, rva): """Get an ASCII string located at the given address.""" s = self.get_section_by_rva(rva) if not s: if rva<len(self.header): return self.get_string_from_data(rva, self.header) return None return self.get_string_from_data(rva-s.VirtualAddress, s.data) def get_string_from_data(self, offset, data): """Get an ASCII string from within the data.""" # OC Patch b = None try: b = data[offset] except IndexError: return '' s = '' while ord(b): s += b offset += 1 try: b = data[offset] except IndexError: break return s def get_string_u_at_rva(self, rva, max_length = 2**16): """Get an Unicode string located at the given address.""" try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. data = self.get_data(rva, 2) except PEFormatError, e: return None #length = struct.unpack('<H', data)[0] s = u'' for idx in xrange(max_length): try: uchr = struct.unpack('<H', self.get_data(rva+2*idx, 2))[0] except struct.error: break if unichr(uchr) == u'\0': break s += unichr(uchr) return s def get_section_by_offset(self, offset): """Get the section containing the given file offset.""" sections = [s for s in self.sections if s.contains_offset(offset)] if sections: return sections[0] return None def get_section_by_rva(self, rva): """Get the section containing the given address.""" sections = [s for s in self.sections if s.contains_rva(rva)] if sections: return sections[0] return None def __str__(self): return self.dump_info() def print_info(self): """Print all the PE header information in a human readable from.""" print self.dump_info() def dump_info(self, dump=None): """Dump all the PE header information into human readable string.""" if dump is None: dump = Dump() warnings = self.get_warnings() if warnings: dump.add_header('Parsing Warnings') for warning in warnings: dump.add_line(warning) dump.add_newline() dump.add_header('DOS_HEADER') dump.add_lines(self.DOS_HEADER.dump()) dump.add_newline() dump.add_header('NT_HEADERS') dump.add_lines(self.NT_HEADERS.dump()) dump.add_newline() dump.add_header('FILE_HEADER') dump.add_lines(self.FILE_HEADER.dump()) image_flags = self.retrieve_flags(IMAGE_CHARACTERISTICS, 'IMAGE_FILE_') dump.add('Flags: ') flags = [] for flag in image_flags: if getattr(self.FILE_HEADER, flag[0]): flags.append(flag[0]) dump.add_line(', '.join(flags)) dump.add_newline() if hasattr(self, 'OPTIONAL_HEADER') and self.OPTIONAL_HEADER is not None: dump.add_header('OPTIONAL_HEADER') dump.add_lines(self.OPTIONAL_HEADER.dump()) dll_characteristics_flags = self.retrieve_flags(DLL_CHARACTERISTICS, 'IMAGE_DLL_CHARACTERISTICS_') dump.add('DllCharacteristics: ') flags = [] for flag in dll_characteristics_flags: if getattr(self.OPTIONAL_HEADER, flag[0]): flags.append(flag[0]) dump.add_line(', '.join(flags)) dump.add_newline() dump.add_header('PE Sections') section_flags = self.retrieve_flags(SECTION_CHARACTERISTICS, 'IMAGE_SCN_') for section in self.sections: dump.add_lines(section.dump()) dump.add('Flags: ') flags = [] for flag in section_flags: if getattr(section, flag[0]): flags.append(flag[0]) dump.add_line(', '.join(flags)) dump.add_line('Entropy: %f (Min=0.0, Max=8.0)' % section.get_entropy() ) if md5 is not None: dump.add_line('MD5 hash: %s' % section.get_hash_md5() ) if sha1 is not None: dump.add_line('SHA-1 hash: %s' % section.get_hash_sha1() ) if sha256 is not None: dump.add_line('SHA-256 hash: %s' % section.get_hash_sha256() ) if sha512 is not None: dump.add_line('SHA-512 hash: %s' % section.get_hash_sha512() ) dump.add_newline() if (hasattr(self, 'OPTIONAL_HEADER') and hasattr(self.OPTIONAL_HEADER, 'DATA_DIRECTORY') ): dump.add_header('Directories') for idx in xrange(len(self.OPTIONAL_HEADER.DATA_DIRECTORY)): directory = self.OPTIONAL_HEADER.DATA_DIRECTORY[idx] dump.add_lines(directory.dump()) dump.add_newline() def convert_char(char): if char in string.ascii_letters or char in string.digits or char in string.punctuation or char in string.whitespace: return char else: return r'\x%02x' % ord(char) def convert_to_printable(s): return ''.join([convert_char(c) for c in s]) if hasattr(self, 'VS_VERSIONINFO'): dump.add_header('Version Information') dump.add_lines(self.VS_VERSIONINFO.dump()) dump.add_newline() if hasattr(self, 'VS_FIXEDFILEINFO'): dump.add_lines(self.VS_FIXEDFILEINFO.dump()) dump.add_newline() if hasattr(self, 'FileInfo'): for entry in self.FileInfo: dump.add_lines(entry.dump()) dump.add_newline() if hasattr(entry, 'StringTable'): for st_entry in entry.StringTable: [dump.add_line(' '+line) for line in st_entry.dump()] dump.add_line(' LangID: '+st_entry.LangID) dump.add_newline() for str_entry in st_entry.entries.items(): dump.add_line( ' ' + convert_to_printable(str_entry[0]) + ': ' + convert_to_printable(str_entry[1]) ) dump.add_newline() elif hasattr(entry, 'Var'): for var_entry in entry.Var: if hasattr(var_entry, 'entry'): [dump.add_line(' '+line) for line in var_entry.dump()] dump.add_line( ' ' + convert_to_printable(var_entry.entry.keys()[0]) + ': ' + var_entry.entry.values()[0]) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_EXPORT'): dump.add_header('Exported symbols') dump.add_lines(self.DIRECTORY_ENTRY_EXPORT.struct.dump()) dump.add_newline() dump.add_line('%-10s %-10s %s' % ('Ordinal', 'RVA', 'Name')) for export in self.DIRECTORY_ENTRY_EXPORT.symbols: dump.add('%-10d 0x%08Xh %s' % ( export.ordinal, export.address, export.name)) if export.forwarder: dump.add_line(' forwarder: %s' % export.forwarder) else: dump.add_newline() dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_IMPORT'): dump.add_header('Imported symbols') for module in self.DIRECTORY_ENTRY_IMPORT: dump.add_lines(module.struct.dump()) dump.add_newline() for symbol in module.imports: if symbol.import_by_ordinal is True: dump.add('%s Ordinal[%s] (Imported by Ordinal)' % ( module.dll, str(symbol.ordinal))) else: dump.add('%s.%s Hint[%s]' % ( module.dll, symbol.name, str(symbol.hint))) if symbol.bound: dump.add_line(' Bound: 0x%08X' % (symbol.bound)) else: dump.add_newline() dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_BOUND_IMPORT'): dump.add_header('Bound imports') for bound_imp_desc in self.DIRECTORY_ENTRY_BOUND_IMPORT: dump.add_lines(bound_imp_desc.struct.dump()) dump.add_line('DLL: %s' % bound_imp_desc.name) dump.add_newline() for bound_imp_ref in bound_imp_desc.entries: dump.add_lines(bound_imp_ref.struct.dump(), 4) dump.add_line('DLL: %s' % bound_imp_ref.name, 4) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_DELAY_IMPORT'): dump.add_header('Delay Imported symbols') for module in self.DIRECTORY_ENTRY_DELAY_IMPORT: dump.add_lines(module.struct.dump()) dump.add_newline() for symbol in module.imports: if symbol.import_by_ordinal is True: dump.add('%s Ordinal[%s] (Imported by Ordinal)' % ( module.dll, str(symbol.ordinal))) else: dump.add('%s.%s Hint[%s]' % ( module.dll, symbol.name, str(symbol.hint))) if symbol.bound: dump.add_line(' Bound: 0x%08X' % (symbol.bound)) else: dump.add_newline() dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_RESOURCE'): dump.add_header('Resource directory') dump.add_lines(self.DIRECTORY_ENTRY_RESOURCE.struct.dump()) for resource_type in self.DIRECTORY_ENTRY_RESOURCE.entries: if resource_type.name is not None: dump.add_line('Name: [%s]' % resource_type.name, 2) else: dump.add_line('Id: [0x%X] (%s)' % ( resource_type.struct.Id, RESOURCE_TYPE.get( resource_type.struct.Id, '-')), 2) dump.add_lines(resource_type.struct.dump(), 2) if hasattr(resource_type, 'directory'): dump.add_lines(resource_type.directory.struct.dump(), 4) for resource_id in resource_type.directory.entries: if resource_id.name is not None: dump.add_line('Name: [%s]' % resource_id.name, 6) else: dump.add_line('Id: [0x%X]' % resource_id.struct.Id, 6) dump.add_lines(resource_id.struct.dump(), 6) if hasattr(resource_id, 'directory'): dump.add_lines(resource_id.directory.struct.dump(), 8) for resource_lang in resource_id.directory.entries: # dump.add_line('\\--- LANG [%d,%d][%s]' % ( # resource_lang.data.lang, # resource_lang.data.sublang, # LANG[resource_lang.data.lang]), 8) dump.add_lines(resource_lang.struct.dump(), 10) dump.add_lines(resource_lang.data.struct.dump(), 12) dump.add_newline() dump.add_newline() if ( hasattr(self, 'DIRECTORY_ENTRY_TLS') and self.DIRECTORY_ENTRY_TLS and self.DIRECTORY_ENTRY_TLS.struct ): dump.add_header('TLS') dump.add_lines(self.DIRECTORY_ENTRY_TLS.struct.dump()) dump.add_newline() if ( hasattr(self, 'DIRECTORY_ENTRY_LOAD_CONFIG') and self.DIRECTORY_ENTRY_LOAD_CONFIG and self.DIRECTORY_ENTRY_LOAD_CONFIG.struct ): dump.add_header('LOAD_CONFIG') dump.add_lines(self.DIRECTORY_ENTRY_LOAD_CONFIG.struct.dump()) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_DEBUG'): dump.add_header('Debug information') for dbg in self.DIRECTORY_ENTRY_DEBUG: dump.add_lines(dbg.struct.dump()) try: dump.add_line('Type: '+DEBUG_TYPE[dbg.struct.Type]) except KeyError: dump.add_line('Type: 0x%x(Unknown)' % dbg.struct.Type) dump.add_newline() if hasattr(self, 'DIRECTORY_ENTRY_BASERELOC'): dump.add_header('Base relocations') for base_reloc in self.DIRECTORY_ENTRY_BASERELOC: dump.add_lines(base_reloc.struct.dump()) for reloc in base_reloc.entries: try: dump.add_line('%08Xh %s' % ( reloc.rva, RELOCATION_TYPE[reloc.type][16:]), 4) except KeyError: dump.add_line('0x%08X 0x%x(Unknown)' % ( reloc.rva, reloc.type), 4) dump.add_newline() return dump.get_text() # OC Patch def get_physical_by_rva(self, rva): """Gets the physical address in the PE file from an RVA value.""" try: return self.get_offset_from_rva(rva) except Exception: return None ## # Double-Word get/set ## def get_data_from_dword(self, dword): """Return a four byte string representing the double word value. (little endian).""" return struct.pack('<L', dword & 0xffffffff) def get_dword_from_data(self, data, offset): """Convert four bytes of data to a double word (little endian) 'offset' is assumed to index into a dword array. So setting it to N will return a dword out of the data sarting at offset N*4. Returns None if the data can't be turned into a double word. """ if (offset+1)*4 > len(data): return None return struct.unpack('<I', data[offset*4:(offset+1)*4])[0] def get_dword_at_rva(self, rva): """Return the double word value at the given RVA. Returns None if the value can't be read, i.e. the RVA can't be mapped to a file offset. """ try: return self.get_dword_from_data(self.get_data(rva)[:4], 0) except PEFormatError: return None def get_dword_from_offset(self, offset): """Return the double word value at the given file offset. (little endian)""" if offset+4 > len(self.__data__): return None return self.get_dword_from_data(self.__data__[offset:offset+4], 0) def set_dword_at_rva(self, rva, dword): """Set the double word value at the file offset corresponding to the given RVA.""" return self.set_bytes_at_rva(rva, self.get_data_from_dword(dword)) def set_dword_at_offset(self, offset, dword): """Set the double word value at the given file offset.""" return self.set_bytes_at_offset(offset, self.get_data_from_dword(dword)) ## # Word get/set ## def get_data_from_word(self, word): """Return a two byte string representing the word value. (little endian).""" return struct.pack('<H', word) def get_word_from_data(self, data, offset): """Convert two bytes of data to a word (little endian) 'offset' is assumed to index into a word array. So setting it to N will return a dword out of the data sarting at offset N*2. Returns None if the data can't be turned into a word. """ if (offset+1)*2 > len(data): return None return struct.unpack('<H', data[offset*2:(offset+1)*2])[0] def get_word_at_rva(self, rva): """Return the word value at the given RVA. Returns None if the value can't be read, i.e. the RVA can't be mapped to a file offset. """ try: return self.get_word_from_data(self.get_data(rva)[:2], 0) except PEFormatError: return None def get_word_from_offset(self, offset): """Return the word value at the given file offset. (little endian)""" if offset+2 > len(self.__data__): return None return self.get_word_from_data(self.__data__[offset:offset+2], 0) def set_word_at_rva(self, rva, word): """Set the word value at the file offset corresponding to the given RVA.""" return self.set_bytes_at_rva(rva, self.get_data_from_word(word)) def set_word_at_offset(self, offset, word): """Set the word value at the given file offset.""" return self.set_bytes_at_offset(offset, self.get_data_from_word(word)) ## # Quad-Word get/set ## def get_data_from_qword(self, word): """Return a eight byte string representing the quad-word value. (little endian).""" return struct.pack('<Q', word) def get_qword_from_data(self, data, offset): """Convert eight bytes of data to a word (little endian) 'offset' is assumed to index into a word array. So setting it to N will return a dword out of the data sarting at offset N*8. Returns None if the data can't be turned into a quad word. """ if (offset+1)*8 > len(data): return None return struct.unpack('<Q', data[offset*8:(offset+1)*8])[0] def get_qword_at_rva(self, rva): """Return the quad-word value at the given RVA. Returns None if the value can't be read, i.e. the RVA can't be mapped to a file offset. """ try: return self.get_qword_from_data(self.get_data(rva)[:8], 0) except PEFormatError: return None def get_qword_from_offset(self, offset): """Return the quad-word value at the given file offset. (little endian)""" if offset+8 > len(self.__data__): return None return self.get_qword_from_data(self.__data__[offset:offset+8], 0) def set_qword_at_rva(self, rva, qword): """Set the quad-word value at the file offset corresponding to the given RVA.""" return self.set_bytes_at_rva(rva, self.get_data_from_qword(qword)) def set_qword_at_offset(self, offset, qword): """Set the quad-word value at the given file offset.""" return self.set_bytes_at_offset(offset, self.get_data_from_qword(qword)) ## # Set bytes ## def set_bytes_at_rva(self, rva, data): """Overwrite, with the given string, the bytes at the file offset corresponding to the given RVA. Return True if successful, False otherwise. It can fail if the offset is outside the file's boundaries. """ offset = self.get_physical_by_rva(rva) if not offset: raise False return self.set_bytes_at_offset(offset, data) def set_bytes_at_offset(self, offset, data): """Overwrite the bytes at the given file offset with the given string. Return True if successful, False otherwise. It can fail if the offset is outside the file's boundaries. """ if not isinstance(data, str): raise TypeError('data should be of type: str') if offset >= 0 and offset < len(self.__data__): self.__data__ = ( self.__data__[:offset] + data + self.__data__[offset+len(data):] ) else: return False self.update_all_section_data() return True def update_all_section_data(self): """Refresh the data of all section in the file. Will call update_section_data() for each section in the file. """ for section in self.sections: self.update_section_data(section) def update_section_data(self, section): """Update the section data with any data updated in the file. If the file's data is modified, the section's data can be refreshed by invoking this method. """ # Refresh the section's data with the modified information # section_data_start = section.PointerToRawData section_data_end = section_data_start+section.SizeOfRawData section.set_data(self.__data__[section_data_start:section_data_end]) def relocate_image(self, new_ImageBase): """Apply the relocation information to the image using the provided new image base. This method will apply the relocation information to the image. Given the new base, all the relocations will be processed and both the raw data and the section's data will be fixed accordingly. The resulting image can be retrieved as well through the method: get_memory_mapped_image() In order to get something that would more closely match what could be found in memory once the Windows loader finished its work. """ relocation_difference = new_ImageBase - self.OPTIONAL_HEADER.ImageBase for reloc in self.DIRECTORY_ENTRY_BASERELOC: virtual_address = reloc.struct.VirtualAddress size_of_block = reloc.struct.SizeOfBlock # We iterate with an index because if the relocation is of type # IMAGE_REL_BASED_HIGHADJ we need to also process the next entry # at once and skip it for the next interation # entry_idx = 0 while entry_idx<len(reloc.entries): entry = reloc.entries[entry_idx] entry_idx += 1 if entry.type == RELOCATION_TYPE['IMAGE_REL_BASED_ABSOLUTE']: # Nothing to do for this type of relocation pass elif entry.type == RELOCATION_TYPE['IMAGE_REL_BASED_HIGH']: # Fix the high 16bits of a relocation # # Add high 16bits of relocation_difference to the # 16bit value at RVA=entry.rva self.set_word_at_rva( entry.rva, ( self.get_word_at_rva(entry.rva) + relocation_difference>>16)&0xffff ) elif entry.type == RELOCATION_TYPE['IMAGE_REL_BASED_LOW']: # Fix the low 16bits of a relocation # # Add low 16 bits of relocation_difference to the 16bit value # at RVA=entry.rva self.set_word_at_rva( entry.rva, ( self.get_word_at_rva(entry.rva) + relocation_difference)&0xffff) elif entry.type == RELOCATION_TYPE['IMAGE_REL_BASED_HIGHLOW']: # Handle all high and low parts of a 32bit relocation # # Add relocation_difference to the value at RVA=entry.rva self.set_dword_at_rva( entry.rva, self.get_dword_at_rva(entry.rva)+relocation_difference) elif entry.type == RELOCATION_TYPE['IMAGE_REL_BASED_HIGHADJ']: # Fix the high 16bits of a relocation and adjust # # Add high 16bits of relocation_difference to the 32bit value # composed from the (16bit value at RVA=entry.rva)<<16 plus # the 16bit value at the next relocation entry. # # If the next entry is beyond the array's limits, # abort... the table is corrupt # if entry_idx == len(reloc.entries): break next_entry = reloc.entries[entry_idx] entry_idx += 1 self.set_word_at_rva( entry.rva, ((self.get_word_at_rva(entry.rva)<<16) + next_entry.rva + relocation_difference & 0xffff0000) >> 16 ) elif entry.type == RELOCATION_TYPE['IMAGE_REL_BASED_DIR64']: # Apply the difference to the 64bit value at the offset # RVA=entry.rva self.set_qword_at_rva( entry.rva, self.get_qword_at_rva(entry.rva) + relocation_difference) def verify_checksum(self): return self.OPTIONAL_HEADER.CheckSum == self.generate_checksum() def generate_checksum(self): # This will make sure that the data represeting the PE image # is updated with any changes that might have been made by # assigning values to header fields as those are not automatically # updated upon assignment. # self.__data__ = self.write() # Get the offset to the CheckSum field in the OptionalHeader # checksum_offset = self.OPTIONAL_HEADER.__file_offset__ + 0x40 # 64 checksum = 0 for i in range( len(self.__data__) / 4 ): # Skip the checksum field # if i == checksum_offset / 4: continue dword = struct.unpack('I', self.__data__[ i*4 : i*4+4 ])[0] checksum = (checksum & 0xffffffff) + dword + (checksum>>32) if checksum > 2**32: checksum = (checksum & 0xffffffff) + (checksum >> 32) checksum = (checksum & 0xffff) + (checksum >> 16) checksum = (checksum) + (checksum >> 16) checksum = checksum & 0xffff return checksum + len(self.__data__)
Python
#!/usr/bin/env python # # Copyright (C) 2009, Florian Hoech # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301, USA """ winresource.py Read and write resources from/to Win32 PE files. Commandline usage: winresource.py <dstpath> <srcpath> Updates or adds resources from file <srcpath> in file <dstpath>. 2009-03 Florian Hoech """ import os.path import pywintypes import win32api silent = False # True suppresses all messages LOAD_LIBRARY_AS_DATAFILE = 2 ERROR_BAD_EXE_FORMAT = 193 ERROR_RESOURCE_DATA_NOT_FOUND = 1812 ERROR_RESOURCE_TYPE_NOT_FOUND = 1813 ERROR_RESOURCE_NAME_NOT_FOUND = 1814 ERROR_RESOURCE_LANG_NOT_FOUND = 1815 class File(object): """ Win32 PE file class. """ def __init__(self, filename): self.filename = filename def get_resources(self, types=None, names=None, languages=None): """ Get resources. types = a list of resource types to search for (None = all) names = a list of resource names to search for (None = all) languages = a list of resource languages to search for (None = all) Return a dict of the form {type_: {name: {language: data}}} which might also be empty if no matching resources were found. """ return GetResources(self.filename, types, names, languages) def update_resources(self, data, type_, names=None, languages=None): """ Update or add resource data. type_ = resource type to update names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ UpdateResources(self.filename, data, type_, names, languages) def update_resources_from_datafile(self, srcpath, type_, names=None, languages=None): """ Update or add resource data from file srcpath. type_ = resource type to update names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ UpdateResourcesFromDataFile(self.filename, srcpath, type_, names, languages) def update_resources_from_dict(self, res, types=None, names=None, languages=None): """ Update or add resources from resource dict. types = a list of resource types to update (None = all) names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ UpdateResourcesFromDict(self.filename, res, types, names, languages) def update_resources_from_resfile(self, srcpath, types=None, names=None, languages=None): """ Update or add resources from dll/exe file srcpath. types = a list of resource types to update (None = all) names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ UpdateResourcesFromResFile(self.filename, srcpath, types, names, languages) def _GetResources(hsrc, types=None, names=None, languages=None): """ Get resources from hsrc. types = a list of resource types to search for (None = all) names = a list of resource names to search for (None = all) languages = a list of resource languages to search for (None = all) Return a dict of the form {type_: {name: {language: data}}} which might also be empty if no matching resources were found. """ res = {} try: # print "I: Enumerating resource types" enum_types = win32api.EnumResourceTypes(hsrc) if types and not "*" in types: enum_types = filter(lambda type_: type_ in types, enum_types) for type_ in enum_types: # print "I: Enumerating resources of type", type_ enum_names = win32api.EnumResourceNames(hsrc, type_) if names and not "*" in names: enum_names = filter(lambda name: name in names, enum_names) for name in enum_names: # print "I: Enumerating resources of type", type_, "name", name enum_languages = win32api.EnumResourceLanguages(hsrc, type_, name) if languages and not "*" in languages: enum_languages = filter(lambda language: language in languages, enum_languages) for language in enum_languages: data = win32api.LoadResource(hsrc, type_, name, language) if not type_ in res: res[type_] = {} if not name in res[type_]: res[type_][name] = {} res[type_][name][language] = data except pywintypes.error, exception: if exception.args[0] in (ERROR_RESOURCE_DATA_NOT_FOUND, ERROR_RESOURCE_TYPE_NOT_FOUND, ERROR_RESOURCE_NAME_NOT_FOUND, ERROR_RESOURCE_LANG_NOT_FOUND): # print "I:", exception.args[1] + ":", \ # exception.args[2] pass else: raise exception return res def GetResources(filename, types=None, names=None, languages=None): """ Get resources from dll/exe file. types = a list of resource types to search for (None = all) names = a list of resource names to search for (None = all) languages = a list of resource languages to search for (None = all) Return a dict of the form {type_: {name: {language: data}}} which might also be empty if no matching resources were found. """ hsrc = win32api.LoadLibraryEx(filename, 0, LOAD_LIBRARY_AS_DATAFILE) res = _GetResources(hsrc, types, names, languages) win32api.FreeLibrary(hsrc) return res def UpdateResources(dstpath, data, type_, names=None, languages=None): """ Update or add resource data in dll/exe file dstpath. type_ = resource type to update names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ # look for existing resources res = GetResources(dstpath, [type_], names, languages) # add type_, names and languages not already present in existing resources if not type_ in res and type_ != "*": res[type_] = {} if names: for name in names: if not name in res[type_] and name != "*": res[type_][name] = [] if languages: for language in languages: if not language in res[type_][name] and language != "*": res[type_][name].append(language) # add resource to destination, overwriting existing resources hdst = win32api.BeginUpdateResource(dstpath, 0) for type_ in res: for name in res[type_]: for language in res[type_][name]: if not silent: print "I: Updating resource type", type_, "name", name, \ "language", language win32api.UpdateResource(hdst, type_, name, data, language) win32api.EndUpdateResource(hdst, 0) def UpdateResourcesFromDataFile(dstpath, srcpath, type_, names=None, languages=None): """ Update or add resource data from file srcpath in dll/exe file dstpath. type_ = resource type to update names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ src = open(srcpath, "rb") data = src.read() src.close() UpdateResources(dstpath, data, type_, names, languages) def UpdateResourcesFromDict(dstpath, res, types=None, names=None, languages=None): """ Update or add resources from resource dict in dll/exe file dstpath. types = a list of resource types to update (None = all) names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ for type_ in res: if not types or type_ in types: for name in res[type_]: if not names or name in names: for language in res[type_][name]: if not languages or language in languages: UpdateResources(dstpath, res[type_][name][language], [type_], [name], [language]) def UpdateResourcesFromResFile(dstpath, srcpath, types=None, names=None, languages=None): """ Update or add resources from dll/exe file srcpath in dll/exe file dstpath. types = a list of resource types to update (None = all) names = a list of resource names to update (None = all) languages = a list of resource languages to update (None = all) """ res = GetResources(srcpath, types, names, languages) UpdateResourcesFromDict(dstpath, res)
Python
""" optparse -- forward-compatibility wrapper for use with Python 2.2.x and earlier. If you import from 'optparse' rather than 'optik', your code will work on base Python 2.3 (and later), or on earlier Pythons with Optik 1.4.1 or later installed. """ from pyi_optik import __version__, __all__ from pyi_optik import *
Python
#!/usr/bin/env python # pyNetworkManager v1.1 - cross-platform Python network management library # Copyright (C) 2012 River Hill Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This is simply a pyNM demo/test. It actually works well, so don't worry # about the "demo/test" part. :P # import pyNM print "Loading pyNetworkManager..." pyNMHandle = pyNM.pyNM() print "Using pyNetworkManager version "+str(pyNMHandle.getVersion()) print "Initializing pyNetworkManager..." pyNMHandle.initNM() print "Setting wireless NIC to DHCP..." pyNMHandle.setWirelessDHCP()
Python
#!/usr/bin/env python # wxAnimPlus v0.1 Alpha - an extension to the wxPython animation class # Copyright (C) 2012 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ###### DEPRECATED UNTIL FURTHER NOTICE ###### import random import wx from PIL import Image # NOTE TO SELF: wx.animate is a piece of crap, use PIL frame by frame parsing and # use http://wiki.wxpython.org/WorkingWithImages to convert to wxImage class PILGIFImageSequence: def __init__(self, im): self.im = im def __getitem__(self, ix): try: if ix: self.im.seek(ix) return self.im except EOFError: raise IndexError # end of sequence class AnimPlusCtrl(wx.PyControl): def __init__(self, parent, id=wx.ID_ANY, anim="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER, validator=wx.DefaultValidator, name="AnimPlusCtrl"): wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name) # Control setup self.SetInitialSize(size) self.SetPosition(pos) self.InheritAttributes() print "Loading GIF animation from: "+anim self.animation = Image.open(anim) #res = self.LoadFile(anim) if (self.animation): self.frames = 0 for frame in PILGIFImageSequence(self.animation): self.frames += 1 #self.frames = len(PILGIFImageSequence(self.animation)) print "Total GIF frames: "+str(self.frames) print "GIF frame size: "+str(self.animation.size) if self.frames == 0: raise Exception("AnimPlusCtrl: Could not load image! (Empty GIF?)") # Reinitialize the image object so that we can seek back to frame 0. self.animation = Image.open(anim) self.curframe = 0 else: raise Exception("AnimPlusCtrl: Could not load image!") self.image = wx.EmptyImage(*self.animation.size) self.TIMER_ID = random.randrange(999, 99999) self.timer = wx.Timer(self, self.TIMER_ID) self.timer.Start(1) self.Bind(wx.EVT_TIMER, self.on_timer) self.parent = parent # Fetch the first image so that we have a wxImage object #self.image = self.animation.GetFrame(1) self.parent.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) #self.on_timer(None) def on_timer(self, event): print "AnimPlusCtrl: on_timer called!" self.timer.Stop() print "DEBUG: self.animation: "+str(self.animation) if self.curframe <= self.frames: print "AnimPlusCtrl: Playing GIF frame "+str(self.curframe)+" out of "+str(self.frames)+" (PIL frame: "+str(self.animation.tell())+")" int = self.animation.info["duration"] RGBData = self.animation.convert('RGB').tostring() self.image.SetData(RGBData) RGBAData = self.animation.convert('RGBA').tostring() AlphaData = RGBAData[3::4] self.image.SetAlphaData(AlphaData) #self.image = self.animation.GetFrame(self.curframe); self.timer = wx.Timer(self.parent, self.TIMER_ID) self.Bind(wx.EVT_TIMER, self.on_timer) self.timer.Start(int) # Add to the frame number and seek to the next frame! self.curframe += 1 self.animation.seek(self.curframe) print "END FRAME" pass def on_paint(self, event): bitmap = wx.BitmapFromImage(self.image) #dc = wx.PaintDC(self.parent) dc = wx.PaintDC(self) w, h = dc.GetSize() dc.Clear() dc.DrawBitmap(bitmap, 0, 0, True) def OnEraseBackground(self, event): # Anti-flicker :P pass
Python
#!/usr/bin/env python # SpringDS v1.0 Beta 1 - a (cross-platform?) wrapper for the FRC Driver Station # Copyright (C) 2012 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import wx import os, sys import traceback import pyNM import threading import time import subprocess import psutil import SpringDSCrash import SpringDSConfig #import random if sys.platform == 'win32': import win32api # Variables # Version SPRINGDS_VERSION = "1.0 beta 1" # Functions # MsgBox - shows a message box. # Types: wx.ICON_INFORMATION, wx.ICON_EXCLAMATION, wx.ICON_ERROR, wx.ICON_ERROR def MsgBox(text, title, type, parent=None): dlg = wx.MessageDialog(parent, text, title, wx.OK | type) dlg.ShowModal() # ErrorBox - shows a error box with a Python traceback. Used if something crashed. def ErrorBox(traceback): SDSCrashFrameInstance = SpringDSCrash.SDSCrashFrame(traceback) #app.SetTopWindow(SDSCrashFrameInstance) SDSCrashFrameInstance.MakeModal() SDSCrashFrameInstance.ShowModal() SDSCrashFrameInstance.MakeModal(False) # Define notification event for thread completion updates EVT_UPDATE_STATUS_ID = wx.NewId() # Define notification event for window termination trigger EVT_TERMINATE_WINDOW_ID = wx.NewId() # Define notification event for unhooking the OnQuit window hook EVT_UNHOOK_ONQUIT_ID = wx.NewId() # Define notification event for showing an error box EVT_ERROR_NOTIFY_ID = wx.NewId() def EVT_UPDATE_STATUS(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_UPDATE_STATUS_ID, func) def EVT_TERMINATE_WINDOW(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_TERMINATE_WINDOW_ID, func) def EVT_UNHOOK_ONQUIT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_UNHOOK_ONQUIT_ID, func) def EVT_ERROR_NOTIFY(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_ERROR_NOTIFY_ID, func) class IOStatusParser: def __init__(self, updatewin, oldio): self.updatewin = updatewin self.oldio = oldio def write(self, text): if text.strip() != "": partn = 0 finaltext = "" for part in text.strip().split(" "): partn += 1 if part != "": if (part[0] == '[') and (part[-1] == ']'): # Check if (partn == 2) and (part == "[SpringDSFrame.on_paint]"): finaltext = "" break else: finaltext = " ".join(text.strip().split(" ")[partn-1:]) break wx.PostEvent(self.updatewin, UpdateStatusEvent(finaltext)) self.oldio.write(text) '''def close(self): self.logfile.write(" Log Session End - "+date("%Y-%m-%d %H:%M:%S")+" **\n") self.logfile.close()''' class UpdateStatusEvent(wx.PyEvent): """Event that carries the status update data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_UPDATE_STATUS_ID) self.data = data class TerminateWindowEvent(wx.PyEvent): """Event that tells the window thread to exit.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_TERMINATE_WINDOW_ID) self.data = data class UnhookOnQuitEvent(wx.PyEvent): """Event that tells the window to unhook its OnQuit event.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_UNHOOK_ONQUIT_ID) self.data = data class ErrorNotifyEvent(wx.PyEvent): """Event that tells the window something bad happened.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_ERROR_NOTIFY_ID) self.data = data class SpringDS_NM(threading.Thread): def __init__(self, updatewin): threading.Thread.__init__(self) self.updatewin = updatewin self.stopNow = False self.oldstdout = sys.stdout self.pyNMHandle = None self.errBoxOpen = True def killSpringDS_NM(self): # Terminate this thread self.stopNow = True def checkKill(self): # Check for flag if self.stopNow == True: self.doKill() def setErrBoxClose(self): self.errBoxOpen = False def doKill(self): # Shut down pyNM print "[SpringDS] Terminating SpringDS and the Driver Station..." for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Dashboard.exe": proc.terminate() if proc.name == "Driver Station.exe": proc.terminate() #print "[SpringDS] Pausing for 3 seconds..." time.sleep(1) try: if self.pyNMHandle != None: self.pyNMHandle._disableRefresh(False) # By now, we've refreshed everything by force. Disable it again for a speedy exit. self.pyNMHandle._disableRefresh(True) if SpringDSConfig.getCfgNICType() == "wireless": print "[SpringDS] Resetting wireless NIC to DHCP..." self.pyNMHandle.setWirelessDHCP() elif SpringDSConfig.getCfgNICType() == "lan": print "[SpringDS] Resetting LAN NIC to DHCP..." self.pyNMHandle.setLANDHCP() except: # Allow termination wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) print "[SpringDS] Restoring I/O..." print "[SpringDS] Exiting..." sys.stdout = self.oldstdout wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) exit() def run(self): out2status = IOStatusParser(self.updatewin, sys.stdout) sys.stdout = out2status self.checkKill() try: SpringDSConfig.initConfig() except: MsgBox("Couldn't load SpringDS configuration!", "Error - SpringDS", wx.ICON_ERROR) import traceback wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) exit() #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) #print "[SpringDS] Couldn't load configuration! Press ALT-F4 to exit." # Wrap all of this in a try/catch so that we can watch for errors and handle # them nicely! try: print "[SpringDS] Loading pyNetworkManager..." self.pyNMHandle = pyNM.pyNM() self.checkKill() print "[SpringDS] Using pyNetworkManager version "+str(self.pyNMHandle.getVersion()) print "[SpringDS] Initializing pyNetworkManager..." #raise pyNM.pyNMError("test", pyNM.pyNM_ERROR_SYSTEM, -123) self.pyNMHandle.initNM() self.checkKill() self.pyNMHandle._disableRefresh() self.checkKill() if SpringDSConfig.getCfgNICType() == 'wireless': print "[SpringDS] Setting required FRC static IP and subnet on wireless NIC: "+SpringDSConfig.getCfgStaticIP()+" and "+SpringDSConfig.getCfgSubnet() self.pyNMHandle.setWirelessStaticIPAndSubnet(SpringDSConfig.getCfgStaticIP(), SpringDSConfig.getCfgSubnet()) elif SpringDSConfig.getCfgNICType() == 'lan': print "[SpringDS] Setting required FRC static IP and subnet on LAN NIC: "+SpringDSConfig.getCfgStaticIP()+" and "+SpringDSConfig.getCfgSubnet() self.pyNMHandle.setLANStaticIPAndSubnet(SpringDSConfig.getCfgStaticIP(), SpringDSConfig.getCfgSubnet()) self.checkKill() # Now launch the Driver Station (and wait)! print "[SpringDS] Launching FRC Driver Station..." subprocess.call(SpringDSConfig.getCfgDriverStationPath()) self.checkKill() print "[SpringDS] Ensuring that everything has closed (and if not, terminating them)..." for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Dashboard.exe": proc.terminate() self.checkKill() self.checkKill() #print "[SpringDS] Pausing for 3 seconds..." #time.sleep(3) self.pyNMHandle._disableRefresh(False) # By now, we've refreshed everything by force. Disable it again for a speedy exit. self.pyNMHandle._disableRefresh(True) if SpringDSConfig.getCfgNICType() == 'wireless': print "[SpringDS] Resetting wireless NIC to DHCP..." self.pyNMHandle.setWirelessDHCP() elif SpringDSConfig.getCfgNICType() == 'lan': print "[SpringDS] Resetting LAN NIC to DHCP..." self.pyNMHandle.setLANDHCP() self.checkKill() print "[SpringDS] Exiting..." sys.stdout = self.oldstdout time.sleep(2) self.checkKill() wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) except pyNM.pyNMError, err: # TODO: add more cases # Is this a permission error? if err.IsSystemError: # Is this a permission error? (This is a subset of the system error) if err.IsPermissionError: # Are we on Windows? if sys.platform == 'win32': wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) # Check args - this should be fixed later to actually check for elevation. ELEVATED = 0 if len(sys.argv) > 1: if sys.argv[1] == '--FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH': # We tried elevating, it failed. ELEVATED = 1 MsgBox("Could not set network config, even with elevation!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDS] Could not set network config, even with elevation. Press ALT-F4 to exit." try: if ELEVATED == 0: #print "DEBUG: sys.argv is "+str(sys.argv) #print "DEBUG: __file__ is "+str(__file__) if getattr(sys, 'frozen', False): print "[SpringDS] Detected regular old script execution, so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" "+" ".join(sys.argv[1:])+"'" win32api.ShellExecute(0, "runas", sys.executable, "'"+" ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif sys.argv[0][len(sys.argv[0])-3:] == '.py': print "[SpringDS] Detected regular old script execution (2), so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" '"+os.path.abspath(__file__)+"''" win32api.ShellExecute(0, "runas", sys.executable, '"'+os.path.abspath(__file__)+'"'+" --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif __file__: print "[SpringDS] Detected that we're in a EXE, so executing accordingly with elevation." print "'"+__file__+" "+" '".join(sys.argv[1:])+"''" win32api.ShellExecute(0, "runas", __file__, "' ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) else: MsgBox("Failed to determine script execution environment!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDS] Failed to determine script execution environment! Press ALT-F4 to exit." except: MsgBox("Couldn't launch SpringDS in elevated mode!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDS] Couldn't launch SpringDS in elevated mode! Press ALT-F4 to exit." else: import traceback if err.exception != "": wx.PostEvent(self.updatewin, ErrorNotifyEvent(err.exception+"\n\n"+"".join(traceback.format_exc()))) else: wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDS] Code failed! Press ALT-F4 to exit. [Inner loop]" #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise except SystemExit: pass except: import traceback print "GAHAHHHHHHHHH FAILURE!!!!" traceback.print_exc() wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDS] Code failed! Press ALT-F4 to exit." #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise class SpringDSFrame(wx.Frame): """ class Panel1 creates a panel for the tile image fw and fh are the width and height of the base frame """ def __init__(self, parent, id, size): wx.Frame.__init__(self, parent, id, "SpringDS", size) # Create panel self.panel = wx.Panel(self) self.panel.SetBackgroundColour((0, 0, 0)) # Background setup print "[SpringDS] Loading image from: "+os.path.join(os.getcwd(), "stripebg.png") self.bmp1 = wx.Bitmap(os.path.join(os.getcwd(), "stripebg.png")) #self.panel.Bind(wx.EVT_ERASE_BACKGROUND, self.on_paint) self.SetIcon(wx.Icon("SpringDSIcon.ico", wx.BITMAP_TYPE_ICO, 16, 16)) self.invalidated = True #wx.EVT_SIZE(self, self.on_size) # now put a button on the panel, on top of wallpaper #self.button1 = wx.Button(self.panel, -1, label='Button1', pos=(10, 5)) self.logo = wx.StaticText(self.panel, -1, '', pos=(5,5)) self.logo.SetBackgroundColour((0, 0, 0)) self.logo.SetForegroundColour((255, 255, 255)) font2 = wx.Font(16, wx.MODERN, wx.NORMAL, wx.BOLD)#, False, u'Comic Sans MS') self.logo.SetFont(font2) self.logo.SetLabel("SpringDS v"+SPRINGDS_VERSION+" - Team #4067") self.status = wx.StaticText(self.panel, -1, '', pos=(10,5)) self.status.SetBackgroundColour((0, 0, 0)) self.status.SetForegroundColour((255, 255, 255)) font = wx.Font(16, wx.MODERN, wx.NORMAL, wx.BOLD)#, False, u'Comic Sans MS') self.status.SetFont(font) self.status2 = wx.StaticText(self.panel, -1, '', pos=(10,5)) self.status2.SetBackgroundColour((0, 0, 0)) self.status2.SetForegroundColour((255, 255, 255)) font = wx.Font(16, wx.MODERN, wx.NORMAL, wx.BOLD)#, False, u'Comic Sans MS') self.status2.SetFont(font) #loading_gif_file = os.path.join(os.getcwd(), "loading_images", "loading" + str(random.randrange(1,6)) + ".gif") # DEPRECATED - doesn't work at all! #loading_widget = wxAnimPlus.AnimPlusCtrl(self, wx.ID_ANY, loading_gif_file, pos=(100,100)) # BROKEN - buggy background #self.ag = wx.animate.GIFAnimationCtrl(self, id, loading_gif_file, pos=(100, 100)) # clears the background #self.ag.GetPlayer().UseBackgroundColour(True) # continuously loop through the frames of the gif file (default) #self.ag.Play() # BROKEN FOR NOW #self.loading = wxAnimPlus.AnimPlusCtrl(self, id, loading_gif_file, pos=(100, 100)) self.Show() self.Bind(wx.EVT_SIZE, self.on_size) self.Bind(wx.EVT_CLOSE, self.on_quit) self.SetSize(size) self.ShowFullScreen(True) # Connect the status update event to a callback EVT_UPDATE_STATUS(self, self.OnUpdateStatus) EVT_TERMINATE_WINDOW(self, self.OnTerminateWindow) EVT_UNHOOK_ONQUIT(self, self.OnUnhookOnQuit) EVT_ERROR_NOTIFY(self, self.OnErrorNotify) self.SpringDS_NM_Instance = SpringDS_NM(self) self.SpringDS_NM_Instance.start() self.quitTriggered = False self.hasTerminated = False def OnErrorNotify(self, event): # Show the error #print "CALLED: showing error!" ErrorBox('%s' % event.data) self.SpringDS_NM_Instance.setErrBoxClose() self.SetFocus() def OnUnhookOnQuit(self, event): self.Unbind(wx.EVT_CLOSE) def OnTerminateWindow(self, event): self.hasTerminated = True self.status2.SetLabel("SpringDS has terminated, closing this window...") self.Refresh() self.Update() time.sleep(2) self.Destroy() def on_quit(self, event): if (self.quitTriggered == False) and (self.hasTerminated == False): self.status2.SetLabel("Attempting to terminate SpringDS, please wait...") self.SpringDS_NM_Instance.killSpringDS_NM() self.quitTriggered = True self.status2.SetLabel("SpringDS is terminating, please wait...") for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Dashboard.exe": proc.terminate() if proc.name == "Driver Station.exe": proc.terminate() else: self.status2.SetLabel("SpringDS is already terminating, please wait...") def OnUpdateStatus(self, event): # Update the status text! if event.data != None: # Process data and set the label self.status.SetLabel('%s' % event.data) def on_paint(self, event): '''if self.invalidated == True: self.invalidated = False else: event.Skip() return''' print "[SpringDS] [SpringDSFrame.on_paint] Function called for painting!" # do the actual drawing on the memory dc here #dc = wx.PaintDC(self.panel) dc = event.GetDC() if not dc: dc = wx.ClientDC(self) rect = self.GetUpdateRegion().GetBox() dc.SetClippingRect(rect) #dc.Clear() w, h = dc.GetSize() # Create BufferBmp and set the same size as the drawing area. #self.BufferBmp = wx.EmptyBitmap(w, h) #memdc = wx.MemoryDC() #memdc.Clear() #memdc.SelectObject(self.BufferBmp) #memdc.BeginDrawing() #dc.SetBackgroundMode(wx.TRANSPARENT) # get image width and height iw = self.bmp1.GetWidth() ih = self.bmp1.GetHeight() # tile/wallpaper the image across the canvas # Draw once to ensure it's done, even if it doesn't trigger from the for loop #dc.DrawBitmap(self.bmp1, 0, 0, True) for x in range(0, self.panel.GetSize()[0], iw): for y in range(0, self.panel.GetSize()[1], ih): dc.DrawBitmap(self.bmp1, x, y, True) #dc.Clear() #dc.EndDrawing() #dc.DrawBitmap(self.BufferBmp, 0, 0, True) #self.panel.Refresh() def on_size(self, event): print "[on_size] Invalidating draw state..." if (self.status != None): self.status.SetPosition((5, self.GetSize()[1] - 20 - 5)) if (self.status2 != None): self.status2.SetPosition((5, self.GetSize()[1] - 20 - 20 - 5)) #if (self.ag != None): # self.ag.SetPosition((5, self.GetSize()[1] - 60 - 5)) self.invalidated = True event.Skip() print "SpringDS v"+str(SPRINGDS_VERSION) bar = "" for i in range(0, len("SpringDS v"+str(SPRINGDS_VERSION)) + 1): bar = bar + "=" print bar print "Copyright (C) 2012 River Hill Robotics Team (Albert H.)\n" app = wx.PySimpleApp() # create a window/frame instance, no parent, -1 is default ID fw = 320 fh = 240 try: SpringDSFrameInstance = SpringDSFrame(None, -1, size=(fw, fh)) app.SetTopWindow(SpringDSFrameInstance) app.MainLoop() except: print "[SpringDS] Crashed..." traceback.print_exc() if sys.platform == 'win32': raw_input("[SpringDS] Press ENTER to exit.")
Python
#!/usr/bin/env python # SpringDS v1.0 Beta 1 - a (cross-platform?) wrapper for the FRC Driver Station # Copyright (C) 2012 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # SpringDS Configuration Management Class # # Configuration Documentation # ============================ # Sample configuration: ################################################################################ # [network] # staticip = 10.40.67.9 # subnet = 255.0.0.0 # nictype = wireless # cnicindex = 1 # teamip = 1 # teamid = 4067 # # [paths] # driverstation = C:\Program Files\FRC Driver Station\Driver Station.exe # dashboard = C:\Program Files\FRC Driver Station\Dashboard.exe # # [springds] # autoupdate = 1 ################################################################################ # Explanation of fields: # network: # staticip - the static IP that will be set. # subnet - the subnet that will be set. # nictype - the type of NIC that will be used. # It can be "lan", "wireless", or "nicindex". # The option "nicindex" specifies an index that will be # used to access a certain NIC within the system's list. # cnicindex - the NIC index in the system's list. This is used when # nictype is "nicindex". # teamip - whether to use the team number to automatically figure out # the IP address or not. (1 for yes, 0 for no) # teamid - the FRC team number/ID. This is used when teamip is 1. # paths: # driverstation - the path to the FRC Driver Station. # dashboard - the path to the FRC Dashboard. # springds: # autoupdate - whether to enable autoupdate or not. (1 for yes, 0 for no.) # # These settings can be changed manually or in the SpringDS Settings program. # ################################################################################ # TODO: # - Implement SpringDSConfigError class and raise them as necessary # - Implement team # -> IP conversion # - More stringent error checking # import os, sys import ConfigParser import re import traceback # Set up globals global configFilePath configFilePath = "" global Config global _hasInited hasInited = False # Default values # WARNING: This is used to write new configs... AND check against old ones. # Don't edit unless you are changing the config structure! configData = { "network" : { "staticip" : "10.40.67.9", "subnet" : "255.0.0.0", "nictype" : "wireless", "cnicindex" : "1", "teamip" : "1", "teamid" : "4067" }, "paths" : { "driverstation" : "C:\Program Files\FRC Driver Station\Driver Station.exe", "dashboard" : "C:\Program Files\FRC Driver Station\Dashboard.exe" }, "springds" : { "autoupdate" : "1" } } # SpringDSConfig error class # TODO: add flag support, error types class SpringDSConfigError(Exception): """Exception raised for errors in the input. Attributes: errMsg: [ARG - required] Explanation of the error. exception: [ARG - optional] Python exception that caused this error. """ def __init__(self, errMsg, exception = ""): # Bind the variables (not really, more like copy) to the class self.errMsg = errMsg self.exception = exception Exception.__init__(self, errMsg) def is_valid_ipv4(ip): """Validates IPv4 addresses. """ pattern = re.compile(r""" ^ (?: # Dotted variants: (?: # Decimal 1-255 (no leading 0's) [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2} | 0x0*[0-9a-f]{1,2} # Hexadecimal 0x0 - 0xFF (possible leading 0's) | 0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's) ) (?: # Repeat 0-3 times, separated by a dot \. (?: [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2} | 0x0*[0-9a-f]{1,2} | 0+[1-3]?[0-7]{0,2} ) ){0,3} | 0x0*[0-9a-f]{1,8} # Hexadecimal notation, 0x0 - 0xffffffff | 0+[0-3]?[0-7]{0,10} # Octal notation, 0 - 037777777777 | # Decimal notation, 1-4294967295: 429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}| 42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}| 4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8} ) $ """, re.VERBOSE | re.IGNORECASE) return pattern.match(ip) is not None # Internal function # Thanks to the Python guys for this code snipplet! # http://wiki.python.org/moin/ConfigParserExamples def ConfigSectionMap(Config, section): dict1 = {} options = Config.options(section) for option in options: try: dict1[option] = Config.get(section, option) if dict1[option] == -1: DebugPrint("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None raise SpringDSConfigError("Failed to create configuration map!", "".join(traceback.format_exc())) return dict1 # Write out configuration! def writeConfig(): global configFilePath global Config if configFilePath != "": try: cfg = open(configFilePath, "w") Config.write(cfg) cfg.close() except: raise SpringDSConfigError("Failed to save configuration!", "".join(traceback.format_exc())) # Reread config Config.read(configFilePath) else: print "[SpringDSConfig] W: Attempted to write config when configFilePath isn't defined yet." # Finds and checks config, and then enables this module. def initConfig(): global configFilePath global Config global _hasInited Config = ConfigParser.ConfigParser() configFilePath = "" print "[SpringDSConfig] Trying to find and open config file... (path "+sys.path[0]+"\SpringDS.ini)" if sys.path[0] == "": if sys.argv[0] == "": print "[SpringDSConfig] Can't find absolute path - will try using the config file in current directory!" configFilePath = ".\SpringDS.ini" whichPath = "current_dir" else: print "[SpringDSConfig] Selecting config file in argv directory: "+sys.argv[0]+"\SpringDS.ini" whichPath = "argv" configFilePath = sys.argv[0]+"\SpringDS.ini" else: print "[SpringDSConfig] Selecting config file in path directory: "+sys.path[0]+"\SpringDS.ini" whichPath = "path" configFilePath = sys.path[0]+"\SpringDS.ini" if (os.path.isfile(configFilePath)): print "[SpringDSConfig] Found config file: "+configFilePath else: # Write some default values. print "[SpringDSConfig] No config file found, so writing a new one." for rsect in configData: Config.add_section(rsect) for rkey, value in rsect.items(): Config.set(rsect, rkey, value) writeConfig() try: Config.read(configFilePath) except: raise SpringDSConfigError("Failed to read configuration!", "".join(traceback.format_exc())) # Now check the sections #print "DEBUG: cfg_sections set to "+str(Config.sections()) cfg_sections = Config.sections() cur_sections = Config.sections() track_rsections = {} for rsect in configData: track_rsections[rsect] = 0 for sect in cfg_sections: secisvalid = False #print "DEBUG: parsing sect "+sect for rsect in configData: #print "DEBUG: rsect "+rsect if rsect == sect: #print "DEBUG: Valid match!" # Increment counter track_rsections[sect] += 1 # Remove the first match - this allows us to detect any duplicate sections! cur_sections.pop(cur_sections.index(sect)) secisvalid = True break if secisvalid != True: print "[SpringDSConfig] W: Detected invalid section "+sect+", removing." Config.remove_section(sect) writeConfig() #print "DEBUG: cfg_sections is "+str(cfg_sections) # Check counter for rsect, count in track_rsections.items(): if count > 1: print "[SpringDSConfig] W: Detected duplicate sections of "+rsect+", consolidating." config_backup = ConfigSectionMap(Config, rsect) while 1: try: Config.remove_section(rsect) except: break Config.add_section(rsect) for key, value in config_backup.items(): Config.set(rsect, key, value) writeConfig() if count == 0: print "[SpringDSConfig] W: Detected missing section "+rsect+", writing defaults. (Count: "+str(count)+")" Config.add_section(rsect) for key, value in configData[rsect].items(): Config.set(rsect, key, value) writeConfig() if count < 0: print "[SpringDSConfig] W: Negative count for section: "+rsect ##################### # Check key validity ##################### for rsect in configData: req_keys = configData[rsect] track_rkeys = {} for reqkey in req_keys: track_rkeys[reqkey] = 0 cur_keys = [] for key, value in ConfigSectionMap(Config, rsect).items(): cur_keys.append(key) for key in ConfigSectionMap(Config, rsect): keyisvalid = False for rkey in req_keys: if rkey == key: # Increment counter track_rkeys[key] += 1 # Remove the first match - this allows us to detect any duplicate sections! cur_keys.pop(cur_keys.index(key)) keyisvalid = True if keyisvalid != True: print "[SpringDSConfig] W: Detected invalid key "+key+" in section "+rsect+", removing." Config.remove_option(rsect, key) writeConfig() # Check counter for rkey, count in track_rkeys.items(): if count > 1: print "[SpringDSConfig] W: Detected duplicate key "+rkey+" in section "+rsect+", consolidating." key_backup = ConfigSectionMap(Config, rsect)[key] while 1: try: Config.remove_option(rsect, rkey) except: break Config.set(rsect, rkey, key_backup) writeConfig() if count == 0: print "[SpringDSConfig] W: Detected missing key "+rkey+" in section "+rsect+", writing defaults." Config.set(rsect, rkey, configData[rsect][rkey]) writeConfig() if count < 0: print "[SpringDSConfig] W: Negative count for key: "+rsect # We're ready! _hasInited = True print "[SpringDSConfig] Configuration initialized!" def getCfgStaticIP(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgStaticIP called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if getCfgTeamIP() == "1": # Translate team number into an IP address! team = getCfgTeamID() if (len(team) > 4) or (len(team) < 1): raise SpringDSConfigError("Couldn't get static IP: Invalid team number specified! (TeamIP is enabled)", "".join(traceback.format_exc())) elif len(team) == 4: return "10."+team[:2]+"."+team[2:]+".6" elif len(team) == 3: return "10."+team[:1]+"."+team[1:]+".6" elif len(team) <= 2: return "10.0."+team+".6" if is_valid_ipv4(ConfigSectionMap(Config, "network")["staticip"]): return ConfigSectionMap(Config, "network")["staticip"] else: raise SpringDSConfigError("Couldn't get static IP: Static IP specified is invalid!", "".join(traceback.format_exc())) #return configData["network"]["staticip"] # NOTE THE abs ADDITION def setCfgAbsStaticIP(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgStaticAbsIP called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if is_valid_ipv4(val): return Config.set("network", "staticip", val) else: raise SpringDSConfigError("Couldn't set static IP: Static IP specified is invalid!", "".join(traceback.format_exc())) # NOTE THE abs ADDITION def getCfgAbsStaticIP(): global _hasInited global Config if is_valid_ipv4(ConfigSectionMap(Config, "network")["staticip"]): return ConfigSectionMap(Config, "network")["staticip"] else: raise SpringDSConfigError("Couldn't get absolute static IP: Static IP specified is invalid!", "".join(traceback.format_exc())) #return configData["network"]["staticip"] def getCfgSubnet(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgSubnet called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if is_valid_ipv4(ConfigSectionMap(Config, "network")["staticip"]): return ConfigSectionMap(Config, "network")["subnet"] else: # TODO: error/fix IP raise SpringDSConfigError("Couldn't get subnet: Subnet specified is invalid!", "".join(traceback.format_exc())) #return configData["network"]["subnet"] def setCfgSubnet(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgSubnet called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if is_valid_ipv4(val): return Config.set("network", "subnet", val) else: # TODO: error raise SpringDSConfigError("Couldn't set subnet: Subnet specified is invalid!", "".join(traceback.format_exc())) def getCfgNICType(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgNICType called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if (ConfigSectionMap(Config, "network")["nictype"] == "wireless") or (ConfigSectionMap(Config, "network")["nictype"] == "lan") or (ConfigSectionMap(Config, "network")["nictype"] == "nic"): return ConfigSectionMap(Config, "network")["nictype"] else: # TODO: error/fix raise SpringDSConfigError("Couldn't get NIC type: NIC type specified is invalid!", "".join(traceback.format_exc())) #return "lan" def setCfgNICType(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgNICType called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if (val == "wireless") or (val == "lan") or (val == "nic"): return Config.set("network", "nictype", val) else: raise SpringDSConfigError("Couldn't set NIC type: NIC type specified is invalid!", "".join(traceback.format_exc())) def getCfgTeamIP(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgTeamIP called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if (ConfigSectionMap(Config, "network")["teamip"] == "0") or (ConfigSectionMap(Config, "network")["teamip"] == "1"): return ConfigSectionMap(Config, "network")["teamip"] else: #TODO: fix it? raise SpringDSConfigError("Couldn't get team number to IP use option (TeamIP): invalid value!", "".join(traceback.format_exc())) def setCfgTeamIP(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgTeamIP called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if (val == "0") or (val == "1"): return Config.set("network", "teamip", val) else: raise SpringDSConfigError("Couldn't set team number to IP use option (TeamIP): invalid value!", "".join(traceback.format_exc())) def getCfgTeamID(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgTeamID called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) return ConfigSectionMap(Config, "network")["teamid"] def setCfgTeamID(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgTeamID called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) return Config.set("network", "teamid", val) def getCfgDriverStationPath(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgDriverStationPath called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) return ConfigSectionMap(Config, "paths")["driverstation"] def setCfgDriverStationPath(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgDriverStationPath called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) return Config.set("paths", "driverstation", val) def getCfgDashboardPath(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgDashboardPath called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) return ConfigSectionMap(Config, "paths")["dashboard"] def setCfgDashboardPath(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgDashboardPath called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) return Config.set("paths", "dashboard", val) def getCfgAutoUpdateOpt(): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: getCfgAutoUpdateOpt called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if (ConfigSectionMap(Config, "springds")["autoupdate"] == "0") or (ConfigSectionMap(Config, "springds")["autoupdate"] == "1"): return ConfigSectionMap(Config, "springds")["autoupdate"] else: raise SpringDSConfigError("Couldn't get SpringDS auto update option (autoupdate): invalid value!", "".join(traceback.format_exc())) def setCfgAutoUpdateOpt(val): global _hasInited global Config if _hasInited == False: print "[SpringDSConfig] E: setCfgAutoUpdateOpt called without initing!" raise SpringDSConfigError("SpringDSConfig hasn't initialized yet!", "".join(traceback.format_exc())) if (val == "0") or (val == "1"): return Config.set("springds", "autoupdate", val) else: raise SpringDSConfigError("Couldn't get SpringDS auto update option (autoupdate): invalid value!", "".join(traceback.format_exc()))
Python
#!/usr/bin/env python # SpringDS v1.0 Beta 1 - a (cross-platform?) wrapper for the FRC Driver Station # Copyright (C) 2012 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This is the GUI class for the SpringDS crash dialog. # It is used by SpringDS and SpringDS Settings. # # -*- coding: iso-8859-15 -*- # generated by wxGlade 0.6.5 (standalone edition) on Mon Mar 19 19:16:07 2012 import wx import sys import traceback # begin wxGlade: extracode # end wxGlade try: from agw import hyperlink as hl except ImportError: # if it's not there locally, try the wxPython lib. import wx.lib.agw.hyperlink as hl #class SDSCrashFrame(wx.Frame): class SDSCrashFrame(wx.Dialog): #def __init__(self, *args, **kwds): def __init__(self, traceback): # begin wxGlade: SDSCrashFrame.__init__ #kwds["style"] = wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR #wx.Frame.__init__(self, *args, **kwds) #wx.Frame.__init__(self, None, id=-1, title="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR) wx.Dialog.__init__(self, None, id=-1, title="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR) self.SDSCrashBasePanel = wx.Panel(self, -1) self.SDSCrashErrorIcon = wx.StaticBitmap(self.SDSCrashBasePanel, -1, wx.ArtProvider.GetBitmap(wx.ART_ERROR)) self.SDSCrashHeaderLbl = wx.StaticText(self.SDSCrashBasePanel, -1, "SpringDS crashed! :(") self.SDSCrashMessageLbl = wx.StaticText(self.SDSCrashBasePanel, -1, "We apologize for the inconvenience.\nWe would appreciate it if you could report this problem to us.\nClick Error Report to see the error information and for more details on how to report.\nPress OK to exit.") self.SDSCrashErrorReportCP = wx.CollapsiblePane(self.SDSCrashBasePanel, label="Error Report") #self.SDSCrashErrorReportPanel = wx.Panel(self.SDSCrashBasePanel, -1) self.SDSCrashErrorReportPanel = self.SDSCrashErrorReportCP.GetPane() self.SDSCrashErrorReportLbl = wx.StaticText(self.SDSCrashErrorReportPanel, -1, "The following error occurred:") self.SDSCrashErrorReportTxtCtrl = wx.TextCtrl(self.SDSCrashErrorReportPanel, -1, traceback, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_WORDWRAP) self.SDSCrashErrorReportingInstructionsLbl = wx.StaticText(self.SDSCrashErrorReportPanel, -1, "Copy the above error message and report it here:") #self.SDSCrashErrorReportingURL = wx.StaticText(self.SDSCrashErrorReportPanel, -1, "URL") self.SDSCrashErrorReportingURL = hl.HyperLinkCtrl(self.SDSCrashErrorReportPanel, wx.ID_ANY, "http://code.google.com/p/frcbot4067/issues/entry", URL="http://code.google.com/p/frcbot4067/issues/entry") self.SDSCrashOKBtn = wx.Button(self.SDSCrashBasePanel, wx.ID_OK, "") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self.OnOKBtnClick, self.SDSCrashOKBtn) # end wxGlade def __set_properties(self): # begin wxGlade: SDSCrashFrame.__set_properties self.SetTitle("Error - SpringDS") _icon = wx.EmptyIcon() _icon.CopyFromBitmap(wx.Bitmap("SpringDSIcon.ico", wx.BITMAP_TYPE_ANY)) #self.SetIcon(_icon) self.SetIcon(wx.Icon("SpringDSIcon.ico", wx.BITMAP_TYPE_ICO, 16, 16)) self.SDSCrashHeaderLbl.SetFont(wx.Font(16, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSCrashErrorReportLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSCrashErrorReportTxtCtrl.SetFont(wx.Font(8, wx.MODERN, wx.NORMAL, wx.NORMAL, 0, "")) self.SDSCrashOKBtn.SetDefault() # end wxGlade def __do_layout(self): # begin wxGlade: SDSCrashFrame.__do_layout SDSCrashBaseSizer = wx.BoxSizer(wx.VERTICAL) SDSCrashMainSizer = wx.FlexGridSizer(3, 1, 0, 0) SDSCrashButtonSizer = wx.FlexGridSizer(1, 1, 0, 0) SDSCrashErrorReportSizer = wx.FlexGridSizer(3, 1, 0, 0) SDSCrashErrorReportingSizer = wx.GridSizer(2, 1, 0, 0) SDSCrashBitmapMessageSizer = wx.FlexGridSizer(1, 2, 0, 0) SDSCrashMessageSizer = wx.FlexGridSizer(2, 1, 0, 0) SDSCrashBitmapMessageSizer.Add(self.SDSCrashErrorIcon, 0, wx.ALL, 4) SDSCrashMessageSizer.Add(self.SDSCrashHeaderLbl, 0, wx.ALL, 4) SDSCrashMessageSizer.Add(self.SDSCrashMessageLbl, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 4) SDSCrashBitmapMessageSizer.Add(SDSCrashMessageSizer, 1, wx.EXPAND, 0) SDSCrashMainSizer.Add(SDSCrashBitmapMessageSizer, 1, wx.EXPAND, 0) SDSCrashErrorReportSizer.Add(self.SDSCrashErrorReportLbl, 0, wx.ALL, 4) SDSCrashErrorReportSizer.Add(self.SDSCrashErrorReportTxtCtrl, 0, wx.ALL | wx.EXPAND, 4) SDSCrashErrorReportingSizer.Add(self.SDSCrashErrorReportingInstructionsLbl, 0, wx.ALL | wx.EXPAND, 4) SDSCrashErrorReportingSizer.Add(self.SDSCrashErrorReportingURL, 0, wx.ALL | wx.EXPAND, 4) SDSCrashErrorReportSizer.Add(SDSCrashErrorReportingSizer, 1, wx.EXPAND, 0) self.SDSCrashErrorReportPanel.SetSizer(SDSCrashErrorReportSizer) SDSCrashErrorReportSizer.AddGrowableRow(1) SDSCrashErrorReportSizer.AddGrowableCol(0) #SDSCrashMainSizer.Add(self.SDSCrashErrorReportPanel, 1, wx.EXPAND, 0) SDSCrashMainSizer.Add(self.SDSCrashErrorReportCP, 1, wx.EXPAND, 0) SDSCrashButtonSizer.Add(self.SDSCrashOKBtn, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 4) SDSCrashButtonSizer.AddGrowableRow(0) SDSCrashButtonSizer.AddGrowableCol(0) SDSCrashMainSizer.Add(SDSCrashButtonSizer, 1, wx.EXPAND, 0) self.SDSCrashBasePanel.SetSizer(SDSCrashMainSizer) SDSCrashBaseSizer.Add(self.SDSCrashBasePanel, 1, wx.EXPAND, 0) self.SetSizer(SDSCrashBaseSizer) SDSCrashBaseSizer.Fit(self) self.Layout() self.Centre() # end wxGlade def OnOKBtnClick(self, event): # wxGlade: SDSCrashFrame.<event_handler> self.Destroy() # end of class SDSCrashFrame if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() #SDSCrashFrameInstance = SDSCrashFrame(None, -1, traceback="") try: SDSCrashFrameInstance = SDSCrashFrame("") except: import traceback print "GAHAHHHHHHHHH FAILURE!!!!" traceback.print_exc() raw_input() app.SetTopWindow(SDSCrashFrameInstance) SDSCrashFrameInstance.Show() app.MainLoop()
Python
#!/usr/bin/env python # pyNetworkManager v1.1 - cross-platform Python network management library # Copyright (C) 2012 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Special thanks to these wonderful websites: # http://www.python-forum.org/pythonforum/viewtopic.php?f=5&t=10133 # http://pypi.python.org/pypi/WMI/#downloads # http://timgolden.me.uk/python/wmi/tutorial.html # http://timgolden.me.uk/python/wmi/cookbook.html # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216%28v=vs.85%29.aspx # http://msdn.microsoft.com/en-us/library/windows/desktop/aa394217%28v=vs.85%29.aspx # http://www.google.com/#sclient=psy-ab&hl=en&safe=active&site=&source=hp&q=wmi+network+adapter+python&pbx=1&oq=wmi+network+adapter+python&aq=f&aqi=&aql=&gs_sm=e&gs_upl=252l5148l0l5366l26l19l0l7l7l2l369l4105l1.7.7.4l26l0&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=ad65ee382c54199f&biw=1024&bih=516 # http://stackoverflow.com/questions/83756/how-to-programmatically-enable-disable-network-interfaces-windows-xp # http://stackoverflow.com/questions/7580834/script-to-change-ip-address-on-windows # http://us.generation-nt.com/answer/win32-networkadapter-wireless-help-25835992.html # http://weblogs.sqlteam.com/mladenp/archive/2010/11/04/find-only-physical-network-adapters-with-wmi-win32_networkadapter-class.aspx # http://www.google.com/search?q=python%20change%20network%20settings&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a&source=hp&channel=np # # API: # pyNM.initNM() # This initializes pyNM. Initialization includes probing for the network devices and sorting them. # pyNM.setWirelessSubnet(subnet_as_string) # This sets the subnet for the wireless NIC. # pyNM.setLANSubnet(subnet_as_string) # This sets the subnet for the Ethernet NIC. # pyNM.setWirelessStaticIP(static_ip_as_string) # This sets the static IP for the wireless NIC. # pyNM.setLANStaticIP(static_ip_as_string) # This sets the static IP for the Ethernet NIC. # pyNM.setWirelessDHCP() # This enables DHCP for the wireless NIC. # pyNM.setLANDHCP() # This enables DHCP for the Ethernet NIC. # pyNM.setNICSubnet(pyNM_NIC, subnet_as_string) # This sets the subnet for a NIC specified in the arguments. # pyNM.setNICStaticIP(pyNM_NIC, static_ip_as_string) # This sets the static IP for a NIC specifid in the arguments. # pyNM.setNICDHCP(pyNM_NIC) # This enables DHCP for a NIC specified in the arguments. # pyNM.getNICs() # This returns an array of NICs detected by pyNM. # # Types: (not really) # pyNM_NetworkDevice (actual type: class with read-only properties) # The type for a network device detected by pyNM. # This type is used to identify NICs passed through the setNIC* method. # Includes: # "name" # The NIC name. This is the manufacturer's name for its NIC. # This is read-only, obviously. You'll have to hack the kernel # if you want to change the NIC name... ;) # "control" # Platform dependent handle for the device. # This handle can be used if you wish for a more fine tuned control # over the NIC. The methods for controlling this handle are NOT # cross-platform. For instance, on Windows, the handle is # controlled with the Python WMI API. This is read-only, since # pyNM depends on this to run, and it would be kinda odd to mess # around with a handle... # "sysaddr" # Platform dependent system address for the device. # This can be used if you wish to know the direct address to access # the NIC. This is NOT cross-platform. You must have your own code # to handle the address. For instance, on Windows, this uses # PNPDeviceID, which looks like PCI\VEN_NNEC&DEV_NNNN&SUBSYS_NNLNNNNN&RE # (where N is a number, L is a letter). On Linux, it might be a /dev path. # This is obviously read only, but pyNM will not be using this value anyway # for its operation. # "type" # The type of the NIC. Can either be "wireless" or "ethernet." # This is obviously read only, but pyNM will not be using this value anyway # for its operation. # Methods: # getName() # Returns the name of the NIC. # getControlHandle() # Returns the platform dependent handle for the device. # This is the method equivalent to the read-only type element "control." # See the above documentation for details. # getSysAddr() # Returns the platform dependent system address for the device. # This is the method equivalent to the read-only type element "sysaddr." # See the above documentation for details. # getType() # Returns the type of the NIC. Can either be "wireless" or "ethernet." # This is the method equivalent to the read-only type element "type." # ## READ-ONLY PYTHON ATTRIBUTES: # ## http://bright-green.com/blog/2004_06_03/read_only_python_attributes.html # ## http://devinfee.com/blog/2010/11/07/so-you-want-some-read-only-python-vars/ # import sys # TODO: Only load when class loads if sys.platform == 'win32': # Load the Python modules import wmi import pythoncom # Variables # Version - don't change. pyNM_VERSION = "1.1" # Error flags # Error in the pyNM library code pyNM_ERROR_BUG = 1 # Error in the pyNM client's code pyNM_ERROR_CLIENT = 2 # Error in the system (i.e. connection fails, system problems, etc.) pyNM_ERROR_SYSTEM = 3 # That's... probably all of the errors for now. :P # When more features are added later, more error flags will suffice. # pyNetworkManager error class # TODO: multiple flag support class pyNMError(Exception): """Exception raised for errors in the input. Attributes: errMsg: [ARG - required] Explanation of the error. errFlag: [ARG - required] A flag indicating what kind of pyNM error this is. sysErrNum: [ARG - required] The platform dependent error number. Platform specific error numbers are parsed and translated into more portable error flags. exception: [ARG - optional] Python exception that caused this error. IsSystemError: Boolean that determines whether the error was a system related error or not. IsPermissionError: Boolean that determines whether the error was a permission error or not. This is a subset of the system error. IsClientError: Boolean that determines whether the error was a developer (client coding) error or not. IsLibraryError: Boolean that determines whether the error was a library error or not (library runtime error unrelated to the user/client). IsUnknownError: Boolean that determines whether the error was an unknown error or not. """ # By default, sysErrNum is 0 unless there's a use for it, in which it will be set. def __init__(self, errMsg, errFlag, sysErrNum = 0, exception = ""): # Bind the variables (not really, more like copy) to the class self.errMsg = errMsg self.errFlag = errFlag self.sysErrNum = sysErrNum self.exception = exception # Detailed error processing if self.errFlag == pyNM_ERROR_SYSTEM: if sys.platform == 'win32': # Check to see if this is a WMI permission error or not # The error code is actually -2147217405, but... if self.sysErrNum < 0: self.IsPermissionError = True else: self.IsPermissionError = False else: # No other platforms implemented yet, so just assume that it isn't special. self.IsPermissionError = False self.IsSystemError = True self.IsUnknownError = False self.IsClientError = False self.IsLibraryError = False elif self.errFlag == pyNM_ERROR_CLIENT: # Software developer's error (the client of this library) self.IsUnknownError = False self.IsClientError = True self.IsPermissionError = False self.IsSystemError = False self.IsLibraryError = False elif self.errFlag == pyNM_ERROR_BUG: # This code's error (library) self.IsUnknownError = False self.IsClientError = False self.IsPermissionError = False self.IsSystemError = False self.IsLibraryError = True else: # Oh my! An UNKNOWN error! GAHHHHHHHHHHHH self.IsUnknownError = True self.IsClientError = False self.IsPermissionError = False self.IsSystemError = False # This error boolean may change in the future - does an unknown error count # as a bug? self.IsLibraryError = False Exception.__init__(self, errMsg) # pyNetworkManager main class # This class serves as a wrapper/bootstapper for the # platform specific pyNM classes. class pyNM: def __init__(self, platform = None): # Some self-advertisement print "[pyNM] "+"pyNetworkManager v"+str(pyNM_VERSION) bar = "" for i in range(0, len("pyNetworkManager v"+str(pyNM_VERSION)) + 1): bar = bar + "=" print "[pyNM] "+bar print "[pyNM] "+"Copyright (C) 2012 River Hill Robotics Team (Albert H.)\n"+"[pyNM] " # Give this class a version variable self.version = pyNM_VERSION if platform is not None: if platform not in ['win32', 'linux2', 'darwin']: raise pyNMError("Either the platform specified is invalid or it isn't supported at this time.", pyNM_ERROR_CLIENT) print "[pyNM] WARNING: Platform choice forced to "+platform+"." else: platform = sys.platform print "[pyNM] Platform: "+platform if platform == 'win32': # Windows! Yay! pyNM_Win32_Handle = pyNM_Win32() self.initNM = pyNM_Win32_Handle.initNM self.setWirelessSubnet = pyNM_Win32_Handle.setWirelessSubnet self.setLANSubnet = pyNM_Win32_Handle.setLANSubnet self.setWirelessStaticIP = pyNM_Win32_Handle.setWirelessStaticIP self.setLANStaticIP = pyNM_Win32_Handle.setLANStaticIP self.setWirelessDHCP = pyNM_Win32_Handle.setWirelessDHCP self.setLANDHCP = pyNM_Win32_Handle.setLANDHCP self.setNICSubnet = pyNM_Win32_Handle.setNICSubnet self.setNICStaticIP = pyNM_Win32_Handle.setNICStaticIP self.setNICDHCP = pyNM_Win32_Handle.setNICDHCP self.getNICs = pyNM_Win32_Handle.getNICs self.setWirelessStaticIPAndSubnet = pyNM_Win32_Handle.setWirelessStaticIPAndSubnet self.setLANStaticIPAndSubnet = pyNM_Win32_Handle.setLANStaticIPAndSubnet self.setNICStaticIPAndSubnet = pyNM_Win32_Handle.setNICStaticIPAndSubnet self._disableRefresh = pyNM_Win32_Handle._disableRefresh elif platform == 'linux2': # Linux! Yay! pyNM_Linux2_Handle = pyNM_Linux2() self.initNM = pyNM_Linux2_Handle.initNM elif platform == 'darwin': # Mac OS X... eww. (Also OpenDarwin, if anyone uses that.) pyNM_Darwin_Handle = pyNM_Darwin() self.initNM = pyNM_Darwin_Handle.initNM print "[pyNM] Platform wrapper setup complete." def getVersion(self): return pyNM_VERSION class pyNM_Win32: # NOTE: # When we print about errors, we are using str(res), even though the actual error number # is stored in res[0]. Why? We don't know Microsoft's WMI API well enough yet to know # if the WMI API returns multiple error codes or not. We hope this isn't the case, # but we're printing the values to be sure. Please report any multiple value error codes # if you find one! def __init__(self): # Do some initialization! print "[pyNM] [pyNM_Win32] Initializing..." # Run this for threading pythoncom.CoInitialize() self.disableRefresh = False print "[pyNM] [pyNM_Win32] Welcome to pyNM for the win32 platform!" def _disableRefresh(self, disabled = True): if disabled == True: self.disableRefresh = True else: self.disableRefresh = False # Process queue print "[pyNM] [pyNM_Win32] Refreshing all NIC network configurations..." # DIRTY HACK - TODO: replace by using existing handles and then running refresh self.initNM() def _getWin32NetAdapConfig(self, nic_handle): # Kinda odd that PNPDeviceID isn't shared... but MACAddress is :P nacs = nic_handle.associators(wmi_result_class="Win32_NetworkAdapterConfiguration") if len(nacs) == 0: print "[pyNM] [pyNM_Win32._getWin32NetAdapConfig] Failed to find Win32_NetworkAdapterConfiguration equivalent to NIC handle" raise pyNMError("Failed to find Win32_NetworkAdapterConfiguration equivalent to NIC handle", pyNM_ERROR_SYSTEM) if len(nacs) > 1: print "[pyNM] [pyNM_Win32._getWin32NetAdapConfig] Failed to find exact Win32_NetworkAdapterConfiguration equivalent to NIC handle (got "+str(len(nacs))+" entries)" raise pyNMError("Failed to find exact Win32_NetworkAdapterConfiguration equivalent to NIC handle (got "+str(len(nacs))+" entries)", pyNM_ERROR_SYSTEM) # Everything's fine if there's no errors raised, so return the only entry in the array return nacs[0] def _refreshWin32NetAdapConfig(self, nicac_handle): # This refreshes the Win32_NetworkAdapterConfiguration class to reflect any changes # Very hacky - we're basically getting the associator Win32_NetworkAdapter, then getting # the associator of that class to hop back to Win32_NetworkAdapterConfig. # There's probably a better way to do this, but... print "[pyNM] [pyNM_Win32._refreshWin32NetAdapConfig] Refreshing network configuration class..." if self.disableRefresh == True: print "[pyNM] [pyNM_Win32._refreshWin32NetAdapConfig] Refreshing disabled by client, queueing for later." return nacs = nicac_handle.associators(wmi_result_class="Win32_NetworkAdapter") if len(nacs) == 0: print "[pyNM] [pyNM_Win32._refreshWin32NetAdapConfig] Failed to find Win32_NetworkAdapterConfiguration equivalent to NIC handle" raise pyNMError("Failed to find Win32_NetworkAdapterConfiguration equivalent to NIC handle", pyNM_ERROR_SYSTEM) if len(nacs) > 1: print "[pyNM] [pyNM_Win32._refreshWin32NetAdapConfig] Failed to find exact Win32_NetworkAdapterConfiguration equivalent to NIC handle (got "+str(len(nacs))+" entries)" raise pyNMError("Failed to find exact Win32_NetworkAdapterConfiguration equivalent to NIC handle (got "+str(len(nacs))+" entries)", pyNM_ERROR_SYSTEM) # Everything's fine if there's no errors raised, so find the associator from the only entry in the array nacacs = nacs[0].associators(wmi_result_class="Win32_NetworkAdapterConfiguration") if len(nacacs) == 0: print "[pyNM] [pyNM_Win32._refreshWin32NetAdapConfig] Failed to find Win32_NetworkAdapterConfiguration equivalent to NIC handle" raise pyNMError("Failed to find Win32_NetworkAdapterConfiguration equivalent to NIC handle", pyNM_ERROR_SYSTEM) if len(nacacs) > 1: print "[pyNM] [pyNM_Win32._refreshWin32NetAdapConfig] Failed to find exact Win32_NetworkAdapterConfiguration equivalent to NIC handle (got "+str(len(nacs))+" entries)" raise pyNMError("Failed to find exact Win32_NetworkAdapterConfiguration equivalent to NIC handle (got "+str(len(nacs))+" entries)", pyNM_ERROR_SYSTEM) # Everything's fine if there's no errors raised, so return the only entry in the array return nacacs[0] def _getWirelessNICs(self): return self.nic_wlan_array def _getLANNICs(self): return self.nic_lan_array def initNM(self): print "[pyNM] [pyNM_Win32.initNM] Initializing pyNM for the win32 platform..." wmi_instance = wmi.WMI() self.wmi_instance = wmi_instance network_adapters = wmi_instance.Win32_NetworkAdapter() if len(network_adapters) == 0: raise pyNMError("No network adapters found! (Maybe you don't have enough permissions?)", pyNM_ERROR_SYSTEM) physical_adapters=[] try: for adapter in network_adapters: if (adapter.Manufacturer != 'Microsoft' and adapter.PNPDeviceID != None and len(adapter.PNPDeviceID) >= 4 and adapter.PNPDeviceID[:4] != 'ROOT'): physical_adapters.append(adapter) # NetConnectionID is unreliable, BUT we can use it as reinforcement. (or not :P) # Best to use the Name print "[pyNM] [pyNM_Win32.initNM] HW Network Adapter: name="+str(adapter.Name)+", type="+str(adapter.AdapterType)+", PNPDeviceID="+str(adapter.PNPDeviceID)+", NetConnectionID="+str(adapter.NetConnectionID) except: import traceback print "[pyNM] [pyNM_Win32.initNM] Failed to filter network devices" traceback.print_exc() raise pyNMError("Failed to filter network devices", pyNM_ERROR_SYSTEM) # Now categorize into wireless and LAN (Ethernet) NICs wireless_adapters=[] lan_adapters=[] try: for adapter in physical_adapters: # Do a case-insensitive search! if (str(adapter.Name).lower().find('wireless') != -1) or (str(adapter.Name).lower().find('wifi') != -1) or (str(adapter.Name).lower().find('wi-fi') != -1): print "[pyNM] [pyNM_Win32.initNM] Identified '"+str(adapter.Name)+"' as a wireless NIC" wireless_adapters.append(adapter) elif (str(adapter.Name).lower().find('ethernet') != -1): print "[pyNM] [pyNM_Win32.initNM] Identified '"+str(adapter.Name)+"' as a Ethernet NIC" lan_adapters.append(adapter) else: # Assume it's LAN print "[pyNM] [pyNM_Win32.initNM] Identified '"+str(adapter.Name)+"' as a Ethernet NIC" print "[pyNM] [pyNM_Win32.initNM] ** WARNING: This may not be accurate." except: import traceback print "[pyNM] [pyNM_Win32.initNM] Failed to categorize network devices" traceback.print_exc() raise pyNMError("Failed to filter categorize devices", pyNM_ERROR_SYSTEM) nic_array = [] nic_wlan_array = [] nic_lan_array = [] try: for wireless_adapter in wireless_adapters: nic_handle = pyNM_NetworkDevice(str(wireless_adapter.Name), [wireless_adapter, self._getWin32NetAdapConfig(wireless_adapter)], wireless_adapter.PNPDeviceID, "wireless") nic_array.append(nic_handle) nic_wlan_array.append(nic_handle) for lan_adapter in lan_adapters: nic_handle = pyNM_NetworkDevice(str(lan_adapter.Name), [lan_adapter, self._getWin32NetAdapConfig(lan_adapter)], lan_adapter.PNPDeviceID, "ethernet") nic_array.append(nic_handle) nic_lan_array.append(nic_handle) self.nic_array = nic_array self.nic_wlan_array = nic_wlan_array self.nic_lan_array = nic_lan_array except: import traceback print "[pyNM] [pyNM_Win32.initNM] Failed to create device array" traceback.print_exc() raise pyNMError("Failed to create device array", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) print "[pyNM] [pyNM_Win32.initNM] Initilization complete!" def setWirelessSubnet(self, subnet): try: for NIC in self.nic_wlan_array: res = NIC.control[1].EnableStatic([unicode(NIC.control[1].IPAddress[0])], [unicode(subnet)]) print "[pyNM] [pyNM_Win32.setWirelessSubnet] ** Result code: "+str(res) if res[0] != 0: print "[pyNM] [pyNM_Win32.setWirelessSubnet] Failed to set wireless subnet (status code "+str(res)+")" raise pyNMError("Failed to set wireless subnet (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setWirelessSubnet] Failed to set wireless subnet" traceback.print_exc() raise pyNMError("Failed to set wireless subnet", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setLANSubnet(self, subnet): try: for NIC in self.nic_lan_array: res = NIC.control[1].EnableStatic([unicode(NIC.control[1].IPAddress[0])], [unicode(subnet)]) if res[0] != 0: print "[pyNM] [pyNM_Win32.setLANSubnet] Failed to set LAN subnet (status code "+str(res)+")" raise pyNMError("Failed to set LAN subnet (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setLANSubnet] Failed to set LAN subnet" traceback.print_exc() raise pyNMError("Failed to set LAN subnet", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setNICSubnet(self, nic, subnet): try: res = nic.control[1].EnableStatic([unicode(nic.control[1].IPAddress[0])], [unicode(subnet)]) if res[0] != 0: print "[pyNM] [pyNM_Win32.setNICSubnet] Failed to set NIC subnet (status code "+str(res)+")" raise pyNMError("Failed to set NIC subnet (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) nic.control[1] = self._refreshWin32NetAdapConfig(nic.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setNICSubnet] Failed to set NIC subnet" traceback.print_exc() raise pyNMError("Failed to set NIC subnet", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setWirelessStaticIP(self, staticip): try: for NIC in self.nic_wlan_array: #print "[pyNM] [pyNM_Win32.setWirelessStaticIP] DEBUG | Dev control contents: "+str(NIC.control[0]) #print "[pyNM] [pyNM_Win32.setWirelessStaticIP] DEBUG | Dev control type: "+str(type(NIC.control[0])) #print "[pyNM] [pyNM_Win32.setWirelessStaticIP] DEBUG | Cfg control contents: "+str(NIC.control[1]) #print "[pyNM] [pyNM_Win32.setWirelessStaticIP] DEBUG | Cfg control type: "+str(type(NIC.control[1])) # Windows is really stupid... they specify strings as args, but instead ask for string *arrays* # ARRRRRRRRRRRGGHHHHHHHH !@#$%^&* print "[pyNM] [pyNM_Win32.setWirelessStaticIP] Setting static IP to "+str([unicode(staticip)])+" and IPSubnet to "+str(NIC.control[1].IPSubnet) res = NIC.control[1].EnableStatic([unicode(staticip)], [unicode(NIC.control[1].IPSubnet[0])]) print "[pyNM] [pyNM_Win32.setWirelessStaticIP] ** Result code: "+str(res) if res[0] != 0: print "[pyNM] [pyNM_Win32.setNICWirelessIP] Failed to set wireless static IP (status code "+str(res)+")" raise pyNMError("Failed to set wireless static IP (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setWirelessStaticIP] Failed to set wireless static IP" traceback.print_exc() raise pyNMError("Failed to set wireless static IP", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setLANStaticIP(self, staticip): try: for NIC in self.nic_lan_array: NIC.control[1].EnableStatic([unicode(staticip)], [unicode(NIC.control[1].IPSubnet[0])]) if res[0] != 0: print "[pyNM] [pyNM_Win32.setLANStaticIP] Failed to set LAN static IP (status code "+str(res)+")" raise pyNMError("Failed to set LAN static IP (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setLANStaticIP] Failed to set LAN static IP" traceback.print_exc() raise pyNMError("Failed to set LAN static IP", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setNICStaticIP(self, nic, staticip): try: nic.control[1].EnableStatic([unicode(staticip)], [unicode(NIC.control[1].IPSubnet[0])]) if res[0] != 0: print "[pyNM] [pyNM_Win32.setNICStaticIP] Failed to set NIC static IP (status code "+str(res)+")" raise pyNMError("Failed to set NIC static IP (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) nic.control[1] = self._refreshWin32NetAdapConfig(nic.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setNICStaticIP] Failed to set NIC static IP" traceback.print_exc() raise pyNMError("Failed to set NIC static IP", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setWirelessStaticIPAndSubnet(self, staticip, subnet): try: for NIC in self.nic_wlan_array: res = NIC.control[1].EnableStatic([unicode(staticip)], [unicode(subnet)]) print "[pyNM] [pyNM_Win32.setWirelessStaticIPAndSubnet] ** Result code: "+str(res) if res[0] != 0: print "[pyNM] [pyNM_Win32.setWirelessStaticIPAndSubnet] Failed to set wireless static IP and subnet (status code "+str(res)+")" raise pyNMError("Failed to set wireless static IP and subnet (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setWirelessStaticIPAndSubnet] Failed to set wireless static IP and subnet" traceback.print_exc() raise pyNMError("Failed to set wireless static IP and subnet", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setLANStaticIPAndSubnet(self, staticip, subnet): try: for NIC in self.nic_lan_array: res = NIC.control[1].EnableStatic([unicode(staticip)], [unicode(subnet)]) if res[0] != 0: print "[pyNM] [pyNM_Win32.setLANStaticIPAndSubnet] Failed to set LAN static IP and subnet (status code "+str(res)+")" raise pyNMError("Failed to set LAN static IP and subnet (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setLANStaticIPAndSubnet] Failed to set LAN static IP and subnet" traceback.print_exc() raise pyNMError("Failed to set LAN static IP and subnet", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setNICStaticIPAndSubnet(self, nic, staticip, subnet): try: res = nic.control[1].EnableStatic([unicode(staticip)], [unicode(subnet)]) if res[0] != 0: print "[pyNM] [pyNM_Win32.setNICStaticIPAndSubnet] Failed to set NIC static IP and subnet (status code "+str(res)+")" raise pyNMError("Failed to set NIC static IP and subnet (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) nic.control[1] = self._refreshWin32NetAdapConfig(nic.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setNICStaticIPAndSubnet] Failed to set NIC static IP and subnet" traceback.print_exc() raise pyNMError("Failed to set NIC static IP and subnet", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setWirelessDHCP(self): try: for NIC in self.nic_wlan_array: res = NIC.control[1].EnableDHCP() if res[0] != 0: print "[pyNM] [pyNM_Win32.setWirelessDHCP] Failed to set wireless DHCP (status code "+str(res)+")" raise pyNMError("Failed to set wireless DHCP (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setWirelessDHCP] Failed to set wireless DHCP" traceback.print_exc() raise pyNMError("Failed to set wireless DHCP", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setLANDHCP(self): try: for NIC in self.nic_lan_array: res = NIC.control[1].EnableDHCP() if res[0] != 0: print "[pyNM] [pyNM_Win32.setLANDHCP] Failed to set LAN DHCP (status code "+str(res)+")" raise pyNMError("Failed to set LAN DHCP (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) NIC.control[1] = self._refreshWin32NetAdapConfig(NIC.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setLANDHCP] Failed to set LAN DHCP" traceback.print_exc() raise pyNMError("Failed to set LAN DHCP", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def setNICDHCP(self, nic): try: res = nic.control[1].EnableDHCP() if res[0] != 0: print "[pyNM] [pyNM_Win32.setNICDHCP] Failed to set NIC DHCP (status code "+str(res)+")" raise pyNMError("Failed to set NIC DHCP (status code "+str(res)+")", pyNM_ERROR_SYSTEM, res[0]) nic.control[1] = self._refreshWin32NetAdapConfig(nic.control[1]) except pyNMError: raise except: import traceback print "[pyNM] [pyNM_Win32.setNICDHCP] Failed to set NIC DHCP" traceback.print_exc() raise pyNMError("Failed to set NIC DHCP", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def getNICs(self): return self.nic_array class pyNM_Linux2: def __init__(self): # Nothing print "[pyNM] [pyNM_Linux2] Welcome to pyNM for the Linux (linux2) platform!" raise pyNMError("Linux2 platform not implemented.", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def initNM(self): print "[pyNM] [pyNM_Linux2.initNM] Initializing pyNM for the Linux (linux2) platform..." class pyNM_Darwin: def __init__(self): # Nothing print "[pyNM] [pyNM_Darwin] Welcome to pyNM for the Mac (darwin) platform!" raise pyNMError("Darwin platform not implemented.", pyNM_ERROR_BUG, 0, "".join(traceback.format_exc())) def initNM(self): print "[pyNM] [pyNM_Darwin.initNM] Initializing pyNM for the Mac (darwin) platform..." class pyNM_NetworkDevice: def __init__(self, name, control, sysaddr, type): # Set up class struct self.name = name self.control = control self.sysaddr = sysaddr self.type = type #print "[pyNM] pyNM_NetworkDevice type initialized with name="+str(name)+", control="+str(control)+", sysaddr="+str(sysaddr)+", type="+str(type) def getName(self): return self.name def getControlHandle(self): return self.control def getSysAddr(self): return self.sysaddr def getType(self): return self.type if __name__ == "__main__": wmi_instance = wmi.WMI() network_adapters = wmi_instance.Win32_NetworkAdapter() index = 0 if len(network_adapters) == 0: print "ERROR: No network adapters found! (Maybe you don't have enough permissions?)" sys.exit(1) '''for adapter in network_adapters: print "Network adapter "+str(index)+" type: "+str(adapter.AdapterType) print "Network adapter "+str(index)+" name: "+str(adapter.Name) print "Network adapter "+str(index)+" mfr: "+str(adapter.Manufacturer) index += 1''' physical_adapters=[] try: for adapter in network_adapters: if (adapter.Manufacturer != 'Microsoft' and adapter.PNPDeviceID != None and len(adapter.PNPDeviceID) >= 4 and adapter.PNPDeviceID[:4] != 'ROOT'): physical_adapters.append(adapter) # NetConnectionID is unreliable, BUT we can use it as reinforcement. (or not :P) # Best to use the Name print "HW Network Adapter: name="+str(adapter.Name)+", type="+str(adapter.AdapterType)+", PNPDeviceID="+str(adapter.PNPDeviceID)+", NetConnectionID="+str(adapter.NetConnectionID) except: import traceback print "Failed to filter network devices" traceback.print_exc() raw_input()
Python
#!/usr/bin/env python # SpringDS v1.0 Beta 1 - a (cross-platform?) wrapper for the FRC Driver Station # Copyright (C) 2012 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This is the SpringDS Settings manager. # # -*- coding: iso-8859-15 -*- # generated by wxGlade 0.6.5 (standalone edition) on Wed Mar 21 14:30:52 2012 import wx import wx.lib.filebrowsebutton as filebrowse try: from agw import hyperlink as hl except ImportError: # if it's not there locally, try the wxPython lib. import wx.lib.agw.hyperlink as hl import SpringDSConfig import SpringDSCrash # begin wxGlade: extracode # end wxGlade # MsgBox - shows a message box. # Types: wx.ICON_INFORMATION, wx.ICON_EXCLAMATION, wx.ICON_ERROR, wx.ICON_ERROR def MsgBox(text, title, type, parent=None): dlg = wx.MessageDialog(parent, text, title, wx.OK | type) dlg.ShowModal() def ErrorBox(traceback): SDSCrashFrameInstance = SpringDSCrash.SDSCrashFrame(traceback) #app.SetTopWindow(SDSCrashFrameInstance) SDSCrashFrameInstance.MakeModal() SDSCrashFrameInstance.ShowModal() class SpringDSSettingsFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: SpringDSSettingsFrame.__init__ kwds["style"] = wx.CAPTION | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.SIMPLE_BORDER wx.Frame.__init__(self, *args, **kwds) self.SDSSBasePanel = wx.Panel(self, -1) self.SDSSHeaderImage = wx.StaticBitmap(self.SDSSBasePanel, -1, wx.Bitmap("SpringDSSettingsHeader.png", wx.BITMAP_TYPE_ANY)) self.SDSSNotebook = wx.Notebook(self.SDSSBasePanel, -1, style=0) self.SDSSNetworkPane = wx.Panel(self.SDSSNotebook, -1) self.SDSSStaticIPLbl = wx.StaticText(self.SDSSNetworkPane, -1, "Static IP:") self.SDSSStaticIPTxtCtrl = wx.TextCtrl(self.SDSSNetworkPane, -1, SpringDSConfig.getCfgAbsStaticIP()) self.SDSSStaticIPTeamNumCheckbox = wx.CheckBox(self.SDSSNetworkPane, -1, "Use FRC team number to determine static IP") self.SDSSubnetLbl = wx.StaticText(self.SDSSNetworkPane, -1, "Subnet:") self.SDSSubnetTxtCtrl = wx.TextCtrl(self.SDSSNetworkPane, -1, SpringDSConfig.getCfgSubnet()) self.SDSSConnectionTypeLbl = wx.StaticText(self.SDSSNetworkPane, -1, "Connection Type:") self.SDSSConnectionTypeRadioBox = wx.RadioBox(self.SDSSNetworkPane, -1, "", choices=["LAN", "Wireless", "Custom NIC Selection..."], majorDimension=0, style=wx.RA_SPECIFY_ROWS) self.SDSSConnectionTypeRadioBox.Bind(wx.EVT_RADIOBOX, self.OnChangeConnectionType) self.SDSSNICSelectComboBox = wx.ComboBox(self.SDSSNetworkPane, -1, choices=["NIC #0"], style=wx.CB_DROPDOWN | wx.CB_DROPDOWN) self.SDSSNICSelectScanBtn = wx.Button(self.SDSSNetworkPane, -1, "Scan") self.SDSSFRCTeamNumLbl = wx.StaticText(self.SDSSNetworkPane, -1, "FRC Team Number:") self.SDSSFRCTeamNumTxtCtrl = wx.TextCtrl(self.SDSSNetworkPane, -1, SpringDSConfig.getCfgTeamID()) self.SDSSPathsPane = wx.Panel(self.SDSSNotebook, -1) self.SDSSFRCDSPathLbl = wx.StaticText(self.SDSSPathsPane, -1, "FRC Driver Station Path:") #self.SDSSFRCDSPathTxtBox = wx.TextCtrl(self.SDSSPathsPane, -1, "") self.SDSSFRCDSPathTxtBox = filebrowse.FileBrowseButton(self.SDSSPathsPane, -1, labelText="", initialValue = SpringDSConfig.getCfgDriverStationPath()) self.SDSSFRCDBPathLbl = wx.StaticText(self.SDSSPathsPane, -1, "FRC Dashboard Path:") #self.SDSSFRCDBPathTxtBox = wx.TextCtrl(self.SDSSPathsPane, -1, "") self.SDSSFRCDBPathTxtBox = filebrowse.FileBrowseButton(self.SDSSPathsPane, -1, labelText="", initialValue = SpringDSConfig.getCfgDashboardPath()) self.SDSSAboutPane = wx.Panel(self.SDSSNotebook, -1) self.SDSSAboutVersionLbl = wx.StaticText(self.SDSSAboutPane, -1, "SpringDS v1.0b") self.SDSSDevelopedByLbl = wx.StaticText(self.SDSSAboutPane, -1, "Developed by:") self.SDSSDeveloperLbl = wx.StaticText(self.SDSSAboutPane, -1, "Albert Huang") self.SDSSCredit2Lbl = wx.StaticText(self.SDSSAboutPane, -1, "River Hill Robotics - The Incredible Hawk - Team #4067") self.SDSSAboutWebsiteLbl = wx.StaticText(self.SDSSAboutPane, -1, "Website:") #self.SDSSAboutURLLbl = wx.StaticText(self.SDSSAboutPane, -1, "URL") self.SDSSAboutURLLbl = hl.HyperLinkCtrl(self.SDSSAboutPane, wx.ID_ANY, "http://code.google.com/p/frcbot4067/", URL="http://code.google.com/p/frcbot4067/") self.SDSSOKBtn = wx.Button(self.SDSSBasePanel, wx.ID_OK, "") self.SDSSOKBtn.Bind(wx.EVT_BUTTON, self.OnOKButton) self.SDSSCancelBtn = wx.Button(self.SDSSBasePanel, wx.ID_CANCEL, "") self.SDSSCancelBtn.Bind(wx.EVT_BUTTON, self.OnCancelButton) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: SpringDSSettingsFrame.__set_properties self.SetTitle("SpringDS Settings") _icon = wx.EmptyIcon() _icon.CopyFromBitmap(wx.Bitmap("SpringDSSettingsIcon.ico", wx.BITMAP_TYPE_ANY)) #self.SetIcon(_icon) self.SetIcon(wx.Icon("SpringDSSettingsIcon.ico", wx.BITMAP_TYPE_ICO, 16, 16)) self.SDSSStaticIPLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSStaticIPTeamNumCheckbox.SetValue(SpringDSConfig.getCfgTeamIP() == "1") self.SDSSubnetLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSConnectionTypeLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) if (SpringDSConfig.getCfgNICType() == 'wireless'): self.SDSSConnectionTypeRadioBox.SetSelection(1) self.SDSSNICSelectComboBox.Enable(False) self.SDSSNICSelectScanBtn.Enable(False) self.SDSSNICSelectionIndex = 1 elif (SpringDSConfig.getCfgNICType() == 'lan'): self.SDSSConnectionTypeRadioBox.SetSelection(0) self.SDSSNICSelectComboBox.Enable(False) self.SDSSNICSelectScanBtn.Enable(False) self.SDSSNICSelectionIndex = 0 elif (SpringDSConfig.getCfgNICType() == 'nic'): #self.SDSSConnectionTypeRadioBox.SetSelection(2) #self.SDSSNICSelectComboBox.Enable(True) #self.SDSSNICSelectScanBtn.Enable(True) #self.SDSSNICSelectionIndex = 2 self.SDSSConnectionTypeRadioBox.SetSelection(0) self.SDSSNICSelectComboBox.Enable(False) self.SDSSNICSelectScanBtn.Enable(False) self.SDSSNICSelectionIndex = 0 MsgBox("The custom NIC selection feature of SpringDS is currently a work in progress. Please change the custom NIC option to another one.", "Error - SpringDS Settings", wx.ICON_WARNING, self) else: raise #self.SDSSConnectionTypeRadioBox.SetSelection(0) self.SDSSNICSelectComboBox.SetSelection(-1) self.SDSSFRCTeamNumLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSFRCDSPathLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSFRCDBPathLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSAboutVersionLbl.SetBackgroundColour(wx.Colour(0, 73, 130)) self.SDSSAboutVersionLbl.SetForegroundColour(wx.Colour(255, 209, 41)) self.SDSSAboutVersionLbl.SetFont(wx.Font(16, wx.MODERN, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSDevelopedByLbl.SetBackgroundColour(wx.Colour(0, 73, 130)) self.SDSSDevelopedByLbl.SetForegroundColour(wx.Colour(255, 209, 41)) self.SDSSDevelopedByLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSDeveloperLbl.SetBackgroundColour(wx.Colour(0, 73, 130)) self.SDSSDeveloperLbl.SetForegroundColour(wx.Colour(255, 209, 41)) self.SDSSCredit2Lbl.SetBackgroundColour(wx.Colour(0, 73, 130)) self.SDSSCredit2Lbl.SetForegroundColour(wx.Colour(255, 209, 41)) self.SDSSAboutWebsiteLbl.SetBackgroundColour(wx.Colour(0, 73, 130)) self.SDSSAboutWebsiteLbl.SetForegroundColour(wx.Colour(255, 209, 41)) self.SDSSAboutWebsiteLbl.SetFont(wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) self.SDSSAboutURLLbl.SetBackgroundColour(wx.Colour(0, 73, 130)) self.SDSSAboutURLLbl.SetForegroundColour(wx.Colour(255, 209, 41)) self.SDSSAboutPane.SetBackgroundColour(wx.Colour(0, 73, 130)) self.SDSSOKBtn.SetDefault() self.SDSSBasePanel.SetBackgroundColour(wx.Colour(0, 52, 92)) # end wxGlade def __do_layout(self): # begin wxGlade: SpringDSSettingsFrame.__do_layout SDSSBaseSizer = wx.BoxSizer(wx.VERTICAL) SDSSMainSizer = wx.FlexGridSizer(3, 1, 0, 0) SDSSButtonSizer = wx.FlexGridSizer(1, 2, 0, 0) SDSSAboutSizer = wx.FlexGridSizer(3, 1, 0, 0) SDSSAboutWebsiteSizer = wx.FlexGridSizer(1, 2, 0, 0) SDSSCreditSizer = wx.FlexGridSizer(2, 1, 0, 0) SDSSCreditDevSizer = wx.FlexGridSizer(1, 2, 0, 0) SDSSPathsSizer = wx.FlexGridSizer(2, 2, 0, 0) SDSSNetworkSizer = wx.FlexGridSizer(4, 2, 0, 0) SDSSConnectionTypeSizer = wx.FlexGridSizer(2, 1, 0, 0) SDSSNICSelectSizer = wx.FlexGridSizer(1, 2, 0, 0) SDSSStaticIPSizer = wx.FlexGridSizer(2, 1, 0, 0) SDSSMainSizer.Add(self.SDSSHeaderImage, 0, 0, 0) SDSSNetworkSizer.Add(self.SDSSStaticIPLbl, 0, wx.ALL, 4) SDSSStaticIPSizer.Add(self.SDSSStaticIPTxtCtrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSStaticIPSizer.Add(self.SDSSStaticIPTeamNumCheckbox, 0, wx.ALL | wx.EXPAND, 4) SDSSStaticIPSizer.AddGrowableRow(0) SDSSStaticIPSizer.AddGrowableRow(1) SDSSStaticIPSizer.AddGrowableCol(0) SDSSNetworkSizer.Add(SDSSStaticIPSizer, 1, wx.EXPAND, 0) SDSSNetworkSizer.Add(self.SDSSubnetLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSNetworkSizer.Add(self.SDSSubnetTxtCtrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSNetworkSizer.Add(self.SDSSConnectionTypeLbl, 0, wx.ALL, 4) SDSSConnectionTypeSizer.Add(self.SDSSConnectionTypeRadioBox, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 4) SDSSNICSelectSizer.Add(self.SDSSNICSelectComboBox, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSNICSelectSizer.Add(self.SDSSNICSelectScanBtn, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSNICSelectSizer.AddGrowableRow(0) SDSSNICSelectSizer.AddGrowableCol(0) SDSSConnectionTypeSizer.Add(SDSSNICSelectSizer, 1, wx.EXPAND, 0) SDSSNetworkSizer.Add(SDSSConnectionTypeSizer, 1, wx.EXPAND, 0) SDSSNetworkSizer.Add(self.SDSSFRCTeamNumLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSNetworkSizer.Add(self.SDSSFRCTeamNumTxtCtrl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) self.SDSSNetworkPane.SetSizer(SDSSNetworkSizer) SDSSNetworkSizer.AddGrowableRow(0) SDSSNetworkSizer.AddGrowableCol(1) SDSSPathsSizer.Add(self.SDSSFRCDSPathLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSPathsSizer.Add(self.SDSSFRCDSPathTxtBox, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 4) SDSSPathsSizer.Add(self.SDSSFRCDBPathLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSPathsSizer.Add(self.SDSSFRCDBPathTxtBox, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 4) self.SDSSPathsPane.SetSizer(SDSSPathsSizer) SDSSAboutSizer.Add(self.SDSSAboutVersionLbl, 0, wx.ALL, 4) SDSSCreditDevSizer.Add(self.SDSSDevelopedByLbl, 0, wx.ALL, 4) SDSSCreditDevSizer.Add(self.SDSSDeveloperLbl, 0, wx.ALL, 4) SDSSCreditDevSizer.AddGrowableRow(0) SDSSCreditSizer.Add(SDSSCreditDevSizer, 1, wx.EXPAND, 0) SDSSCreditSizer.Add(self.SDSSCredit2Lbl, 0, wx.ALL, 4) SDSSCreditSizer.AddGrowableCol(0) SDSSAboutSizer.Add(SDSSCreditSizer, 1, wx.EXPAND, 0) SDSSAboutWebsiteSizer.Add(self.SDSSAboutWebsiteLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSAboutWebsiteSizer.Add(self.SDSSAboutURLLbl, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4) SDSSAboutWebsiteSizer.AddGrowableCol(1) SDSSAboutSizer.Add(SDSSAboutWebsiteSizer, 1, wx.EXPAND, 0) self.SDSSAboutPane.SetSizer(SDSSAboutSizer) SDSSAboutSizer.AddGrowableRow(1) SDSSAboutSizer.AddGrowableCol(0) self.SDSSNotebook.AddPage(self.SDSSNetworkPane, "Network") self.SDSSNotebook.AddPage(self.SDSSPathsPane, "Paths") self.SDSSNotebook.AddPage(self.SDSSAboutPane, "About...") SDSSMainSizer.Add(self.SDSSNotebook, 1, wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND, 4) SDSSButtonSizer.Add(self.SDSSOKBtn, 0, wx.ALL, 4) SDSSButtonSizer.Add(self.SDSSCancelBtn, 0, wx.ALL, 4) SDSSMainSizer.Add(SDSSButtonSizer, 1, wx.ALL | wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 4) self.SDSSBasePanel.SetSizer(SDSSMainSizer) SDSSMainSizer.AddGrowableRow(1) SDSSMainSizer.AddGrowableCol(0) SDSSBaseSizer.Add(self.SDSSBasePanel, 1, wx.EXPAND, 0) self.SetSizer(SDSSBaseSizer) SDSSBaseSizer.Fit(self) self.Layout() # end wxGlade def OnCancelButton(self, event): # Just exit! self.Destroy() def OnOKButton(self, event): # Save the settings! try: print "[SpringDSSettings] Saving static IP..." SpringDSConfig.setCfgAbsStaticIP(self.SDSSStaticIPTxtCtrl.GetValue()) print "[SpringDSSettings] Saving team number to IP option..." SpringDSConfig.setCfgTeamIP((self.SDSSStaticIPTeamNumCheckbox.GetValue() and "1") or "0") print "[SpringDSSettings] Saving subnet..." SpringDSConfig.setCfgSubnet(self.SDSSubnetTxtCtrl.GetValue()) print "[SpringDSSettings] Saving FRC team number..." SpringDSConfig.setCfgTeamID(self.SDSSFRCTeamNumTxtCtrl.GetValue()) print "[SpringDSSettings] Saving NIC type..." if (self.SDSSConnectionTypeRadioBox.GetSelection() == 1): print "[SpringDSSettings] Wireless" SpringDSConfig.setCfgNICType("wireless") elif (self.SDSSConnectionTypeRadioBox.GetSelection() == 0): print "[SpringDSSettings] LAN" SpringDSConfig.setCfgNICType("lan") elif (self.SDSSConnectionTypeRadioBox.GetSelection() == 2): #self.SDSSNICSelectComboBox.Enable(True) #self.SDSSNICSelectScanBtn.Enable(True) # Disabled for now. MsgBox("You're sneaky! (You should've been stopped before from selecting custom NICs.)\nThis feature of SpringDS is currently a work in progress. This option can not be selected at this time.", "Error - SpringDS Settings", wx.ICON_ERROR, self) # ...and don't save anything. else: raise print "[SpringDSSettings] Saving driver station path..." SpringDSConfig.setCfgDriverStationPath(self.SDSSFRCDSPathTxtBox.GetValue()) print "[SpringDSSettings] Saving dashboard path..." SpringDSConfig.setCfgDashboardPath(self.SDSSFRCDBPathTxtBox.GetValue()) print "[SpringDSSettings] ** Saving config file... **" SpringDSConfig.writeConfig() print "[SpringDSSettings] All done! Exiting." self.Destroy() except: import traceback ErrorBox("An error occurred while saving the SpringDS configuration. \n"+"".join(traceback.format_exc())) def OnChangeConnectionType(self, event): if (self.SDSSConnectionTypeRadioBox.GetSelection() == 1) or (self.SDSSConnectionTypeRadioBox.GetSelection() == 0): self.SDSSNICSelectComboBox.Enable(False) self.SDSSNICSelectScanBtn.Enable(False) self.SDSSNICSelectionIndex = self.SDSSConnectionTypeRadioBox.GetSelection() elif (self.SDSSConnectionTypeRadioBox.GetSelection() == 2): #self.SDSSNICSelectComboBox.Enable(True) #self.SDSSNICSelectScanBtn.Enable(True) # Disabled for now. MsgBox("This feature of SpringDS is currently a work in progress. This option can not be selected at this time.", "Error - SpringDS Settings", wx.ICON_ERROR, self) self.SDSSConnectionTypeRadioBox.SetSelection(self.SDSSNICSelectionIndex) else: raise # end of class SpringDSSettingsFrame if __name__ == "__main__": try: SpringDSConfig.initConfig() except: MsgBox("Couldn't load SpringDS configuration!", "Error - SpringDS", wx.ICON_ERROR) import traceback ErrorBox("".join(traceback.format_exc())) exit() try: app = wx.PySimpleApp(0) wx.InitAllImageHandlers() SpringDSSettingsFrameInstance = SpringDSSettingsFrame(None, -1, "") app.SetTopWindow(SpringDSSettingsFrameInstance) SpringDSSettingsFrameInstance.Show() app.MainLoop() except: import traceback ErrorBox("".join(traceback.format_exc())) exit()
Python
#!/usr/bin/env python # SpringDS v1.0 Beta 1 - a (cross-platform?) wrapper for the FRC Driver Station # Copyright (C) 2012 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # This is the SpringDS Panel, a lighter and (probably) more useful version # of SpringDS. It allows complete, single-click control of the network settings, # great for coding work... and of course, launching the driver station. # # -*- coding: iso-8859-15 -*- # generated by wxGlade 0.6.5 (standalone edition) on Sun Mar 25 19:43:09 2012 import wx import os, sys import traceback import pyNM import threading import time import subprocess import psutil import SpringDSCrash import SpringDSConfig #import random if sys.platform == 'win32': import win32api # Variables # Version SPRINGDS_VERSION = "1.0 beta 1" # Functions # MsgBox - shows a message box. # Types: wx.ICON_INFORMATION, wx.ICON_EXCLAMATION, wx.ICON_ERROR, wx.ICON_ERROR def MsgBox(text, title, type, parent=None): dlg = wx.MessageDialog(parent, text, title, wx.OK | type) dlg.ShowModal() def ErrorBox(traceback): SDSCrashFrameInstance = SpringDSCrash.SDSCrashFrame(traceback) #app.SetTopWindow(SDSCrashFrameInstance) SDSCrashFrameInstance.MakeModal() SDSCrashFrameInstance.ShowModal() SDSCrashFrameInstance.MakeModal(False) # Define notification event for thread completion updates EVT_UPDATE_STATUS_ID = wx.NewId() # Define notification event for window termination trigger EVT_TERMINATE_WINDOW_ID = wx.NewId() # Define notification event for thread progress updates EVT_UPDATE_PROGRESS_ID = wx.NewId() # Define notification event for showing an error box EVT_ERROR_NOTIFY_ID = wx.NewId() # Define notification event for turning the button back to normal EVT_RESET_LAUNCHER_BTN_ID = wx.NewId() def EVT_UPDATE_STATUS(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_UPDATE_STATUS_ID, func) def EVT_TERMINATE_WINDOW(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_TERMINATE_WINDOW_ID, func) def EVT_UPDATE_PROGRESS(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_UPDATE_PROGRESS_ID, func) def EVT_ERROR_NOTIFY(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_ERROR_NOTIFY_ID, func) def EVT_RESET_LAUNCHER_BTN(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESET_LAUNCHER_BTN_ID, func) class IOStatusParser: def __init__(self, updatewin, oldio): self.updatewin = updatewin self.oldio = oldio def write(self, text): if text.strip() != "": partn = 0 finaltext = "" for part in text.strip().split(" "): partn += 1 if part != "": if (part[0] == '[') and (part[-1] == ']'): # Check if (partn == 2) and (part == "[SpringDSFrame.on_paint]"): finaltext = "" break else: finaltext = " ".join(text.strip().split(" ")[partn-1:]) break wx.PostEvent(self.updatewin, UpdateStatusEvent(finaltext)) self.oldio.write(text) '''def close(self): self.logfile.write(" Log Session End - "+date("%Y-%m-%d %H:%M:%S")+" **\n") self.logfile.close()''' class UpdateStatusEvent(wx.PyEvent): """Event that carries the status update data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_UPDATE_STATUS_ID) self.data = data class TerminateWindowEvent(wx.PyEvent): """Event that tells the window thread to exit.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_TERMINATE_WINDOW_ID) self.data = data class UpdateProgressEvent(wx.PyEvent): """Event that carries the progress update data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_UPDATE_PROGRESS_ID) self.data = data class ErrorNotifyEvent(wx.PyEvent): """Event that tells the window something bad happened.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_ERROR_NOTIFY_ID) self.data = data class ResetLauncherBtnEvent(wx.PyEvent): """Event that tells the window something bad happened.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_RESET_LAUNCHER_BTN_ID) self.data = data # This is the slave daemon - to prevent GUI lockups when we do network-y stuff, # we send commands to this daemon, and the daemon sends signals to the GUI in response # to update progress. class SpringDS_NM_Slave(threading.Thread): def __init__(self, updatewin): threading.Thread.__init__(self) self.updatewin = updatewin self.stopNow = False self.oldstdout = sys.stdout self.pyNMHandle = None self.errBoxOpen = True self.action = "" self.curAction = "" self.networkInFRCMode = False self.pyNMInited = False self.actionRan = False def killSlave(self): # Terminate this thread self.stopNow = True def checkKill(self): # Check for flag if self.stopNow == True: self.doKill() def checkActionDiff(self): # Check to see if the GUI requested something different, and break if needed! if self.action != self.curAction: return True # Optimization: keep it outside of if loop instead of putting it into the # else clause - exercise for the reader as to why this works, and is faster. return False def initPyNM(self): if self.pyNMInited == False: wx.PostEvent(self.updatewin, UpdateProgressEvent(5)) print "[SpringDSPanel] Loading pyNetworkManager..." self.pyNMHandle = pyNM.pyNM() self.checkKill() print "[SpringDSPanel] Using pyNetworkManager version "+str(self.pyNMHandle.getVersion()) print "[SpringDSPanel] Initializing pyNetworkManager..." wx.PostEvent(self.updatewin, UpdateProgressEvent(10)) self.pyNMHandle.initNM() self.checkKill() self.pyNMInited = True def setAction(self, cmd): self.action = cmd if cmd == "TerminateDS": for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Driver Station.exe": proc.terminate() self.checkKill() def setErrBoxClose(self): self.errBoxOpen = False def doKill(self): # Shut down pyNM wx.PostEvent(self.updatewin, UpdateProgressEvent(33)) print "[SpringDSPanel] Terminating SpringDS and the Driver Station..." for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Dashboard.exe": proc.terminate() if proc.name == "Driver Station.exe": proc.terminate() wx.PostEvent(self.updatewin, ResetLauncherBtnEvent(None)) #print "[SpringDSPanel] Pausing for 3 seconds..." time.sleep(1) try: if self.pyNMHandle != None: if SpringDSConfig.getCfgNICType() == "wireless": print "[SpringDSPanel] Resetting wireless NIC to DHCP..." self.pyNMHandle.setWirelessDHCP() elif SpringDSConfig.getCfgNICType() == "lan": print "[SpringDSPanel] Resetting LAN NIC to DHCP..." self.pyNMHandle.setLANDHCP() except: # Allow termination pass wx.PostEvent(self.updatewin, UpdateProgressEvent(66)) wx.PostEvent(self.updatewin, UpdateProgressEvent(99)) print "[SpringDSPanel] Restoring I/O..." print "[SpringDSPanel] Exiting..." time.sleep(1.5) sys.stdout = self.oldstdout wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) exit() def run(self): # Hook the output to our little I/O class so we can catch and interpret it! out2status = IOStatusParser(self.updatewin, sys.stdout) sys.stdout = out2status self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(50)) try: SpringDSConfig.initConfig() print "[SpringDSPanel] Ready." wx.PostEvent(self.updatewin, UpdateProgressEvent(0)) except: MsgBox("Couldn't load SpringDS configuration!", "Error - SpringDS", wx.ICON_ERROR) import traceback wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) exit() # Now we place this into a while loop to process actions. while self.stopNow == False: #print "DEBUG: Loop outside" self.checkKill() self.curAction = self.action while 1: time.sleep(0.1) self.checkKill() if self.checkActionDiff(): break if self.actionRan == False: if self.action == "LaunchDS": # Wrap all of this in a try/catch so that we can watch for errors and handle # them nicely! try: wx.PostEvent(self.updatewin, UpdateProgressEvent(1)) self.initPyNM() self.checkKill() if self.checkActionDiff(): break if SpringDSConfig.getCfgNICType() == "wireless": print "[SpringDSPanel] Setting required FRC static IP and subnet for wireless NIC: "+SpringDSConfig.getCfgStaticIP()+" and "+SpringDSConfig.getCfgSubnet() self.pyNMHandle.setWirelessStaticIPAndSubnet(SpringDSConfig.getCfgStaticIP(), SpringDSConfig.getCfgSubnet()) elif SpringDSConfig.getCfgNICType() == "lan": print "[SpringDSPanel] Setting required FRC static IP and subnet for LAN NIC: "+SpringDSConfig.getCfgStaticIP()+" and "+SpringDSConfig.getCfgSubnet() self.pyNMHandle.setLANStaticIPAndSubnet(SpringDSConfig.getCfgStaticIP(), SpringDSConfig.getCfgSubnet()) wx.PostEvent(self.updatewin, UpdateProgressEvent(70)) self.checkKill() if self.checkActionDiff(): break # Now launch the Driver Station (and wait)! print "[SpringDSPanel] Launching FRC Driver Station..." wx.PostEvent(self.updatewin, UpdateProgressEvent(100)) subprocess.call(SpringDSConfig.getCfgDriverStationPath()) self.checkKill() if self.checkActionDiff(): break print "[SpringDSPanel] Ensuring that everything has closed (and if not, terminating them)..." wx.PostEvent(self.updatewin, UpdateProgressEvent(70)) for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Dashboard.exe": proc.terminate() self.checkKill() self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(20)) if SpringDSConfig.getCfgNICType() == "wireless": print "[SpringDSPanel] Resetting wireless NIC to DHCP..." self.pyNMHandle.setWirelessDHCP() elif SpringDSConfig.getCfgNICType() == "lan": print "[SpringDSPanel] Resetting LAN NIC to DHCP..." self.pyNMHandle.setLANDHCP() self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(0)) wx.PostEvent(self.updatewin, ResetLauncherBtnEvent(None)) print "[SpringDSPanel] Ready." except pyNM.pyNMError, err: # TODO: add more cases # Is this a permission error? if err.IsSystemError: # Is this a permission error? (This is a subset of the system error) if err.IsPermissionError: # Are we on Windows? if sys.platform == 'win32': wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) # Check args - this should be fixed later to actually check for elevation. ELEVATED = 0 if len(sys.argv) > 1: if sys.argv[1] == '--FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH': # We tried elevating, it failed. ELEVATED = 1 MsgBox("Could not set network config, even with elevation!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Could not set network config, even with elevation. Press ALT-F4 to exit." try: if ELEVATED == 0: #print "DEBUG: sys.argv is "+str(sys.argv) #print "DEBUG: __file__ is "+str(__file__) if getattr(sys, 'frozen', False): print "[SpringDSPanel] Detected regular old script execution, so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" "+" ".join(sys.argv[1:])+"'" win32api.ShellExecute(0, "runas", sys.executable, "'"+" ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif sys.argv[0][len(sys.argv[0])-3:] == '.py': print "[SpringDSPanel] Detected regular old script execution (2), so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" '"+os.path.abspath(__file__)+"''" win32api.ShellExecute(0, "runas", sys.executable, '"'+os.path.abspath(__file__)+'"'+" --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif __file__: print "[SpringDSPanel] Detected that we're in a EXE, so executing accordingly with elevation." print "'"+__file__+" "+" '".join(sys.argv[1:])+"''" win32api.ShellExecute(0, "runas", __file__, "' ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) else: MsgBox("Failed to determine script execution environment!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Failed to determine script execution environment! Press ALT-F4 to exit." except: MsgBox("Couldn't launch SpringDS in elevated mode!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Couldn't launch SpringDS in elevated mode! Press ALT-F4 to exit." else: import traceback if err.exception != "": wx.PostEvent(self.updatewin, ErrorNotifyEvent(err.exception+"\n\n"+"".join(traceback.format_exc()))) else: wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit. [Inner loop]" #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise except SystemExit: pass except: import traceback print "GAHAHHHHHHHHH FAILURE!!!!" traceback.print_exc() wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit." #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise elif self.action == "TerminateDS": # Wrap all of this in a try/catch so that we can watch for errors and handle # them nicely! try: wx.PostEvent(self.updatewin, UpdateProgressEvent(1)) self.initPyNM() self.checkKill() if self.checkActionDiff(): break wx.PostEvent(self.updatewin, UpdateProgressEvent(50)) print "[SpringDSPanel] Ensuring that everything has closed (and if not, terminating them)..." for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Dashboard.exe": proc.terminate() self.checkKill() self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(70)) if SpringDSConfig.getCfgNICType() == 'wireless': print "[SpringDSPanel] Resetting wireless NIC to DHCP..." self.pyNMHandle.setWirelessDHCP() elif SpringDSConfig.getCfgNICType() == 'lan': print "[SpringDSPanel] Resetting LAN NIC to DHCP..." self.pyNMHandle.setLANDHCP() self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(0)) wx.PostEvent(self.updatewin, ResetLauncherBtnEvent(None)) print "[SpringDSPanel] Ready." # Note that we don't handle pyNMError as closely as LaunchDS - if the NM # failed because of permission issues, it should've died trying to start. except pyNM.pyNMError, err: # TODO: add more cases # Is this a permission error? import traceback if err.exception != "": wx.PostEvent(self.updatewin, ErrorNotifyEvent(err.exception+"\n\n"+"".join(traceback.format_exc()))) else: wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit. [Inner loop]" #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise except SystemExit: pass except: import traceback print "GAHAHHHHHHHHH FAILURE!!!!" traceback.print_exc() wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit." #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise elif self.action == "SetupNetwork": # Wrap all of this in a try/catch so that we can watch for errors and handle # them nicely! try: wx.PostEvent(self.updatewin, UpdateProgressEvent(1)) self.initPyNM() self.checkKill() if self.checkActionDiff(): break wx.PostEvent(self.updatewin, UpdateProgressEvent(50)) if SpringDSConfig.getCfgNICType() == "wireless": print "[SpringDSPanel] Setting the FRC static IP and subnet on wireless NIC: "+SpringDSConfig.getCfgStaticIP()+" and "+SpringDSConfig.getCfgSubnet() self.pyNMHandle.setWirelessStaticIPAndSubnet(SpringDSConfig.getCfgStaticIP(), SpringDSConfig.getCfgSubnet()) elif SpringDSConfig.getCfgNICType() == "lan": print "[SpringDSPanel] Setting the FRC static IP and subnet on LAN NIC: "+SpringDSConfig.getCfgStaticIP()+" and "+SpringDSConfig.getCfgSubnet() self.pyNMHandle.setLANStaticIPAndSubnet(SpringDSConfig.getCfgStaticIP(), SpringDSConfig.getCfgSubnet()) self.checkKill() if self.checkActionDiff(): break self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(0)) print "[SpringDSPanel] Ready." except pyNM.pyNMError, err: # TODO: add more cases # Is this a permission error? if err.IsSystemError: # Is this a permission error? (This is a subset of the system error) if err.IsPermissionError: # Are we on Windows? if sys.platform == 'win32': wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) # Check args - this should be fixed later to actually check for elevation. ELEVATED = 0 if len(sys.argv) > 1: if sys.argv[1] == '--FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH': # We tried elevating, it failed. ELEVATED = 1 MsgBox("Could not set network config, even with elevation!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Could not set network config, even with elevation. Press ALT-F4 to exit." try: if ELEVATED == 0: #print "DEBUG: sys.argv is "+str(sys.argv) #print "DEBUG: __file__ is "+str(__file__) if getattr(sys, 'frozen', False): print "[SpringDSPanel] Detected regular old script execution, so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" "+" ".join(sys.argv[1:])+"'" win32api.ShellExecute(0, "runas", sys.executable, "'"+" ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif sys.argv[0][len(sys.argv[0])-3:] == '.py': print "[SpringDSPanel] Detected regular old script execution (2), so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" '"+os.path.abspath(__file__)+"''" win32api.ShellExecute(0, "runas", sys.executable, '"'+os.path.abspath(__file__)+'"'+" --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif __file__: print "[SpringDSPanel] Detected that we're in a EXE, so executing accordingly with elevation." print "'"+__file__+" "+" '".join(sys.argv[1:])+"''" win32api.ShellExecute(0, "runas", __file__, "' ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) else: MsgBox("Failed to determine script execution environment!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Failed to determine script execution environment! Press ALT-F4 to exit." except: MsgBox("Couldn't launch SpringDS in elevated mode!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Couldn't launch SpringDS in elevated mode! Press ALT-F4 to exit." else: import traceback if err.exception != "": wx.PostEvent(self.updatewin, ErrorNotifyEvent(err.exception+"\n\n"+"".join(traceback.format_exc()))) else: wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit. [Inner loop]" #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise except SystemExit: pass except: import traceback print "GAHAHHHHHHHHH FAILURE!!!!" traceback.print_exc() wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit." #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise elif self.action == "ResetNetwork": # Wrap all of this in a try/catch so that we can watch for errors and handle # them nicely! try: wx.PostEvent(self.updatewin, UpdateProgressEvent(1)) self.initPyNM() self.checkKill() if self.checkActionDiff(): break self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(50)) if SpringDSConfig.getCfgNICType() == 'wireless': print "[SpringDSPanel] Resetting wireless NIC to DHCP..." self.pyNMHandle.setWirelessDHCP() elif SpringDSConfig.getCfgNICType() == 'lan': print "[SpringDSPanel] Resetting LAN NIC to DHCP..." self.pyNMHandle.setLANDHCP() self.checkKill() wx.PostEvent(self.updatewin, UpdateProgressEvent(0)) print "[SpringDSPanel] Ready." except pyNM.pyNMError, err: # TODO: add more cases # Is this a permission error? if err.IsSystemError: # Is this a permission error? (This is a subset of the system error) if err.IsPermissionError: # Are we on Windows? if sys.platform == 'win32': wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) # Check args - this should be fixed later to actually check for elevation. ELEVATED = 0 if len(sys.argv) > 1: if sys.argv[1] == '--FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH': # We tried elevating, it failed. ELEVATED = 1 MsgBox("Could not set network config, even with elevation!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Could not set network config, even with elevation. Press ALT-F4 to exit." try: if ELEVATED == 0: #print "DEBUG: sys.argv is "+str(sys.argv) #print "DEBUG: __file__ is "+str(__file__) if getattr(sys, 'frozen', False): print "[SpringDSPanel] Detected regular old script execution, so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" "+" ".join(sys.argv[1:])+"'" win32api.ShellExecute(0, "runas", sys.executable, "'"+" ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif sys.argv[0][len(sys.argv[0])-3:] == '.py': print "[SpringDSPanel] Detected regular old script execution (2), so re-executing accordingly with elevation." #print "DEBUG: executing this:" print "'"+sys.executable+" '"+os.path.abspath(__file__)+"''" win32api.ShellExecute(0, "runas", sys.executable, '"'+os.path.abspath(__file__)+'"'+" --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) elif __file__: print "[SpringDSPanel] Detected that we're in a EXE, so executing accordingly with elevation." print "'"+__file__+" "+" '".join(sys.argv[1:])+"''" win32api.ShellExecute(0, "runas", __file__, "' ".join(sys.argv[1:])+"' --FLAG-SPRINGDS-INTERNAL-ELEVATION-LAUNCH", None, 1) time.sleep(3) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) else: MsgBox("Failed to determine script execution environment!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Failed to determine script execution environment! Press ALT-F4 to exit." except: MsgBox("Couldn't launch SpringDS in elevated mode!", "Error - SpringDS", wx.ICON_ERROR) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Couldn't launch SpringDS in elevated mode! Press ALT-F4 to exit." else: import traceback if err.exception != "": wx.PostEvent(self.updatewin, ErrorNotifyEvent(err.exception+"\n\n"+"".join(traceback.format_exc()))) else: wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit. [Inner loop]" #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise except SystemExit: pass except: import traceback print "GAHAHHHHHHHHH FAILURE!!!!" traceback.print_exc() wx.PostEvent(self.updatewin, ErrorNotifyEvent("".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) self.doKill() #wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) #print "[SpringDSPanel] Code failed! Press ALT-F4 to exit." #wx.PostEvent(self.updatewin, UnhookOnQuitEvent(None)) raise elif self.action == "": # Do nothing self.actionRan = True print "[SpringDSPanel] Ready." wx.PostEvent(self.updatewin, UpdateProgressEvent(0)) else: import traceback wx.PostEvent(self.updatewin, ErrorNotifyEvent("An invalid action has been specified. \n\n"+"".join(traceback.format_exc()))) while self.errBoxOpen: time.sleep(1) wx.PostEvent(self.updatewin, TerminateWindowEvent(None)) exit() self.actionRan = True if self.checkActionDiff(): break self.actionRan = False # begin wxGlade: extracode # end wxGlade class SpringDSPanelFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: SpringDSPanelFrame.__init__ kwds["style"] = wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.RESIZE_BORDER wx.Frame.__init__(self, *args, **kwds) self.SDSPBasePanel = wx.Panel(self, -1) self.SDSPHeaderImage = wx.StaticBitmap(self.SDSPBasePanel, -1, wx.Bitmap("SpringDSPanelHeader.png", wx.BITMAP_TYPE_ANY)) self.SDSPProgressBar = wx.Gauge(self.SDSPBasePanel, -1, 10, style=wx.GA_HORIZONTAL | wx.GA_SMOOTH) self.SDSPStatusLbl = wx.StaticText(self.SDSPBasePanel, -1, "Ready.") self.SDSPButtonPanel = wx.Panel(self.SDSPBasePanel, -1) self.SDSPLaunchDSBtn = wx.Button(self.SDSPButtonPanel, -1, "Launch Driver Station") self.SDSPSetupNetworkBtn = wx.Button(self.SDSPButtonPanel, -1, "Setup Network") self.SDSPResetNetworkBtn = wx.Button(self.SDSPButtonPanel, -1, "Reset Network") self.SDSPExitBtn = wx.Button(self.SDSPButtonPanel, -1, "Exit") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self.OnLaunchDriverStation, self.SDSPLaunchDSBtn) self.Bind(wx.EVT_BUTTON, self.OnSetupNetwork, self.SDSPSetupNetworkBtn) self.Bind(wx.EVT_BUTTON, self.OnResetNetwork, self.SDSPResetNetworkBtn) self.Bind(wx.EVT_BUTTON, self.OnExit, self.SDSPExitBtn) # end wxGlade #self.Bind(wx.EVT_SIZE, self.on_size) # Background setup print "[SpringDS] Loading image from: "+os.path.join(os.getcwd(), "stripebg.png") self.bmp1 = wx.Bitmap(os.path.join(os.getcwd(), "stripebg.png")) self.SDSPButtonPanel.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_CLOSE, self.on_quit) # Connect the status update event to a callback EVT_UPDATE_STATUS(self, self.OnUpdateStatus) EVT_TERMINATE_WINDOW(self, self.OnTerminateWindow) EVT_UPDATE_PROGRESS(self, self.OnUpdateProgress) EVT_ERROR_NOTIFY(self, self.OnErrorNotify) EVT_RESET_LAUNCHER_BTN(self, self.OnResetLauncherBtn) self.SpringDS_NM_Slave_Instance = SpringDS_NM_Slave(self) self.SpringDS_NM_Slave_Instance.start() self.quitTriggered = False self.hasTerminated = False def __set_properties(self): # begin wxGlade: SpringDSPanelFrame.__set_properties self.SetTitle("SpringDS Panel") _icon = wx.EmptyIcon() _icon.CopyFromBitmap(wx.Bitmap("SpringDSPanelIcon.ico", wx.BITMAP_TYPE_ANY)) self.SDSPProgressBar.SetRange(100) #self.SetIcon(_icon) self.SetIcon(wx.Icon("SpringDSPanelIcon.ico", wx.BITMAP_TYPE_ICO, 16, 16)) # end wxGlade def __do_layout(self): # begin wxGlade: SpringDSPanelFrame.__do_layout SDSPBaseSizer = wx.BoxSizer(wx.VERTICAL) SDSPMainSizer = wx.FlexGridSizer(3, 1, 0, 0) SDSPButtonSizer = wx.FlexGridSizer(1, 4, 0, 0) SDSPIndicatorSizer = wx.FlexGridSizer(2, 1, 0, 0) SDSPMainSizer.Add(self.SDSPHeaderImage, 0, 0, 0) SDSPIndicatorSizer.Add(self.SDSPProgressBar, 0, wx.ALL | wx.EXPAND, 4) SDSPIndicatorSizer.Add(self.SDSPStatusLbl, 0, wx.ALL, 4) SDSPIndicatorSizer.AddGrowableRow(0) SDSPIndicatorSizer.AddGrowableRow(1) SDSPIndicatorSizer.AddGrowableCol(0) SDSPMainSizer.Add(SDSPIndicatorSizer, 1, wx.EXPAND, 0) SDSPButtonSizer.Add(self.SDSPLaunchDSBtn, 0, wx.ALL, 4) SDSPButtonSizer.Add(self.SDSPSetupNetworkBtn, 0, wx.ALL, 4) SDSPButtonSizer.Add(self.SDSPResetNetworkBtn, 0, wx.ALL, 4) SDSPButtonSizer.Add(self.SDSPExitBtn, 0, wx.ALL, 4) self.SDSPButtonPanel.SetSizer(SDSPButtonSizer) SDSPMainSizer.Add(self.SDSPButtonPanel, 1, wx.EXPAND, 0) self.SDSPBasePanel.SetSizer(SDSPMainSizer) SDSPMainSizer.AddGrowableCol(0) SDSPBaseSizer.Add(self.SDSPBasePanel, 1, wx.EXPAND, 0) self.SetSizer(SDSPBaseSizer) SDSPBaseSizer.Fit(self) self.Layout() self.Centre() # end wxGlade def OnLaunchDriverStation(self, event): # wxGlade: SpringDSPanelFrame.<event_handler> if self.SDSPLaunchDSBtn.GetLabel() == "Launch Driver Station": self.SpringDS_NM_Slave_Instance.setAction("LaunchDS") self.SDSPLaunchDSBtn.SetLabel("Exit Driver Station") else: self.SpringDS_NM_Slave_Instance.setAction("TerminateDS") self.SDSPLaunchDSBtn.SetLabel("Launch Driver Station") def OnResetLauncherBtn(self, event): self.SDSPLaunchDSBtn.SetLabel("Launch Driver Station") def OnSetupNetwork(self, event): # wxGlade: SpringDSPanelFrame.<event_handler> self.SpringDS_NM_Slave_Instance.setAction("SetupNetwork") def OnExit(self, event): # wxGlade: SpringDSPanelFrame.<event_handler> self.Close() def OnResetNetwork(self, event): # wxGlade: SpringDSPanelFrame.<event_handler> self.SpringDS_NM_Slave_Instance.setAction("ResetNetwork") def OnErrorNotify(self, event): # Show the error #print "CALLED: showing error!" ErrorBox('%s' % event.data) self.SpringDS_NM_Slave_Instance.setErrBoxClose() self.SetFocus() def OnUpdateProgress(self, event): self.SDSPProgressBar.SetValue(event.data) def OnTerminateWindow(self, event): self.hasTerminated = True self.SDSPStatusLbl.SetLabel("SpringDS has terminated, closing this window...") self.Refresh() self.Update() time.sleep(2) self.Destroy() def on_quit(self, event): self.SDSPLaunchDSBtn.Enable(False) self.SDSPSetupNetworkBtn.Enable(False) self.SDSPResetNetworkBtn.Enable(False) self.SDSPExitBtn.Enable(False) if (self.quitTriggered == False) and (self.hasTerminated == False): self.SDSPStatusLbl.SetLabel("Attempting to terminate SpringDS, please wait...") self.SpringDS_NM_Slave_Instance.killSlave() self.quitTriggered = True self.SDSPStatusLbl.SetLabel("SpringDS is terminating, please wait...") for proc in psutil.process_iter(): if sys.platform == 'win32': if proc.name == "Dashboard.exe": proc.terminate() if proc.name == "Driver Station.exe": proc.terminate() else: self.SDSPStatusLbl.SetLabel("SpringDS is already terminating, please wait...") def OnUpdateStatus(self, event): # Update the status text! if event.data != None: # Process data and set the label self.SDSPStatusLbl.SetLabel('%s' % event.data) def on_paint(self, event): #print "[SpringDSPanel] [SpringDSFrame.on_paint] Function called for painting!" # Grab the source DC dc = wx.PaintDC(self.SDSPButtonPanel) # If something goes wrong... we still need something to draw on. if not dc: dc = wx.ClientDC(self.SDSPButtonPanel) rect = self.SDSPButtonPanel.GetUpdateRegion().GetBox() dc.SetClippingRect(rect) w, h = dc.GetSize() # Get the BG image width and height! iw = self.bmp1.GetWidth() ih = self.bmp1.GetHeight() # Tile/wallpaper the image across the canvas for x in range(0, self.SDSPButtonPanel.GetSize()[0], iw): for y in range(0, self.SDSPButtonPanel.GetSize()[1], ih): dc.DrawBitmap(self.bmp1, x, y, True) # end of class SpringDSPanelFrame if __name__ == "__main__": print "SpringDS Panel v"+str(SPRINGDS_VERSION) bar = "" for i in range(0, len("SpringDS Panel v"+str(SPRINGDS_VERSION)) + 1): bar = bar + "=" print bar print "Copyright (C) 2012 River Hill Robotics Team (Albert H.)\n" try: app = wx.PySimpleApp(0) wx.InitAllImageHandlers() SpringDSPanelFrameInstance = SpringDSPanelFrame(None, -1, "") app.SetTopWindow(SpringDSPanelFrameInstance) SpringDSPanelFrameInstance.Show() app.MainLoop() except: print "[SpringDSPanel] Crashed..." traceback.print_exc() ErrorBox("".join(traceback.format_exc()))
Python
#!/usr/bin/env python # Team 4067 Java Cleanup - cleanup any old build files # Copyright (C) 2013 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os import shutil def listDir(directory): if os.path.isdir(directory): return [ name for name in os.listdir(directory) if os.path.isdir(os.path.join(directory, name)) ] else: return [] for srcDir in listDir("."): if os.path.isdir(os.path.join(srcDir, "nbproject")): # It's a Netbeans project, so let's clean it up! print "Examining "+srcDir+" for any old build files..." if os.path.isdir(os.path.join(srcDir, "j2meclasses")): print " = Removing j2meclasses directory..." shutil.rmtree(os.path.join(srcDir, "j2meclasses")) if os.path.isdir(os.path.join(srcDir, "build")): print " = Removing build directory..." shutil.rmtree(os.path.join(srcDir, "build")) if os.path.isdir(os.path.join(srcDir, "suite")): print " = Removing suite directory..." shutil.rmtree(os.path.join(srcDir, "suite")) else: print "Skipping "+srcDir+" as it is not a Netbeans project." for srcDir in listDir("FRCEventCode"): if os.path.isdir(os.path.join("FRCEventCode", srcDir, "nbproject")): # It's a Netbeans project, so let's clean it up! print "Examining "+srcDir+" for any old build files..." if os.path.isdir(os.path.join("FRCEventCode", srcDir, "j2meclasses")): print " = Removing j2meclasses directory..." shutil.rmtree(os.path.join("FRCEventCode", srcDir, "j2meclasses")) if os.path.isdir(os.path.join("FRCEventCode", srcDir, "build")): print " = Removing build directory..." shutil.rmtree(os.path.join("FRCEventCode", srcDir, "build")) if os.path.isdir(os.path.join("FRCEventCode", srcDir, "suite")): print " = Removing suite directory..." shutil.rmtree(os.path.join("FRCEventCode", srcDir, "suite")) else: print "Skipping "+srcDir+" as it is not a Netbeans project. " print "Cleanup complete! Press ENTER to exit!" raw_input()
Python
#!/usr/bin/env python # Team 4067 64-bit Java Disable Tool - Disable 64-bit Java to enable SmartDashboard to run! # Copyright (C) 2013 River Hill HS Robotics Team (Albert H.) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os import sys import shutil import traceback import ctypes try: import win32com.shell.shell as shell except: print "ERROR: You need to install pywin32 in order to use this program." print "Get it at http://sourceforge.net/projects/pywin32/ and install it." print "Press ENTER to exit." raw_input() sys.exit(1) # Functions # Windows 64-bit check - courtesy of "phobie" from http://stackoverflow.com/a/12578715 def is_windows_64bit(): if 'PROCESSOR_ARCHITEW6432' in os.environ: return True return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64') def selfElevate(): script = os.path.abspath(sys.argv[0]) params = ' '.join([script] + sys.argv[1:]) try: # nShow = SW_SHOW = 5 shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, nShow=5) except Exception, e: print "Looks like you canceled the elevation request. You must elevate to run this" print "script." print "Detailed Python error:" print traceback.format_exc() print "Press ENTER to exit." raw_input() sys.exit(1) sys.exit(0) def IOFail(): # Check for elevation if ctypes.windll.shell32.IsUserAnAdmin() == 1: print "ERROR: Failed to move file! Please check that you have permissions to move the file, then try again." print "Press ENTER to exit." raw_input() sys.exit(1) else: print "Re-running with more privledges..." selfElevate() sys.exit(0) print "64-bit Java Disable Tool" print "=========================" print "Copyright (C) 2013 River Hill High School Robotics Team (Albert H.)" print " *** FRC 4067 The Incredible Hawk *** " print "" # Sanity check - is this Windows? if sys.platform != 'win32': print "ERROR: This tool only runs on Windows." print "Press ENTER to exit." raw_input() sys.exit(1) if not is_windows_64bit(): print "ERROR: This tool only runs on Windows 64-bit. (You are running Windows 32-bit, as detected by this program.)" print "Press ENTER to exit." raw_input() sys.exit(1) # Get the system paths WINDOWS_DIR = os.environ.get("SYSTEMROOT") USER_DIR = os.environ.get("USERPROFILE") if os.path.exists(os.path.join(USER_DIR, "My Documents")): # Windows NT, 2000, XP USER_DOC_DIR = os.path.join(USER_DIR, "My Documents") elif os.path.exists(os.path.join(USER_DIR, "Documents")): # Windows Vista, 7, 8 USER_DOC_DIR = os.path.join(USER_DIR, "Documents") else: print "ERROR: Couldn't find your documents directory! This is a weird bug unless you modified this program!" print "Press ENTER to exit." raw_input() sys.exit(1) USER_DOCB_DIR = os.path.join(USER_DOC_DIR, "Java64Backup") if not os.path.exists(USER_DOCB_DIR): print "Creating backup directory for the first time..." os.makedirs(USER_DOCB_DIR) # Another sanity check - does WINDOWS_DIR exist? if (not WINDOWS_DIR) or (not os.path.exists(WINDOWS_DIR)): print "ERROR: Couldn't find the Windows directory! This is a weird bug unless you modified this program!" print "Press ENTER to exit." raw_input() sys.exit(1) # Last sanity check - does SYSWOW64 exist? if not os.path.exists(os.path.join(WINDOWS_DIR, "SYSWOW64")): print "ERROR: Couldn't find the Windows 64-bit system directory! This is a weird bug unless you modified this program!" print "Press ENTER to exit." raw_input() sys.exit(1) WINDOWS_SYS64_DIR = os.path.join(WINDOWS_DIR, "SYSWOW64") WINDOWS_SYS32_DIR = os.path.join(WINDOWS_DIR, "SYSTEM32") # Now start doing things! JAVA_SYS64_PATH = os.path.join(WINDOWS_SYS64_DIR, "java.exe") JAVAW_SYS64_PATH = os.path.join(WINDOWS_SYS64_DIR, "javaw.exe") JAVAWS_SYS64_PATH = os.path.join(WINDOWS_SYS64_DIR, "javaws.exe") JAVA_SYS32_PATH = os.path.join(WINDOWS_SYS32_DIR, "java.exe") JAVAW_SYS32_PATH = os.path.join(WINDOWS_SYS32_DIR, "javaw.exe") JAVAWS_SYS32_PATH = os.path.join(WINDOWS_SYS32_DIR, "javaws.exe") JAVA_USERDOCB_PATH = os.path.join(USER_DOCB_DIR, "java.exe") JAVAW_USERDOCB_PATH = os.path.join(USER_DOCB_DIR, "javaw.exe") JAVAWS_USERDOCB_PATH = os.path.join(USER_DOCB_DIR, "javaws.exe") JAVA_IN_SYS64 = os.path.exists(JAVA_SYS64_PATH) JAVAW_IN_SYS64 = os.path.exists(JAVAW_SYS64_PATH) JAVAWS_IN_SYS64 = os.path.exists(JAVAWS_SYS64_PATH) JAVA_IN_SYS32 = os.path.exists(JAVA_SYS32_PATH) JAVAW_IN_SYS32 = os.path.exists(JAVAW_SYS32_PATH) JAVAWS_IN_SYS32 = os.path.exists(JAVAWS_SYS32_PATH) JAVA_IN_USERDOC = os.path.exists(JAVA_USERDOCB_PATH) JAVAW_IN_USERDOC = os.path.exists(JAVAW_USERDOCB_PATH) JAVAWS_IN_USERDOC = os.path.exists(JAVAWS_USERDOCB_PATH) if ctypes.windll.shell32.IsUserAnAdmin() == 0: print "This program needs elevation. Elevating..." selfElevate() else: print "Detected admin privledges." if JAVA_IN_SYS64 and JAVAW_IN_SYS64 and JAVAWS_IN_SYS64 and JAVA_IN_SYS32 and JAVAW_IN_SYS32 and JAVAWS_IN_SYS32: print "Detected Java 64-bit installation in system directory, moving all into a backup folder." try: print "Copying file: "+JAVA_SYS64_PATH shutil.copy(JAVA_SYS64_PATH, JAVA_USERDOCB_PATH) print "Copying file: "+JAVAW_SYS64_PATH shutil.copy(JAVAW_SYS64_PATH, JAVAW_USERDOCB_PATH) print "Copying file: "+JAVAWS_SYS64_PATH shutil.copy(JAVAWS_SYS64_PATH, JAVAWS_USERDOCB_PATH) print "Copying file: "+JAVA_SYS32_PATH shutil.copy(JAVA_SYS32_PATH, JAVA_USERDOCB_PATH) print "Copying file: "+JAVAW_SYS32_PATH shutil.copy(JAVAW_SYS32_PATH, JAVAW_USERDOCB_PATH) print "Copying file: "+JAVAWS_SYS32_PATH shutil.copy(JAVAWS_SYS32_PATH, JAVAWS_USERDOCB_PATH) print "Removing file: "+JAVA_SYS64_PATH os.remove(JAVA_SYS64_PATH) print "Removing file: "+JAVAW_SYS64_PATH os.remove(JAVAW_SYS64_PATH) print "Removing file: "+JAVAWS_SYS64_PATH os.remove(JAVAWS_SYS64_PATH) print "Removing file: "+JAVA_SYS32_PATH os.remove(JAVA_SYS32_PATH) print "Removing file: "+JAVAW_SYS32_PATH os.remove(JAVAW_SYS32_PATH) print "Removing file: "+JAVAWS_SYS32_PATH os.remove(JAVAWS_SYS32_PATH) except IOError: IOFail() except WindowsError: IOFail() except Exception, e: print "ERROR: Something weird happened. Please report this error to the developer!" print "Python error details follow:" print traceback.format_exc() print "Copy and paste the error by right clicking either in the console or on the" print "title bar of the console! You need to click Mark, then select the above error," print "and then bring up the menu and select Copy." print "" print "Press ENTER to exit." raw_input() sys.exit(1) elif (not JAVA_IN_SYS64 and not JAVAW_IN_SYS64 and not JAVAWS_IN_SYS64) and (JAVA_IN_USERDOC and JAVAW_IN_USERDOC and JAVAWS_IN_USERDOC): print "Detected Java 64-bit installation in backup folder, moving back to system directory." try: print "Moving file: "+JAVA_USERDOCB_PATH shutil.copy(JAVA_USERDOCB_PATH, JAVA_SYS64_PATH) shutil.move(JAVA_USERDOCB_PATH, JAVA_SYS32_PATH) print "Moving file: "+JAVAW_USERDOCB_PATH shutil.copy(JAVAW_USERDOCB_PATH, JAVAW_SYS64_PATH) shutil.move(JAVAW_USERDOCB_PATH, JAVAW_SYS32_PATH) print "Moving file: "+JAVAWS_USERDOCB_PATH shutil.copy(JAVAWS_USERDOCB_PATH, JAVAWS_SYS64_PATH) shutil.move(JAVAWS_USERDOCB_PATH, JAVAWS_SYS32_PATH) except IOError: IOFail() except WindowsError: IOFail() except Exception, e: print "ERROR: Something weird happened. Please report this error to the developer!" print "Python error details follow:" print traceback.format_exc() print "Copy and paste the error by right clicking either in the console or on the" print "title bar of the console! You need to click Mark, then select the above error," print "and then bring up the menu and select Copy." print "" print "Press ENTER to exit." raw_input() sys.exit(1) else: sys.stdout.write("Inconsistent backup detected! Would you like to try and recover? [y/n] ") yn = raw_input() if yn.lower() == 'y': print "Trying to recover..." print " - Copying all current system Java executables to the backup directory..." try: print " = Copying file: "+JAVA_SYS64_PATH shutil.copy(JAVA_SYS64_PATH, JAVA_USERDOCB_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() print " = (Continuing anyway.)" try: print " = Copying file: "+JAVAW_SYS64_PATH shutil.copy(JAVAW_SYS64_PATH, JAVAW_USERDOCB_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() print " = (Continuing anyway.)" try: print " = Copying file: "+JAVAWS_SYS64_PATH shutil.copy(JAVAWS_SYS64_PATH, JAVAWS_USERDOCB_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() print " = (Continuing anyway.)" try: print " = Copying file: "+JAVA_SYS32_PATH shutil.copy(JAVA_SYS32_PATH, JAVA_USERDOCB_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() print " = (Continuing anyway.)" try: print " = Copying file: "+JAVAW_SYS32_PATH shutil.copy(JAVAW_SYS32_PATH, JAVAW_USERDOCB_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() print " = (Continuing anyway.)" try: print " = Copying file: "+JAVAWS_SYS32_PATH shutil.copy(JAVAWS_SYS32_PATH, JAVAWS_USERDOCB_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() print " = (Continuing anyway.)" print " - Moving backup files back to the system directory..." try: print " = Moving file: "+JAVA_USERDOCB_PATH shutil.copy(JAVA_USERDOCB_PATH, JAVA_SYS64_PATH) shutil.move(JAVA_USERDOCB_PATH, JAVA_SYS32_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() if os.path.exists(JAVA_SYS64_PATH): print " = (However, this program does exist in the system directory - as long as you haven't changed versions, this should be fine.)" print " = (Continuing anyway.)" try: print " = Moving file: "+JAVAW_USERDOCB_PATH shutil.copy(JAVAW_USERDOCB_PATH, JAVAW_SYS64_PATH) shutil.move(JAVAW_USERDOCB_PATH, JAVAW_SYS32_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() if os.path.exists(JAVAW_SYS64_PATH): print " = (However, this program does exist in the system directory - as long as you haven't changed versions, this should be fine.)" print " = (Continuing anyway.)" try: print " = Moving file: "+JAVAWS_USERDOCB_PATH shutil.copy(JAVAWS_USERDOCB_PATH, JAVAWS_SYS64_PATH) shutil.move(JAVAWS_USERDOCB_PATH, JAVAW_SYS32_PATH) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() if os.path.exists(JAVAWS_SYS64_PATH): print " = (However, this program does exist in the system directory - as long as you haven't changed versions, this should be fine.)" print " - Removing backup directory..." try: shutil.rmtree(USER_DOCB_DIR) except Exception, e: print " = FAILED! Python error details follow:" print traceback.format_exc() print " = You should try to remove this directory before running this tool again!" print "Press ENTER to exit." raw_input()
Python
#! /usr/bin/env python # encoding: utf-8 import platform import sys from distutils import sysconfig as _sysconfig import Utils import Options # the following two variables are used by the target "waf dist" VERSION='' APPNAME='' # these variables are mandatory ('/' are converted automatically) top = '.' out = 'build' # TODO extensive testing with different configuration (should work with Python >= 2.3) def set_options(opt): myplatform = Utils.detect_platform() if myplatform.startswith('linux'): opt.add_option('--no-lsb', action = 'store_true', help = 'Prevent building LSB (Linux Standard Base) bootloader.', default = False, dest = 'nolsb') opt.add_option('--lsbcc-path', action = 'store', help = 'Path to lsbcc. By default PATH is searched for lsbcc otherwise is tried file /opt/lsb/bin/lsbcc. [Default: lsbcc]', default = 'lsbcc', dest = 'lsbcc_path') opt.add_option('--lsb-target-version', action = 'store', help = 'Specify LSB target version [Default: 4.0]', default = '4.0', dest = 'lsb_version') opt.tool_options('compiler_cc') opt.tool_options('python') def configure(conf): def achitecture(): return '32bit' conf.env.NAME = 'default' opt = Options.options myplatform = Utils.detect_platform() # on 64bit Mac function platform.architecture() returns 64bit even # for 32bit Python. This is the workaround for this. if myplatform == 'darwin' and sys.maxint <= 3**32: myarch = '32bit' else: myarch = platform.architecture()[0] # 32bit or 64bit conf.env.MYARCH = myarch Utils.pprint('CYAN', '%s-%s detected' % (platform.system(), myarch)) if myplatform == 'darwin' and myarch == '64bit': Utils.pprint('CYAN', 'WARNING: Building bootloader for Python 64-bit on Mac OSX') Utils.pprint('CYAN', 'For 32b-bit bootloader prepend the python command with:') Utils.pprint('CYAN', 'VERSIONER_PYTHON_PREFER_32_BIT=yes arch -i386 python') if myplatform.startswith('linux') and not opt.nolsb: Utils.pprint('CYAN', 'Building LSB bootloader.') ### C compiler if myplatform.startswith('win'): try: # mingw (gcc for Windows) conf.check_tool('gcc') except: try: # Newest detected MSVC version is used by default. # msvc 7.1 (Visual Studio 2003) # msvc 8.0 (Visual Studio 2005) # msvc 9.0 (Visual Studio 2008) #conf.env['MSVC_VERSIONS'] = ['msvc 7.1', 'msvc 8.0', 'msvc 9.0'] if myarch == '32bit': conf.env['MSVC_TARGETS'] = ['x86', 'ia32'] elif myarch == '64bit': conf.env['MSVC_TARGETS'] = ['x64', 'x86_amd64', 'intel64', 'em64t'] conf.check_tool('msvc') conf.print_all_msvc_detected() # Do not embed manifest file. # Manifest file will be added in the phase of packaging python application. conf.env.MSVC_MANIFEST = False # Path to Python development file pythonXY.lib is not detected correctly # by waf 1.5 on Windows in virtualenv. if _sysconfig.get_config_var('LIBDIR'): conf.env.append_value('LINKFLAGS', '/LIBPATH:' + _sysconfig.get_config_var('LIBDIR')) except: Utils.pprint('RED', 'GCC (MinGW) or MSVC compiler not found.') exit(1) else: # When using GCC, deactivate declarations after statements # (not supported by Visual Studio) conf.env.append_value('CCFLAGS', '-Wdeclaration-after-statement') conf.env.append_value('CCFLAGS', '-Werror') else: conf.check_tool('compiler_cc') conf.check_tool('python') conf.check_python_headers() # Do not link with libpython and libpthread. for lib in conf.env.LIB_PYEMBED: if lib.startswith('python') or lib.startswith('pthread'): conf.env.LIB_PYEMBED.remove(lib) ### build LSB (Linux Standard Base) boot loader if myplatform.startswith('linux') and not opt.nolsb: try: # custom lsbcc path if opt.lsbcc_path != 'lsbcc': conf.env.LSBCC = conf.find_program(opt.lsbcc_path, mandatory=True) # default values else: conf.env.LSBCC = conf.find_program(opt.lsbcc_path) if not conf.env.LSBCC: conf.env.LSBCC = conf.find_program('/opt/lsb/bin/lsbcc', mandatory=True) except: Utils.pprint('RED', 'LSB (Linux Standard Base) tools >= 4.0 are required.') Utils.pprint('RED', 'Try --no-lsb option if not interested in building LSB binary.') exit(2) # lsbcc as CC compiler conf.env.append_value('CCFLAGS', '--lsb-cc=%s' % conf.env.CC[0]) conf.env.append_value('LINKFLAGS', '--lsb-cc=%s' % conf.env.CC[0]) conf.env.CC = conf.env.LSBCC conf.env.LINK_CC = conf.env.LSBCC ## check LSBCC flags # --lsb-besteffort - binary will work on platforms without LSB stuff # --lsb-besteffort - available in LSB build tools >= 4.0 conf.check_cc(ccflags='--lsb-besteffort', msg='Checking for LSB build tools >= 4.0', errmsg='LSB >= 4.0 is required', mandatory=True) conf.env.append_value('CCFLAGS', '--lsb-besteffort') conf.env.append_value('LINKFLAGS', '--lsb-besteffort') # binary compatibility with a specific LSB version # LSB 4.0 can generate binaries compatible with 3.0, 3.1, 3.2, 4.0 # however because of using function 'mkdtemp', loader requires # using target version 4.0 lsb_target_flag = '--lsb-target-version=%s' % opt.lsb_version conf.env.append_value('CCFLAGS', lsb_target_flag) conf.env.append_value('LINKFLAGS', lsb_target_flag) ### Defines, Includes if myplatform.startswith('lin'): # make sure we don't use declarations after statement (break Visual Studio) conf.env.append_value('CCFLAGS', '-Wdeclaration-after-statement') conf.env.append_value('CCFLAGS', '-Werror') if myplatform.startswith('win'): conf.env.append_value('CCDEFINES', 'WIN32') conf.env.append_value('CPPPATH', '../zlib') if myplatform.startswith('sun'): conf.env.append_value('CCDEFINES', 'SUNOS') if myplatform.startswith('aix'): conf.env.append_value('CCDEFINES', 'AIX') conf.env.append_value('CPPPATH', '../common') ### Libraries if myplatform.startswith('win'): conf.check_cc(lib='user32', mandatory=True) conf.check_cc(lib='comctl32', mandatory=True) conf.check_cc(lib='kernel32', mandatory=True) conf.check_cc(lib='ws2_32', mandatory=True) else: conf.check_cc(lib='z', mandatory=True) if conf.check_cc(function_name='readlink', header_name='unistd.h'): conf.env.append_value('CCFLAGS', '-DHAVE_READLINK') ### ccflags if myplatform.startswith('win') and conf.env.CC_NAME == 'gcc': # Disables console - MinGW option conf.check_cc(ccflags='-mwindows', mandatory=True, msg='Checking for flags -mwindows') # Use Visual C++ compatible alignment conf.check_cc(ccflags='-mms-bitfields', mandatory=True, msg='Checking for flags -mms-bitfields') conf.env.append_value('CCFLAGS', '-mms-bitfields') elif myplatform.startswith('win') and conf.env.CC_NAME == 'msvc': if myarch == '32bit': conf.env.append_value('LINKFLAGS', '/MACHINE:X86') elif myarch == '64bit': conf.env.append_value('LINKFLAGS', '/MACHINE:X64') # enable 64bit porting warnings conf.env.append_value('CCFLAGS', '/Wp64') # We use SEH exceptions in winmain.c; make sure they are activated. conf.env.append_value('CCFLAGS', '/EHa') # Compile with 64bit gcc 32bit binaries or vice versa. if conf.env.CC_NAME == 'gcc': if myarch == '32bit' and conf.check_cc(ccflags='-m32', msg='Checking for flags -m32'): conf.env.append_value('CCFLAGS', '-m32') elif myarch == '64bit': conf.env.append_value('CCFLAGS', '-m64') # Ensure proper architecture flags on Mac OS X. # TODO Add support for universal binaries. if myplatform.startswith('darwin'): available_archs = {'32bit': 'i386', '64bit': 'x86_64'} mac_arch = available_archs[myarch] conf.env.append_value('CCFLAGS', '-arch') conf.env.append_value('CCFLAGS', mac_arch) conf.env.append_value('CXXFLAGS', '-arch') conf.env.append_value('CXXFLAGS', mac_arch) conf.env.append_value('LINKFLAGS', '-arch') conf.env.append_value('LINKFLAGS', mac_arch) # On linux link only with needed libraries. # -Wl,--as-needed is on some platforms detected during configure but # fails during build. (Mac OS X, Solaris, AIX) if myplatform.startswith('linux') and conf.check_cc(ccflags='-Wl,--as-needed', msg='Checking for flags -Wl,--as-needed'): conf.env.append_value('LINKFLAGS', '-Wl,--as-needed') ### Other stuff if myplatform.startswith('darwin'): conf.env.MACOSX_DEPLOYMENT_TARGET = '10.4' if myplatform.startswith('win'): # RC file - icon conf.check_tool('winres') ### DEBUG and RELEASE environments rel = conf.env.copy() dbg = conf.env.copy() rel.set_variant('release') # separate subfolder for building dbg.set_variant('debug') # separate subfolder for building rel.detach() # detach environment from default dbg.detach() ## setup DEBUG environment dbg.set_variant('debug') # separate subfolder for building conf.set_env_name('debug', dbg) conf.setenv('debug') conf.env.append_value('CCDEFINES', '_DEBUG LAUNCH_DEBUG'.split()) conf.env.append_value('CCFLAGS', conf.env.CCFLAGS_DEBUG) dbgw = conf.env.copy() # WINDOWED DEBUG environment dbgw.set_variant('debugw') # separate subfolder for building dbgw.detach() ## setup windowed DEBUG environment conf.set_env_name('debugw', dbgw) conf.setenv('debugw') conf.env.append_value('CCDEFINES', 'WINDOWED') # disables console - mingw option if myplatform.startswith('win') and conf.env.CC_NAME == 'gcc': conf.env.append_value('LINKFLAGS', '-mwindows') elif myplatform.startswith('darwin'): conf.env.append_value('CCFLAGS', '-I/Developer/Headers/FlatCarbon') conf.env.append_value('LINKFLAGS', '-framework') conf.env.append_value('LINKFLAGS', 'Carbon') ## setup RELEASE environment conf.set_env_name('release', rel) conf.setenv('release') conf.env.append_value('CCDEFINES', 'NDEBUG') conf.env.append_value('CCFLAGS', conf.env.CCFLAGS_RELEASE) relw = conf.env.copy() # WINDOWED RELEASE environment relw.set_variant('releasew') # separate subfolder for building relw.detach() ## setup windowed RELEASE environment conf.set_env_name('releasew', relw) conf.setenv('releasew') conf.env.append_value('CCDEFINES', 'WINDOWED') # disables console if myplatform.startswith('win') and conf.env.CC_NAME == 'gcc': conf.env.append_value('LINKFLAGS', '-mwindows') elif myplatform.startswith('darwin'): conf.env.append_value('LINKFLAGS', '-framework') conf.env.append_value('LINKFLAGS', 'ApplicationServices') def build(bld): # Force to run with 1 job (no parallel building). # There are reported build failures on multicore CPUs # with some msvc versions. Options.options.jobs = 1 myplatform = Utils.detect_platform() install_path = '../../support/loader/' + platform.system() + "-" + bld.env.MYARCH targets = dict(release='run', debug='run_d', releasew='runw', debugw='runw_d') if myplatform.startswith('win'): # static lib zlib for key in targets.keys(): bld( features = 'cc cstaticlib', source = bld.path.ant_glob('zlib/*.c'), target = 'staticlib_zlib', env = bld.env_of_name(key), ) # console for key in ('release', 'debug'): bld( features = 'cc cprogram pyembed', source = bld.path.ant_glob('windows/utils.c windows/run.rc common/*.c'), target = targets[key], install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), ) # windowed for key in ('releasew', 'debugw'): bld( features = 'cc cprogram pyembed', source = bld.path.ant_glob('windows/utils.c windows/runw.rc common/*.c'), # uses different RC file (icon) target = targets[key], install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), ) ## inprocsrvr console if bld.env.CC_NAME == 'msvc': linkflags_c = bld.env.CPPFLAGS_CONSOLE linkflags_w = bld.env.CPPFLAGS_WINDOWS else: linkflags_c = '' linkflags_w = '' for key, value in dict(release='inprocsrvr', debug='inprocsrvr_d').items(): bld( features = 'cc cshlib', source = bld.path.ant_glob('common/launch.c windows/dllmain.c'), target = value, install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), linkflags = linkflags_c ) ## inprocsrvr windowed for key, value in dict(releasew='inprocsrvrw', debugw='inprocsrvrw_d').items(): bld( features = 'cc cshlib', source = bld.path.ant_glob('common/launch.c windows/dllmain.c'), target = value, install_path = install_path, uselib_local = 'staticlib_zlib', uselib = 'USER32 COMCTL32 KERNEL32 WS2_32', env = bld.env_of_name(key).copy(), linkflags = linkflags_w ) else: # linux, darwin (MacOSX) for key, value in targets.items(): bld( features = 'cc cprogram pyembed', source = bld.path.ant_glob('linux/*.c common/*.c'), target = value, install_path = install_path, uselib = 'Z', # zlib env = bld.env_of_name(key).copy(), )
Python
#!/usr/bin/env python from distutils.core import setup from distutils.extension import Extension setup( name = 'AES', ext_modules=[ Extension("AES", ["AES.c"]), ], )
Python