code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
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 |
# Hook for _mysql, required if higher-level pure python module is not imported
# Author: htgoebel
# Date: 2011-11-18
# Ticket: #323
hiddenimports = ['_mysql_exceptions']
| 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 |
import os
import enchant
def _win32_data_files():
# This is basically a copy of enchant.utils.win32_data_files as of
# release 1.6.0. We use this as a fallback for older versions of
# enchant which do not have this function.
# enchant is licenced under LGPL.
dataDirs = ("share/enchant/myspell","share/enchant/ispell","lib/enchant")
mainDir = os.path.abspath(os.path.dirname(enchant.__file__))
dataFiles = []
for dataDir in dataDirs:
files = []
fullDir = os.path.join(mainDir,os.path.normpath(dataDir))
for fn in os.listdir(fullDir):
fullFn = os.path.join(fullDir,fn)
if os.path.isfile(fullFn):
files.append(fullFn)
dataFiles.append((dataDir,files))
return dataFiles
try:
from enchant.utils import win32_data_files
except:
# fall back to the function above
win32_data_files = _win32_data_files
print win32_data_files()
| 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 |
import sys
from hookutils import eval_script
if sys.platform == 'win32':
files = eval_script('enchant-datafiles-finder.py')
datas = [] # data files in PyInstaller hook format
for d in files:
for f in d[1]:
datas.append((f, d[0]))
| 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, m in enumerate(mod.imports):
if m[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
import PyInstaller.depend.modules
hiddenimports = ['win32com.server.policy']
def hook(mod):
import sys
newname = 'pythoncom%d%d' % sys.version_info[:2]
if mod.typ == 'EXTENSION':
mod.__name__ = newname
else:
import win32api
h = win32api.LoadLibrary(newname + '.dll')
pth = win32api.GetModuleFileName(h)
#win32api.FreeLibrary(h)
mod = PyInstaller.depend.modules.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 |
# Hook for http://pypi.python.org/pypi/h5py/
# Author: dhyams
# Date: 2011-10-14
# Ticket: #437
hiddenimports = ['_proxy','utils','defs']
| 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
# Since Python 2.3, builtin module "time" imports Python module _strptime
# to implement "time.strptime".
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 |
# enchant.checker.wxSpellCheckerDialog causes pyinstaller to include
# whole gtk and wx libraries if they are installed. This module is
# thus ignored to prevent this.
# TODO find better workaround
def hook(mod):
# Workaround DOES NOT work with well with python 2.6
# let's just disable it
#return None
return mod
| Python |
#
# Copyright (C) 2012, Daniel Hyams
#
# 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 PyInstaller.hooks.hookutils
# If the user imports setuparg1, we just set an attribute
# in PyInstaller.hooks.hookutils that allows us to later
# find out about this.
PyInstaller.hooks.hookutils.wxpubsub = 'arg1'
| 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 marshal
txt = exec_statement("import xml;print xml.__file__")
if txt.find('_xmlplus') > -1:
if txt.endswith(".py"):
txt = txt + 'c'
try:
co = marshal.loads(open(txt, 'rb').read()[8:])
except IOError:
co = compile(open(txt[:-1], 'rU').read(), txt, 'exec')
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(os.path.join(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
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']
mod.imports = [m
for m in mod.imports
# if first part of module-name not in removes
if m[0].split('.', 1)[0] not in removes
]
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 |
#
# Copyright (C) 2012, Martin Zibricky
#
# 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
# OpenGL_accelerate contais modules written in cython. This module
# should speed up some functions from OpenGL module. The following
# hiddenimports are not resolved by PyInstaller because OpenGL_accelerate
# is compiled to native Python modules.
hiddenimports = [
'OpenGL_accelerate.wrapper',
'OpenGL_accelerate.formathandler',
]
| Python |
#
# Copyright (C) 2011, Martin Zibricky
#
# 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 PyInstaller import is_py25
# These modules must be included with 'email' module for
# lazy loading to provide name mapping from new-style (lower case) names
# email.<old name> -> email.<new name is lowercased old name>
# email.MIME<old name> -> email.mime.<new name is lowercased old name>
if is_py25:
import email
hiddenimports = ['email.' + x.lower() for x in email._LOWERNAMES]
hiddenimports += ['email.mime.' + x.lower() for x in email._MIMENAMES]
| Python |
hiddenimports = ['sip', 'PyQt4.QtCore', 'PyQt4._qt']
from PyInstaller.hooks.hookutils import qt4_plugins_binaries
def hook(mod):
# Network Bearer Management in Qt4 4.7+
mod.binaries.extend(qt4_plugins_binaries('bearer'))
return mod
| Python |
#!/usr/bin/env python
import glob
import os
import sys
import PyInstaller
import PyInstaller.compat as compat
from PyInstaller.compat import is_darwin, set
from PyInstaller.utils import misc
import PyInstaller.log as logging
logger = logging.getLogger(__name__)
def __exec_python_cmd(cmd):
"""
Executes an externally spawned Python interpreter and returns
anything that was emitted in the standard output as a single
string.
"""
# Prepend PYTHONPATH with pathex
pp = os.pathsep.join(PyInstaller.__pathex__)
old_pp = compat.getenv('PYTHONPATH')
if old_pp:
pp = os.pathsep.join([pp, old_pp])
compat.setenv("PYTHONPATH", pp)
try:
try:
txt = compat.exec_python(*cmd)
except OSError, e:
raise SystemExit("Execution failed: %s" % e)
finally:
if old_pp is not None:
compat.setenv("PYTHONPATH", old_pp)
else:
compat.unsetenv("PYTHONPATH")
return txt.strip()
def exec_statement(statement):
"""Executes a Python statement in an externally spawned interpreter, and
returns anything that was emitted in the standard output as a single string.
"""
cmd = ['-c', statement]
return __exec_python_cmd(cmd)
def exec_script(scriptfilename, *args):
"""
Executes a Python script in an externally spawned interpreter, and
returns anything that was emitted in the standard output as a
single string.
To prevent missuse, the script passed to hookutils.exec-script
must be located in the `hooks` directory.
"""
if scriptfilename != os.path.basename(scriptfilename):
raise SystemError("To prevent missuse, the script passed to "
"hookutils.exec-script must be located in "
"the `hooks` directory.")
cmd = [os.path.join(os.path.dirname(__file__), scriptfilename)]
cmd.extend(args)
return __exec_python_cmd(cmd)
def eval_statement(statement):
txt = exec_statement(statement).strip()
if not txt:
# return an empty string which is "not true" but iterable
return ''
return eval(txt)
def eval_script(scriptfilename, *args):
txt = exec_script(scriptfilename, *args).strip()
if not txt:
# return an empty string which is "not true" but iterable
return ''
return eval(txt)
def get_pyextension_imports(modname):
"""
Return list of modules required by binary (C/C++) Python extension.
Python extension files ends with .so (Unix) or .pyd (Windows).
It's almost impossible to analyze binary extension and its dependencies.
Module cannot be imported directly.
Let's at least try import it in a subprocess and get the diffrence
in module list from sys.modules.
This function could be used for 'hiddenimports' in PyInstaller hooks files.
"""
statement = """
import sys
# Importing distutils filters common modules, especiall in virtualenv.
import distutils
original_modlist = sys.modules.keys()
# When importing this module - sys.modules gets updated.
import %(modname)s
all_modlist = sys.modules.keys()
diff = set(all_modlist) - set(original_modlist)
# Module list contain original modname. We do not need it there.
diff.discard('%(modname)s')
# Print module list to stdout.
print list(diff)
""" % {'modname': modname}
module_imports = eval_statement(statement)
if not module_imports:
logger.error('Cannot find imports for module %s' % modname)
return [] # Means no imports found or looking for imports failed.
#module_imports = filter(lambda x: not x.startswith('distutils'), module_imports)
return module_imports
def qt4_plugins_dir():
qt4_plugin_dirs = eval_statement(
"from PyQt4.QtCore import QCoreApplication;"
"app=QCoreApplication([]);"
"print map(unicode,app.libraryPaths())")
if not qt4_plugin_dirs:
logger.error("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
logger.error("Cannot find existing PyQt4 plugin directory")
return ""
def qt4_phonon_plugins_dir():
qt4_plugin_dirs = eval_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:
logger.error("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
logger.error("Cannot find existing PyQt4 phonon plugin directory")
return ""
def qt4_plugins_binaries(plugin_type):
"""Return list of dynamic libraries formated for mod.binaries."""
binaries = []
pdir = qt4_plugins_dir()
files = misc.dlls_in_dir(os.path.join(pdir, plugin_type))
for f in files:
binaries.append((
os.path.join('qt4_plugins', plugin_type, os.path.basename(f)),
f, 'BINARY'))
return binaries
def qt4_menu_nib_dir():
"""Return path to Qt resource dir qt_menu.nib."""
menu_dir = ''
# Detect MacPorts prefix (usually /opt/local).
# Suppose that PyInstaller is using python from macports.
macports_prefix = sys.executable.split('/Library')[0]
# list of directories where to look for qt_menu.nib
dirs = [
# Qt4 from MacPorts not compiled as framework.
os.path.join(macports_prefix, 'lib', 'Resources'),
# Qt4 from MacPorts compiled as framework.
os.path.join(macports_prefix, 'libexec', 'qt4-mac', 'lib',
'QtGui.framework', 'Versions', '4', 'Resources'),
# Qt4 installed into default location.
'/Library/Frameworks/QtGui.framework/Resources',
'/Library/Frameworks/QtGui.framework/Versions/4/Resources',
'/Library/Frameworks/QtGui.Framework/Versions/Current/Resources',
]
# Qt4 from Homebrew compiled as framework
import glob
globpath = '/usr/local/Cellar/qt/4.*/lib/QtGui.framework/Versions/4/Resources'
qt_homebrew_dirs = glob.glob(globpath)
dirs += qt_homebrew_dirs
# Check directory existence
for d in dirs:
d = os.path.join(d, 'qt_menu.nib')
if os.path.exists(d):
menu_dir = d
break
if not menu_dir:
logger.error('Cannont find qt_menu.nib directory')
return menu_dir
def django_dottedstring_imports(django_root_dir):
package_name = os.path.basename(django_root_dir)
compat.setenv("DJANGO_SETTINGS_MODULE", "%s.settings" % package_name)
return eval_script("django-import-finder.py")
def find_django_root(dir):
entities = set(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):
try:
dir_entities = os.listdir(path_to_analyze)
except (IOError, OSError):
# silently skip unreadable directories
continue
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
def matplotlib_backends():
"""
Return matplotlib backends availabe in current Python installation.
All matplotlib backends are hardcoded. We have to try import them
and return the list of successfully imported backends.
"""
all_bk = eval_statement('import matplotlib; print matplotlib.rcsetup.all_backends')
avail_bk = []
import_statement = """
try:
__import__('matplotlib.backends.backend_%s')
except ImportError, e:
print str(e)
"""
# CocoaAgg backend causes subprocess to exit and thus detection
# is not reliable. This backend is meaningful only on Mac OS X.
if not is_darwin and 'CocoaAgg' in all_bk:
all_bk.remove('CocoaAgg')
# Try to import every backend in a subprocess.
for bk in all_bk:
stdout = exec_statement(import_statement % bk.lower())
# Backend import is successfull if there is no text in stdout.
if not stdout:
avail_bk.append(bk)
# Convert backend name to module name.
# e.g. GTKAgg -> backend_gtkagg
return ['backend_' + x.lower() for x in avail_bk]
def opengl_arrays_modules():
"""
Return list of array modules for OpenGL module.
e.g. 'OpenGL.arrays.vbo'
"""
statement = 'import OpenGL; print OpenGL.__path__[0]'
opengl_mod_path = PyInstaller.hooks.hookutils.exec_statement(statement)
arrays_mod_path = os.path.join(opengl_mod_path, 'arrays')
files = glob.glob(arrays_mod_path + '/*.py')
modules = []
for f in files:
mod = os.path.splitext(os.path.basename(f))[0]
# Skip __init__ module.
if mod == '__init__':
continue
modules.append('OpenGL.arrays.' + mod)
return modules
| Python |
hiddenimports = ["tables._comp_lzo", "tables._comp_bzip2"]
| Python |
#
# Copyright (C) 2009, Lorenzo Mancini
#
# 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
# 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.
from PyInstaller.compat import is_win, is_darwin
from PyInstaller.hooks.hookutils import opengl_arrays_modules
# PlatformPlugin performs a conditional import based on os.name and
# sys.platform. PyInstaller misses this so let's add it ourselves...
if is_win:
hiddenimports = ['OpenGL.platform.win32']
elif is_darwin:
hiddenimports = ['OpenGL.platform.darwin']
# Use glx for other platforms (Linux, ...)
else:
hiddenimports = ['OpenGL.platform.glx']
# Arrays modules are needed too.
hiddenimports += opengl_arrays_modules()
| Python |
# Contributed by pyplant@googlemail.com
hiddenimports = ['_elementpath', 'gzip']
| Python |
from PyInstaller.hooks.hookutils import exec_statement
hiddenimports = ["babel.dates"]
babel_localedata_dir = exec_statement(
"import babel.localedata; print babel.localedata._dirname")
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 PyInstaller.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 PyInstaller.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 |
# Hook for storm ORM
# Author: mail@georg-schoelly.ch
# Date: 2011-10-14
# Ticket: #437
hiddenimports = [
'storm.databases.sqlite',
'storm.databases.postgres',
'storm.databases.mysql'
]
| 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
# This code is courtesy of Thomas Heller, who
# has kindly donated it to this project.
RT_ICON = 3
RT_GROUP_ICON = 14
LOAD_LIBRARY_AS_DATAFILE = 2
import struct
import types
try:
StringTypes = types.StringTypes
except AttributeError:
StringTypes = [ type("") ]
import PyInstaller.log as logging
logger = logging.getLogger('PyInstaller.icon')
class Structure:
def __init__(self):
size = self._sizeInBytes = struct.calcsize(self._format_)
self._fields_ = list(struct.unpack(self._format_, '\000' * size))
indexes = self._indexes_ = {}
for i, nm in enumerate(self._names_):
indexes[nm] = i
def dump(self):
logger.info("DUMP of %s", self)
for name in self._names_:
if not name.startswith('_'):
logger.info("%20s = %s", name, getattr(self, name))
logger.info("")
def __getattr__(self, name):
if name in self._names_:
index = self._indexes_[name]
return self._fields_[index]
try:
return self.__dict__[name]
except KeyError:
raise AttributeError, name
def __setattr__(self, name, value):
if name in self._names_:
index = self._indexes_[name]
self._fields_[index] = value
else:
self.__dict__[name] = value
def tostring(self):
return apply(struct.pack, [self._format_,] + self._fields_)
def fromfile(self, file):
data = file.read(self._sizeInBytes)
self._fields_ = list(struct.unpack(self._format_, data))
class ICONDIRHEADER(Structure):
_names_ = "idReserved", "idType", "idCount"
_format_ = "hhh"
class ICONDIRENTRY(Structure):
_names_ = ("bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes",
"wBitCount", "dwBytesInRes", "dwImageOffset")
_format_ = "bbbbhhii"
class GRPICONDIR(Structure):
_names_ = "idReserved", "idType", "idCount"
_format_ = "hhh"
class GRPICONDIRENTRY(Structure):
_names_ = ("bWidth", "bHeight", "bColorCount", "bReserved", "wPlanes",
"wBitCount", "dwBytesInRes", "nID")
_format_ = "bbbbhhih"
class IconFile:
def __init__(self, path):
self.path = path
file = open(path, "rb")
self.entries = []
self.images = []
header = self.header = ICONDIRHEADER()
header.fromfile(file)
for i in range(header.idCount):
entry = ICONDIRENTRY()
entry.fromfile(file)
self.entries.append(entry)
for e in self.entries:
file.seek(e.dwImageOffset, 0)
self.images.append(file.read(e.dwBytesInRes))
def grp_icon_dir(self):
return self.header.tostring()
def grp_icondir_entries(self, id=1):
data = ""
for entry in self.entries:
e = GRPICONDIRENTRY()
for n in e._names_[:-1]:
setattr(e, n, getattr(entry, n))
e.nID = id
id = id + 1
data = data + e.tostring()
return data
def CopyIcons_FromIco(dstpath, srcpath, id=1):
import win32api #, win32con
icons = map(IconFile, srcpath)
logger.info("Updating icons from %s to %s", srcpath, dstpath)
hdst = win32api.BeginUpdateResource(dstpath, 0)
iconid = 1
for i, f in enumerate(icons):
data = f.grp_icon_dir()
data = data + f.grp_icondir_entries(iconid)
win32api.UpdateResource(hdst, RT_GROUP_ICON, i, data)
logger.info("Writing RT_GROUP_ICON %d resource with %d bytes", i, len(data))
for data in f.images:
win32api.UpdateResource(hdst, RT_ICON, iconid, data)
logger.info("Writing RT_ICON %d resource with %d bytes", iconid, len(data))
iconid = iconid + 1
win32api.EndUpdateResource(hdst, 0)
def CopyIcons(dstpath, srcpath):
import os.path
if type(srcpath) in StringTypes:
srcpath = [ srcpath ]
def splitter(s):
try:
srcpath, index = s.split(',')
return srcpath.strip(), int(index)
except ValueError:
return s, None
srcpath = map(splitter, srcpath)
logger.info("SRCPATH %s", srcpath)
if len(srcpath) > 1:
# At the moment, we support multiple icons only from .ico files
srcs = []
for s in srcpath:
e = os.path.splitext(s[0])[1]
if e.lower() != '.ico':
raise ValueError, "multiple icons supported only from .ico files"
if s[1] is not None:
raise ValueError, "index not allowed for .ico files"
srcs.append(s[0])
return CopyIcons_FromIco(dstpath, srcs)
srcpath,index = srcpath[0]
srcext = os.path.splitext(srcpath)[1]
if srcext.lower() == '.ico':
return CopyIcons_FromIco(dstpath, [srcpath])
if index is not None:
logger.info("Updating icons from %s, %d to %s", srcpath, index, dstpath)
else:
logger.info("Updating icons from %s to %s", srcpath, dstpath)
import win32api #, win32con
hdst = win32api.BeginUpdateResource(dstpath, 0)
hsrc = win32api.LoadLibraryEx(srcpath, 0, LOAD_LIBRARY_AS_DATAFILE)
if index is None:
grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[0]
elif index >= 0:
grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[index]
else:
grpname = -index
data = win32api.LoadResource(hsrc, RT_GROUP_ICON, grpname)
win32api.UpdateResource(hdst, RT_GROUP_ICON, grpname, data)
for iconname in win32api.EnumResourceNames(hsrc, RT_ICON):
data = win32api.LoadResource(hsrc, RT_ICON, iconname)
win32api.UpdateResource(hdst, RT_ICON, iconname, data)
win32api.FreeLibrary(hsrc)
win32api.EndUpdateResource(hdst, 0)
if __name__ == "__main__":
import sys
dstpath = sys.argv[1]
srcpath = sys.argv[2:]
CopyIcons(dstpath, srcpath)
| 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
# DEV NOTES
#
# Currently not implemented in the Manifest class:
# * Validation (only very basic sanity checks are currently in place)
# * comClass, typelib, comInterfaceProxyStub and windowClass child elements of
# the file element
# * comInterfaceExternalProxyStub and windowClass child elements of the
# assembly element
# * Application Configuration File and Multilanguage User Interface (MUI)
# support when searching for assembly files
#
# Isolated Applications and Side-by-side Assemblies:
# http://msdn.microsoft.com/en-us/library/dd408052%28VS.85%29.aspx
#
# Changelog:
# 2009-12-17 fix: small glitch in toxml / toprettyxml methods (xml declaration
# wasn't replaced when a different encodig than UTF-8 was used)
# chg: catch xml.parsers.expat.ExpatError and re-raise as
# ManifestXMLParseError
# chg: support initialize option in parse method also
#
# 2009-12-13 fix: fixed os import
# fix: skip invalid / empty dependent assemblies
#
# 2009-08-21 fix: Corrected assembly searching sequence for localized
# assemblies
# fix: Allow assemblies with no dependent files
#
# 2009-07-31 chg: Find private assemblies even if unversioned
# add: Manifest.same_id method to check if two manifests have the
# same assemblyIdentity
#
# 2009-07-30 fix: Potential failure in File.calc_hash method if hash
# algorythm not supported
# add: Publisher configuration (policy) support when searching for
# assembly files
# fix: Private assemblies are now actually found if present (and no
# shared assembly exists)
# add: Python 2.3 compatibility (oldest version supported by
# pyinstaller)
#
# 2009-07-28 chg: Code cleanup, removed a bit of redundancy
# add: silent mode (set silent attribute on module)
# chg: Do not print messages in silent mode
#
# 2009-06-18 chg: Use glob instead of regular expression in Manifest.find_files
#
# 2009-05-04 fix: Don't fail if manifest has empty description
# fix: Manifests created by the toxml, toprettyxml, writexml or
# writeprettyxml methods are now correctly recognized by
# Windows, which expects the XML declaration to be ordered
# version-encoding-standalone (standalone being optional)
# add: 'encoding' keyword argument in toxml, toprettyxml, writexml
# and writeprettyxml methods
# chg: UpdateManifestResourcesFromXML and
# UpdateManifestResourcesFromXMLFile: set resource name
# depending on file type ie. exe or dll
# fix: typo in __main__: UpdateManifestResourcesFromDataFile
# should have been UpdateManifestResourcesFromXMLFile
#
# 2009-03-21 First version
"""
winmanifest.py
Create, parse and write MS Windows Manifest files.
Find files which are part of an assembly, by searching shared and
private assemblies.
Update or add manifest resources in Win32 PE files.
Commandline usage:
winmanifest.py <dstpath> <xmlpath>
Updates or adds manifest <xmlpath> as resource in Win32 PE file <dstpath>.
"""
import os
from glob import glob
import re
import sys
import xml
from xml.dom import Node, minidom
from xml.dom.minidom import Document, Element
from PyInstaller import compat
from PyInstaller.compat import hashlib, architecture
from PyInstaller import log as logging
logger = logging.getLogger('PyInstaller.build.winmanifest')
try:
from PyInstaller.utils import winresource
except ImportError, detail:
winresource = None
logger.warn(detail)
logger.warn("Cannot check for assembly dependencies - resource access ")
logger.warn("unavailable. To enable resource access, please install ")
logger.warn("http://sourceforge.net/projects/pywin32/")
LANGUAGE_NEUTRAL_NT5 = "x-ww"
LANGUAGE_NEUTRAL_NT6 = "none"
RT_MANIFEST = 24
Document.aChild = Document.appendChild
Document.cE = Document.createElement
Document.cT = Document.createTextNode
Document.getEByTN = Document.getElementsByTagName
Element.aChild = Element.appendChild
Element.getA = Element.getAttribute
Element.getEByTN = Element.getElementsByTagName
Element.remA = Element.removeAttribute
Element.setA = Element.setAttribute
def getChildElementsByTagName(self, tagName):
""" Return child elements of type tagName if found, else [] """
result = []
for child in self.childNodes:
if isinstance(child, Element):
if child.tagName == tagName:
result.append(child)
return result
def getFirstChildElementByTagName(self, tagName):
""" Return the first element of type tagName if found, else None """
for child in self.childNodes:
if isinstance(child, Element):
if child.tagName == tagName:
return child
return None
Document.getCEByTN = getChildElementsByTagName
Document.getFCEByTN = getFirstChildElementByTagName
Element.getCEByTN = getChildElementsByTagName
Element.getFCEByTN = getFirstChildElementByTagName
class _Dummy:
pass
if winresource:
_File = winresource.File
else:
_File = _Dummy
class File(_File):
""" A file referenced by an assembly inside a manifest. """
def __init__(self, filename="", hashalg=None, hash=None, comClasses=None,
typelibs=None, comInterfaceProxyStubs=None,
windowClasses=None):
if winresource:
winresource.File.__init__(self, filename)
else:
self.filename = filename
self.name = os.path.basename(filename)
if hashalg:
self.hashalg = hashalg.upper()
else:
self.hashalg = None
if (os.path.isfile(filename) and hashalg and hashlib and
hasattr(hashlib, hashalg.lower())):
self.calc_hash()
else:
self.hash = hash
self.comClasses = comClasses or [] # TO-DO: implement
self.typelibs = typelibs or [] # TO-DO: implement
self.comInterfaceProxyStubs = comInterfaceProxyStubs or [] # TO-DO: implement
self.windowClasses = windowClasses or [] # TO-DO: implement
def calc_hash(self, hashalg=None):
"""
Calculate the hash of the file.
Will be called automatically from the constructor if the file exists
and hashalg is given (and supported), but may also be called manually
e.g. to update the hash if the file has changed.
"""
fd = open(self.filename, "rb")
buf = fd.read()
fd.close()
if hashalg:
self.hashalg = hashalg.upper()
self.hash = getattr(hashlib, self.hashalg.lower())(buf).hexdigest()
def find(self, searchpath):
logger.info("Searching for file %s", self.name)
fn = os.path.join(searchpath, self.name)
if os.path.isfile(fn):
logger.info("Found file %s", fn)
return fn
else:
logger.warn("No such file %s", fn)
return None
class InvalidManifestError(Exception):
pass
class ManifestXMLParseError(InvalidManifestError):
pass
class Manifest(object):
# Manifests:
# http://msdn.microsoft.com/en-us/library/aa375365%28VS.85%29.aspx
"""
Manifest constructor.
To build a basic manifest for your application:
mf = Manifest(type='win32', name='YourAppName', language='*',
processorArchitecture='x86', version=[1, 0, 0, 0])
To write the XML to a manifest file:
mf.writexml("YourAppName.exe.manifest")
or
mf.writeprettyxml("YourAppName.exe.manifest")
"""
def __init__(self, manifestVersion=None, noInheritable=False,
noInherit=False, type_=None, name=None, language=None,
processorArchitecture=None, version=None,
publicKeyToken=None, description=None,
requestedExecutionLevel=None, uiAccess=None,
dependentAssemblies=None, files=None,
comInterfaceExternalProxyStubs=None):
self.filename = None
self.optional = None
self.manifestType = "assembly"
self.manifestVersion = manifestVersion or [1, 0]
self.noInheritable = noInheritable
self.noInherit = noInherit
self.type = type_
self.name = name
self.language = language
self.processorArchitecture = processorArchitecture
self.version = version
self.publicKeyToken = publicKeyToken
# publicKeyToken:
# A 16-character hexadecimal string that represents the last 8 bytes
# of the SHA-1 hash of the public key under which the assembly is
# signed. The public key used to sign the catalog must be 2048 bits
# or greater. Required for all shared side-by-side assemblies.
# http://msdn.microsoft.com/en-us/library/aa375692(VS.85).aspx
self.applyPublisherPolicy = None
self.description = None
self.requestedExecutionLevel = requestedExecutionLevel
self.uiAccess = uiAccess
self.dependentAssemblies = dependentAssemblies or []
self.bindingRedirects = []
self.files = files or []
self.comInterfaceExternalProxyStubs = comInterfaceExternalProxyStubs or [] # TO-DO: implement
def add_dependent_assembly(self, manifestVersion=None, noInheritable=False,
noInherit=False, type_=None, name=None, language=None,
processorArchitecture=None, version=None,
publicKeyToken=None, description=None,
requestedExecutionLevel=None, uiAccess=None,
dependentAssemblies=None, files=None,
comInterfaceExternalProxyStubs=None):
"""
Shortcut for self.dependentAssemblies.append(Manifest(*args, **kwargs))
"""
self.dependentAssemblies.append(Manifest(manifestVersion,
noInheritable, noInherit, type_, name,
language, processorArchitecture,
version, publicKeyToken, description,
requestedExecutionLevel, uiAccess,
dependentAssemblies, files,
comInterfaceExternalProxyStubs))
if self.filename:
# Enable search for private assembly by assigning bogus filename
# (only the directory has to be correct)
self.dependentAssemblies[-1].filename = ":".join((self.filename,
name))
def add_file(self, name="", hashalg="", hash="", comClasses=None,
typelibs=None, comInterfaceProxyStubs=None,
windowClasses=None):
""" Shortcut for manifest.files.append """
self.files.append(File(name, hashalg, hash, comClasses,
typelibs, comInterfaceProxyStubs, windowClasses))
def find_files(self, ignore_policies=True):
""" Search shared and private assemblies and return a list of files.
If any files are not found, return an empty list.
IMPORTANT NOTE: For the purpose of getting the dependent assembly
files of an executable, the publisher configuration (aka policy)
should be ignored (which is the default). Setting ignore_policies=False
is only useful to find out which files are actually loaded at
runtime.
"""
# Shared Assemblies:
# http://msdn.microsoft.com/en-us/library/aa375996%28VS.85%29.aspx
#
# Private Assemblies:
# http://msdn.microsoft.com/en-us/library/aa375674%28VS.85%29.aspx
#
# Assembly Searching Sequence:
# http://msdn.microsoft.com/en-us/library/aa374224%28VS.85%29.aspx
#
# NOTE:
# Multilanguage User Interface (MUI) support not yet implemented
files = []
languages = []
if self.language not in (None, "", "*", "neutral"):
languages.append(self.getlanguage())
if "-" in self.language:
# language-culture syntax, e.g. en-us
# Add only the language part
languages.append(self.language.split("-")[0])
if self.language not in ("en-us", "en"):
languages.append("en-us")
if self.language != "en":
languages.append("en")
languages.append(self.getlanguage("*"))
winsxs = os.path.join(compat.getenv("SystemRoot"), "WinSxS")
if not os.path.isdir(winsxs):
logger.warn("No such dir %s", winsxs)
manifests = os.path.join(winsxs, "Manifests")
if not os.path.isdir(manifests):
logger.warn("No such dir %s", manifests)
if not ignore_policies and self.version:
if sys.getwindowsversion() < (6, ):
# Windows XP
pcfiles = os.path.join(winsxs, "Policies")
if not os.path.isdir(pcfiles):
logger.warn("No such dir %s", pcfiles)
else:
# Vista or later
pcfiles = manifests
for language in languages:
version = self.version
# Search for publisher configuration
if not ignore_policies and version:
# Publisher Configuration (aka policy)
# A publisher configuration file globally redirects
# applications and assemblies having a dependence on one
# version of a side-by-side assembly to use another version of
# the same assembly. This enables applications and assemblies
# to use the updated assembly without having to rebuild all of
# the affected applications.
# http://msdn.microsoft.com/en-us/library/aa375680%28VS.85%29.aspx
#
# Under Windows XP and 2003, policies are stored as
# <version>.policy files inside
# %SystemRoot%\WinSxS\Policies\<name>
# Under Vista and later, policies are stored as
# <name>.manifest files inside %SystemRoot%\winsxs\Manifests
redirected = False
if os.path.isdir(pcfiles):
logger.info("Searching for publisher configuration %s ...",
self.getpolicyid(True, language=language))
if sys.getwindowsversion() < (6, ):
# Windows XP
policies = os.path.join(pcfiles,
self.getpolicyid(True,
language=language) +
".policy")
else:
# Vista or later
policies = os.path.join(pcfiles,
self.getpolicyid(True,
language=language) +
".manifest")
for manifestpth in glob(policies):
if not os.path.isfile(manifestpth):
logger.warn("Not a file %s", manifestpth)
continue
logger.info("Found %s", manifestpth)
try:
policy = ManifestFromXMLFile(manifestpth)
except Exception, exc:
logger.error("Could not parse file %s", manifestpth)
logger.exception(exc)
else:
logger.info("Checking publisher policy for "
"binding redirects")
for assembly in policy.dependentAssemblies:
if (not assembly.same_id(self, True) or
assembly.optional):
continue
for redirect in assembly.bindingRedirects:
if logger.isEnabledFor(logging.INFO):
old = "-".join([".".join([str(i)
for i in
part])
for part in
redirect[0]])
new = ".".join([str(i)
for i in
redirect[1]])
logger.info("Found redirect for "
"version(s) %s -> %n",
old, new)
if (version >= redirect[0][0] and
version <= redirect[0][-1] and
version != redirect[1]):
logger.info("Applying redirect "
"%s -> %s",
".".join([str(i)
for i in
version]),
new)
version = redirect[1]
redirected = True
if not redirected:
logger.info("Publisher configuration not used")
# Search for assemblies according to assembly searching sequence
paths = []
if os.path.isdir(manifests):
# Add winsxs search paths
paths.extend(glob(os.path.join(manifests,
self.getid(language=language,
version=version) +
"_*.manifest")))
if self.filename:
# Add private assembly search paths
dirnm = os.path.dirname(self.filename)
if language in (LANGUAGE_NEUTRAL_NT5,
LANGUAGE_NEUTRAL_NT6):
for ext in (".dll", ".manifest"):
paths.extend(glob(os.path.join(dirnm, self.name + ext)))
paths.extend(glob(os.path.join(dirnm, self.name,
self.name + ext)))
else:
for ext in (".dll", ".manifest"):
paths.extend(glob(os.path.join(dirnm, language,
self.name + ext)))
for ext in (".dll", ".manifest"):
paths.extend(glob(os.path.join(dirnm, language,
self.name,
self.name + ext)))
logger.info("Searching for assembly %s ...",
self.getid(language=language, version=version))
for manifestpth in paths:
if not os.path.isfile(manifestpth):
logger.warn("Not a file %s", manifestpth)
continue
assemblynm = os.path.basename(
os.path.splitext(manifestpth)[0])
try:
if manifestpth.endswith(".dll"):
logger.info("Found manifest in %s", manifestpth)
manifest = ManifestFromResFile(manifestpth, [1])
else:
logger.info("Found manifest %s", manifestpth)
manifest = ManifestFromXMLFile(manifestpth)
except Exception, exc:
logger.error("Could not parse manifest %s", manifestpth)
logger.exception(exc)
else:
if manifestpth.startswith(winsxs):
assemblydir = os.path.join(winsxs, assemblynm)
if not os.path.isdir(assemblydir):
logger.warn("No such dir %s", assemblydir)
logger.warn("Assembly incomplete")
return []
else:
assemblydir = os.path.dirname(manifestpth)
files.append(manifestpth)
for file_ in self.files or manifest.files:
fn = file_.find(assemblydir)
if fn:
files.append(fn)
else:
# If any of our files does not exist,
# the assembly is incomplete
logger.warn("Assembly incomplete")
return []
return files
logger.warn("Assembly not found")
return []
def getid(self, language=None, version=None):
"""
Return an identification string which uniquely names a manifest.
This string is a combination of the manifest's processorArchitecture,
name, publicKeyToken, version and language.
Arguments:
version (tuple or list of integers) - If version is given, use it
instead of the manifest's
version.
"""
if not self.name:
logger.warn("Assembly metadata incomplete")
return ""
id = []
if self.processorArchitecture:
id.append(self.processorArchitecture)
id.append(self.name)
if self.publicKeyToken:
id.append(self.publicKeyToken)
if version or self.version:
id.append(".".join([str(i) for i in version or self.version]))
if not language:
language = self.getlanguage()
if language:
id.append(language)
return "_".join(id)
def getlanguage(self, language=None, windowsversion=None):
"""
Get and return the manifest's language as string.
Can be either language-culture e.g. 'en-us' or a string indicating
language neutrality, e.g. 'x-ww' on Windows XP or 'none' on Vista
and later.
"""
if not language:
language = self.language
if language in (None, "", "*", "neutral"):
return (LANGUAGE_NEUTRAL_NT5,
LANGUAGE_NEUTRAL_NT6)[(windowsversion or
sys.getwindowsversion()) >= (6, )]
return language
def getpolicyid(self, fuzzy=True, language=None, windowsversion=None):
"""
Return an identification string which can be used to find a policy.
This string is a combination of the manifest's processorArchitecture,
major and minor version, name, publicKeyToken and language.
Arguments:
fuzzy (boolean) - If False, insert the full version in
the id string. Default is True (omit).
windowsversion - If not specified (or None), default to
(tuple or list of integers) sys.getwindowsversion().
"""
if not self.name:
logger.warn("Assembly metadata incomplete")
return ""
id = []
if self.processorArchitecture:
id.append(self.processorArchitecture)
name = []
name.append("policy")
if self.version:
name.append(str(self.version[0]))
name.append(str(self.version[1]))
name.append(self.name)
id.append(".".join(name))
if self.publicKeyToken:
id.append(self.publicKeyToken)
if self.version and (windowsversion or sys.getwindowsversion()) >= (6, ):
# Vista and later
if fuzzy:
id.append("*")
else:
id.append(".".join([str(i) for i in self.version]))
if not language:
language = self.getlanguage(windowsversion=windowsversion)
if language:
id.append(language)
id.append("*")
id = "_".join(id)
if self.version and (windowsversion or sys.getwindowsversion()) < (6, ):
# Windows XP
if fuzzy:
id = os.path.join(id, "*")
else:
id = os.path.join(id, ".".join([str(i) for i in self.version]))
return id
def load_dom(self, domtree, initialize=True):
"""
Load manifest from DOM tree.
If initialize is True (default), reset existing attributes first.
"""
if domtree.nodeType == Node.DOCUMENT_NODE:
rootElement = domtree.documentElement
elif domtree.nodeType == Node.ELEMENT_NODE:
rootElement = domtree
else:
raise InvalidManifestError("Invalid root element node type " +
str(rootElement.nodeType) +
" - has to be one of (DOCUMENT_NODE, "
"ELEMENT_NODE)")
allowed_names = ("assembly", "assemblyBinding", "configuration",
"dependentAssembly")
if rootElement.tagName not in allowed_names:
raise InvalidManifestError(
"Invalid root element <%s> - has to be one of <%s>" %
(rootElement.tagName, ">, <".join(allowed_names)))
# logger.info("loading manifest metadata from element <%s>", rootElement.tagName)
if rootElement.tagName == "configuration":
for windows in rootElement.getCEByTN("windows"):
for assemblyBinding in windows.getCEByTN("assemblyBinding"):
self.load_dom(assemblyBinding, initialize)
else:
if initialize:
self.__init__()
self.manifestType = rootElement.tagName
self.manifestVersion = [int(i)
for i in
(rootElement.getA("manifestVersion") or
"1.0").split(".")]
self.noInheritable = bool(rootElement.getFCEByTN("noInheritable"))
self.noInherit = bool(rootElement.getFCEByTN("noInherit"))
for assemblyIdentity in rootElement.getCEByTN("assemblyIdentity"):
self.type = assemblyIdentity.getA("type") or None
self.name = assemblyIdentity.getA("name") or None
self.language = assemblyIdentity.getA("language") or None
self.processorArchitecture = assemblyIdentity.getA(
"processorArchitecture") or None
version = assemblyIdentity.getA("version")
if version:
self.version = [int(i) for i in version.split(".")]
self.publicKeyToken = assemblyIdentity.getA("publicKeyToken") or None
for publisherPolicy in rootElement.getCEByTN("publisherPolicy"):
self.applyPublisherPolicy = (publisherPolicy.getA("apply") or
"").lower() == "yes"
for description in rootElement.getCEByTN("description"):
if description.firstChild:
self.description = description.firstChild.wholeText
for trustInfo in rootElement.getCEByTN("trustInfo"):
for security in trustInfo.getCEByTN("security"):
for reqPriv in security.getCEByTN("requestedPrivileges"):
for reqExeLev in reqPriv.getCEByTN("requestedExecutionLevel"):
self.requestedExecutionLevel = reqExeLev.getA("level")
self.uiAccess = (reqExeLev.getA("uiAccess") or
"").lower() == "true"
if rootElement.tagName == "assemblyBinding":
dependencies = [rootElement]
else:
dependencies = rootElement.getCEByTN("dependency")
for dependency in dependencies:
for dependentAssembly in dependency.getCEByTN(
"dependentAssembly"):
manifest = ManifestFromDOM(dependentAssembly)
if not manifest.name:
# invalid, skip
continue
manifest.optional = (dependency.getA("optional") or
"").lower() == "yes"
self.dependentAssemblies.append(manifest)
if self.filename:
# Enable search for private assembly by assigning bogus
# filename (only the directory has to be correct)
self.dependentAssemblies[-1].filename = ":".join(
(self.filename, manifest.name))
for bindingRedirect in rootElement.getCEByTN("bindingRedirect"):
oldVersion = [[int(i) for i in part.split(".")]
for part in
bindingRedirect.getA("oldVersion").split("-")]
newVersion = [int(i)
for i in
bindingRedirect.getA("newVersion").split(".")]
self.bindingRedirects.append((oldVersion, newVersion))
for file_ in rootElement.getCEByTN("file"):
self.add_file(name=file_.getA("name"),
hashalg=file_.getA("hashalg"),
hash=file_.getA("hash"))
def parse(self, filename_or_file, initialize=True):
""" Load manifest from file or file object """
if isinstance(filename_or_file, (str, unicode)):
filename = filename_or_file
else:
filename = filename_or_file.name
try:
domtree = minidom.parse(filename_or_file)
except xml.parsers.expat.ExpatError, e:
args = [e.args[0]]
if isinstance(filename, unicode):
filename = filename.encode(sys.getdefaultencoding(), "replace")
args.insert(0, '\n File "%s"\n ' % filename)
raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
if initialize:
self.__init__()
self.filename = filename
self.load_dom(domtree, False)
def parse_string(self, xmlstr, initialize=True):
""" Load manifest from XML string """
try:
domtree = minidom.parseString(xmlstr)
except xml.parsers.expat.ExpatError, e:
raise ManifestXMLParseError(e)
self.load_dom(domtree, initialize)
def same_id(self, manifest, skip_version_check=False):
"""
Return a bool indicating if another manifest has the same identitiy.
This is done by comparing language, name, processorArchitecture,
publicKeyToken, type and version.
"""
if skip_version_check:
version_check = True
else:
version_check = self.version == manifest.version
return (self.language == manifest.language and
self.name == manifest.name and
self.processorArchitecture == manifest.processorArchitecture and
self.publicKeyToken == manifest.publicKeyToken and
self.type == manifest.type and
version_check)
def todom(self):
""" Return the manifest as DOM tree """
doc = Document()
docE = doc.cE(self.manifestType)
if self.manifestType == "assemblyBinding":
cfg = doc.cE("configuration")
win = doc.cE("windows")
win.aChild(docE)
cfg.aChild(win)
doc.aChild(cfg)
else:
doc.aChild(docE)
if self.manifestType != "dependentAssembly":
docE.setA("xmlns", "urn:schemas-microsoft-com:asm.v1")
if self.manifestType != "assemblyBinding":
docE.setA("manifestVersion",
".".join([str(i) for i in self.manifestVersion]))
if self.noInheritable:
docE.aChild(doc.cE("noInheritable"))
if self.noInherit:
docE.aChild(doc.cE("noInherit"))
aId = doc.cE("assemblyIdentity")
if self.type:
aId.setAttribute("type", self.type)
if self.name:
aId.setAttribute("name", self.name)
if self.language:
aId.setAttribute("language", self.language)
if self.processorArchitecture:
aId.setAttribute("processorArchitecture",
self.processorArchitecture)
if self.version:
aId.setAttribute("version",
".".join([str(i) for i in self.version]))
if self.publicKeyToken:
aId.setAttribute("publicKeyToken", self.publicKeyToken)
if aId.hasAttributes():
docE.aChild(aId)
else:
aId.unlink()
if self.applyPublisherPolicy != None:
ppE = doc.cE("publisherPolicy")
if self.applyPublisherPolicy:
ppE.setA("apply", "yes")
else:
ppE.setA("apply", "no")
docE.aChild(ppE)
if self.description:
descE = doc.cE("description")
descE.aChild(doc.cT(self.description))
docE.aChild(descE)
if self.requestedExecutionLevel in ("asInvoker", "highestAvailable",
"requireAdministrator"):
tE = doc.cE("trustInfo")
tE.setA("xmlns", "urn:schemas-microsoft-com:asm.v3")
sE = doc.cE("security")
rpE = doc.cE("requestedPrivileges")
relE = doc.cE("requestedExecutionLevel")
relE.setA("level", self.requestedExecutionLevel)
if self.uiAccess:
relE.setA("uiAccess", "true")
else:
relE.setA("uiAccess", "false")
rpE.aChild(relE)
sE.aChild(rpE)
tE.aChild(sE)
docE.aChild(tE)
if self.dependentAssemblies:
for assembly in self.dependentAssemblies:
if self.manifestType != "assemblyBinding":
dE = doc.cE("dependency")
if assembly.optional:
dE.setAttribute("optional", "yes")
daE = doc.cE("dependentAssembly")
adom = assembly.todom()
for child in adom.documentElement.childNodes:
daE.aChild(child.cloneNode(False))
adom.unlink()
if self.manifestType != "assemblyBinding":
dE.aChild(daE)
docE.aChild(dE)
else:
docE.aChild(daE)
if self.bindingRedirects:
for bindingRedirect in self.bindingRedirects:
brE = doc.cE("bindingRedirect")
brE.setAttribute("oldVersion",
"-".join([".".join([str(i)
for i in
part])
for part in
bindingRedirect[0]]))
brE.setAttribute("newVersion",
".".join([str(i) for i in bindingRedirect[1]]))
docE.aChild(brE)
if self.files:
for file_ in self.files:
fE = doc.cE("file")
for attr in ("name", "hashalg", "hash"):
val = getattr(file_, attr)
if val:
fE.setA(attr, val)
docE.aChild(fE)
return doc
def toprettyxml(self, indent=" ", newl=os.linesep, encoding="UTF-8"):
""" Return the manifest as pretty-printed XML """
domtree = self.todom()
# WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
# ('application configuration incorrect')
if sys.version_info >= (2,3):
xmlstr = domtree.toprettyxml(indent, newl, encoding)
else:
xmlstr = domtree.toprettyxml(indent, newl)
xmlstr = xmlstr.strip(os.linesep).replace(
'<?xml version="1.0" encoding="%s"?>' % encoding,
'<?xml version="1.0" encoding="%s" standalone="yes"?>' %
encoding)
domtree.unlink()
return xmlstr
def toxml(self, encoding="UTF-8"):
""" Return the manifest as XML """
domtree = self.todom()
# WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
# ('application configuration incorrect')
xmlstr = domtree.toxml(encoding).replace(
'<?xml version="1.0" encoding="%s"?>' % encoding,
'<?xml version="1.0" encoding="%s" standalone="yes"?>' % encoding)
domtree.unlink()
return xmlstr
def update_resources(self, dstpath, names=None, languages=None):
""" Update or add manifest resource in dll/exe file dstpath """
UpdateManifestResourcesFromXML(dstpath, self.toprettyxml(), names,
languages)
def writeprettyxml(self, filename_or_file=None, indent=" ", newl=os.linesep,
encoding="UTF-8"):
""" Write the manifest as XML to a file or file object """
if not filename_or_file:
filename_or_file = self.filename
if isinstance(filename_or_file, (str, unicode)):
filename_or_file = open(filename_or_file, "wb")
xmlstr = self.toprettyxml(indent, newl, encoding)
filename_or_file.write(xmlstr)
filename_or_file.close()
def writexml(self, filename_or_file=None, indent=" ", newl=os.linesep,
encoding="UTF-8"):
""" Write the manifest as XML to a file or file object """
if not filename_or_file:
filename_or_file = self.filename
if isinstance(filename_or_file, (str, unicode)):
filename_or_file = open(filename_or_file, "wb")
xmlstr = self.toxml(indent, newl, encoding)
filename_or_file.write(xmlstr)
filename_or_file.close()
def ManifestFromResFile(filename, names=None, languages=None):
""" Create and return manifest instance from resource in dll/exe file """
res = GetManifestResources(filename, names, languages)
pth = []
if res and res[RT_MANIFEST]:
while isinstance(res, dict) and res.keys():
key = res.keys()[0]
pth.append(str(key))
res = res[key]
if isinstance(res, dict):
raise InvalidManifestError("No matching manifest resource found in '%s'" %
filename)
manifest = Manifest()
manifest.filename = ":".join([filename] + pth)
manifest.parse_string(res, False)
return manifest
def ManifestFromDOM(domtree):
""" Create and return manifest instance from DOM tree """
manifest = Manifest()
manifest.load_dom(domtree)
return manifest
def ManifestFromXML(xmlstr):
""" Create and return manifest instance from XML """
manifest = Manifest()
manifest.parse_string(xmlstr)
return manifest
def ManifestFromXMLFile(filename_or_file):
""" Create and return manifest instance from file """
manifest = Manifest()
manifest.parse(filename_or_file)
return manifest
def GetManifestResources(filename, names=None, languages=None):
""" Get manifest resources from file """
return winresource.GetResources(filename, [RT_MANIFEST], names, languages)
def UpdateManifestResourcesFromXML(dstpath, xmlstr, names=None,
languages=None):
""" Update or add manifest XML as resource in dstpath """
logger.info("Updating manifest in %s", dstpath)
if dstpath.lower().endswith(".exe"):
name = 1
else:
name = 2
winresource.UpdateResources(dstpath, xmlstr, RT_MANIFEST, names or [name],
languages or [0, "*"])
def UpdateManifestResourcesFromXMLFile(dstpath, srcpath, names=None,
languages=None):
""" Update or add manifest XML from srcpath as resource in dstpath """
logger.info("Updating manifest from %s in %s", srcpath, dstpath)
if dstpath.lower().endswith(".exe"):
name = 1
else:
name = 2
winresource.UpdateResourcesFromDataFile(dstpath, srcpath, RT_MANIFEST,
names or [name],
languages or [0, "*"])
def create_manifest(filename, manifest, console):
"""
Create assembly manifest.
"""
if not manifest:
manifest = ManifestFromXMLFile(filename)
# /path/NAME.exe.manifest - split extension twice to get NAME.
name = os.path.basename(filename)
manifest.name = os.path.splitext(os.path.splitext(name)[0])[0]
elif isinstance(manifest, basestring) and "<" in manifest:
# Assume XML string
manifest = ManifestFromXML(manifest)
elif not isinstance(manifest, Manifest):
# Assume filename
manifest = ManifestFromXMLFile(manifest)
dep_names = set([dep.name for dep in manifest.dependentAssemblies])
if manifest.filename != filename:
# Update dependent assemblies
depmanifest = ManifestFromXMLFile(filename)
for assembly in depmanifest.dependentAssemblies:
if not assembly.name in dep_names:
manifest.dependentAssemblies.append(assembly)
dep_names.add(assembly.name)
if (not console and
not "Microsoft.Windows.Common-Controls" in dep_names):
# Add Microsoft.Windows.Common-Controls to dependent assemblies
manifest.dependentAssemblies.append(
Manifest(type_="win32",
name="Microsoft.Windows.Common-Controls",
language="*",
processorArchitecture=processor_architecture(),
version=(6, 0, 0, 0),
publicKeyToken="6595b64144ccf1df")
)
manifest.writeprettyxml(filename)
return manifest
def processor_architecture():
"""
Detect processor architecture for assembly manifest.
According to:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa374219(v=vs.85).aspx
item processorArchitecture in assembly manifest is
'x86' - 32bit Windows
'amd64' - 64bit Windows
"""
if architecture() == '32bit':
return 'x86'
else:
return 'amd64'
if __name__ == "__main__":
dstpath = sys.argv[1]
srcpath = sys.argv[2]
UpdateManifestResourcesFromXMLFile(dstpath, srcpath)
| Python |
# This module contains various helper functions for git DVCS
#
# Copyright (C) 2011, hartmut Goebel
#
# 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 PyInstaller import compat
def get_repo_revision():
try:
rev = compat.exec_command('git', 'rev-parse', '--short', 'HEAD').strip()
if rev:
return rev
except:
pass
return ''
if __name__ == '__main__':
print get_repo_revision()
| Python |
#
# Copyright (C) 2005-2011, 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
# Utils for Windows platform.
__all__ = ['get_windows_dir']
import os
from PyInstaller import compat
import PyInstaller.log as logging
logger = logging.getLogger(__name__)
def get_windows_dir():
"""
Return the Windows directory e.g. C:\\Windows.
"""
try:
import win32api
except ImportError:
windir = compat.getenv('SystemRoot', compat.getenv('WINDIR'))
else:
windir = win32api.GetWindowsDirectory()
if not windir:
raise SystemExit("Error: Can not determine your Windows directory")
return windir
def get_system_path():
"""
Return the path that Windows will search for dlls.
"""
_bpath = []
try:
import win32api
sys_dir = win32api.GetSystemDirectory()
except ImportError:
sys_dir = os.path.normpath(os.path.join(get_windows_dir(), 'system32'))
# Ensure C:\Windows\system32 and C:\Windows directories are
# always present in PATH variable.
# C:\Windows\system32 is valid even for 64bit Windows. Access do DLLs are
# transparently redirected to C:\Windows\syswow64 for 64bit applactions.
# http://msdn.microsoft.com/en-us/library/aa384187(v=vs.85).aspx
_bpath = [sys_dir, get_windows_dir()]
_bpath.extend(compat.getenv('PATH', '').split(os.pathsep))
return _bpath
| Python |
#
# Copyright (C) 2005-2011, 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
"""
This module is for the miscellaneous routines which do not fit somewhere else.
"""
import glob
import os
from PyInstaller import log as logging
from PyInstaller.compat import is_win
logger = logging.getLogger(__name__)
def dlls_in_subdirs(directory):
"""Returns *.dll, *.so, *.dylib in given directories and subdirectories."""
files = []
for root, dirs, files in os.walk(directory):
files.extend(dlls_in_dir(root))
def dlls_in_dir(directory):
"""Returns *.dll, *.so, *.dylib in given directory."""
files = []
files.extend(glob.glob(os.path.join(directory, '*.so')))
files.extend(glob.glob(os.path.join(directory, '*.dll')))
files.extend(glob.glob(os.path.join(directory, '*.dylib')))
return files
def find_executable(executable, path=None):
"""
Try to find 'executable' in the directories listed in 'path' (a
string listing directories separated by 'os.pathsep'; defaults to
os.environ['PATH']).
Returns the complete filename or None if not found.
Code from http://snippets.dzone.com/posts/show/6313
"""
if path is None:
path = os.environ['PATH']
paths = path.split(os.pathsep)
extlist = ['']
if is_win:
(base, ext) = os.path.splitext(executable)
# Executable files on windows have an arbitrary extension, but
# .exe is automatically appended if not present in the name.
if not ext:
executable = executable + ".exe"
pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
(base, ext) = os.path.splitext(executable)
if ext.lower() not in pathext:
extlist = pathext
for ext in extlist:
execname = executable + ext
if os.path.isfile(execname):
return execname
else:
for p in paths:
f = os.path.join(p, execname)
if os.path.isfile(f):
return f
else:
return None
def get_unicode_modules():
"""
Try importing codecs and encodings to include unicode support
in created binary.
"""
modules = []
try:
import codecs
modules = ['codecs']
import encodings
# `encodings` imports `codecs`, so only the first is required.
modules = ['encodings']
except ImportError:
pass
return modules
def get_code_object(filename):
"""
Convert source code from Python source file to code object.
"""
try:
source_code_string = open(filename, 'rU').read() + '\n'
code_object = compile(source_code_string, filename, 'exec')
return code_object
except SyntaxError, e:
logger.exception(e)
raise SystemExit(10)
| Python |
#
| 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 win32api
import struct
import pywintypes
TEST=0
LOAD_LIBRARY_AS_DATAFILE = 2
RT_VERSION = 16
def getRaw(o):
return str(buffer(o))
def decode(pathnm):
h = win32api.LoadLibraryEx(pathnm, 0, LOAD_LIBRARY_AS_DATAFILE)
nm = win32api.EnumResourceNames(h, RT_VERSION)[0]
data = win32api.LoadResource(h, RT_VERSION, nm)
vs = VSVersionInfo()
j = vs.fromRaw(data)
if TEST:
print vs
if data[:j] != vs.toRaw():
print "AAAAAGGHHHH"
glbls = {
'VSVersionInfo': VSVersionInfo,
'FixedFileInfo': FixedFileInfo,
'StringFileInfo': StringFileInfo,
'StringTable': StringTable,
'StringStruct': StringStruct,
'VarFileInfo': VarFileInfo,
'VarStruct': VarStruct,
}
vs2 = eval(repr(vs), glbls)
if vs.toRaw() != vs2.toRaw():
print
print 'reconstruction not the same!'
print vs2
win32api.FreeLibrary(h)
return vs
class VSVersionInfo:
"""
WORD wLength; // length of the VS_VERSION_INFO structure
WORD wValueLength; // length of the Value member
WORD wType; // 1 means text, 0 means binary
WCHAR szKey[]; // Contains the Unicode string "VS_VERSION_INFO".
WORD Padding1[];
VS_FIXEDFILEINFO Value;
WORD Padding2[];
WORD Children[]; // zero or more StringFileInfo or VarFileInfo
// structures (or both) that are children of the
// current version structure.
"""
def __init__(self, ffi=None, kids=None):
self.ffi = ffi
self.kids = kids or []
def fromRaw(self, data):
i, (sublen, vallen, wType, nm) = parseCommon(data)
#vallen is length of the ffi, typ is 0, nm is 'VS_VERSION_INFO'
i = ((i + 3) / 4) * 4
# now a VS_FIXEDFILEINFO
self.ffi = FixedFileInfo()
j = self.ffi.fromRaw(data, i)
#print ffi
if TEST and data[i:j] != self.ffi.toRaw():
print "raw:", `data[i:j]`
print "ffi:", `self.ffi.toRaw()`
i = j
while i < sublen:
j = i
i, (csublen, cvallen, ctyp, nm) = parseCommon(data, i)
if str(nm).strip() == "StringFileInfo":
sfi = StringFileInfo()
k = sfi.fromRaw(csublen, cvallen, nm, data, i, j+csublen)
if TEST and data[j:k] != sfi.toRaw():
rd = data[j:k]
sd = sfi.toRaw()
for x in range(0, len(rd), 16):
rds = rd[x:x+16]
sds = sd[x:x+16]
if rds != sds:
print "rd[%s:%s+16]: %r" % (x, x, rds)
print "sd[%s:%s+16]: %r" % (x, x, sds)
print
print ("raw: len %d, wLength %d"
% (len(rd), struct.unpack('h', rd[:2])[0]))
print ("sfi: len %d, wLength %d"
% (len(sd), struct.unpack('h', sd[:2])[0]))
self.kids.append(sfi)
i = k
else:
vfi = VarFileInfo()
k = vfi.fromRaw(csublen, cvallen, nm, data, i, j+csublen)
self.kids.append(vfi)
if TEST and data[j:k] != vfi.toRaw():
print "raw:", `data[j:k]`
print "vfi:", `vfi.toRaw()`
i = k
i = j + csublen
i = ((i + 3) / 4) * 4
return i
def toRaw(self):
nm = pywintypes.Unicode('VS_VERSION_INFO')
rawffi = self.ffi.toRaw()
vallen = len(rawffi)
typ = 0
sublen = 6 + 2*len(nm) + 2
pad = ''
if sublen % 4:
pad = '\000\000'
sublen = sublen + len(pad) + vallen
pad2 = ''
if sublen % 4:
pad2 = '\000\000'
tmp = "".join([kid.toRaw() for kid in self.kids ])
sublen = sublen + len(pad2) + len(tmp)
return (struct.pack('hhh', sublen, vallen, typ)
+ getRaw(nm) + '\000\000' + pad + rawffi + pad2 + tmp)
def __repr__(self, indent=''):
indent = indent + ' '
tmp = [kid.__repr__(indent+' ')
for kid in self.kids]
tmp = ', \n'.join(tmp)
return ("VSVersionInfo(\n%sffi=%s,\n%skids=[\n%s\n%s]\n)"
% (indent, self.ffi.__repr__(indent), indent,
tmp, indent))
def parseCommon(data, start=0):
i = start + 6
(wLength, wValueLength, wType) = struct.unpack('3h', data[start:i])
#print "wLength, wValueLength, wType, i:", wLength, wValueLength, wType, i
i, szKey = parseUString(data, i, i+wLength)
#i = ((i + 3) / 4) * 4
#print `data[start+6:start+wLength]`
return i, (wLength, wValueLength, wType, szKey)
def parseUString(data, start, limit):
i = start
while i < limit:
if data[i:i+2] == '\000\000':
break
i += 2
szKey = pywintypes.UnicodeFromRaw(data[start:i])
i += 2
#print "szKey:", repr(szKey), "(consumed", i-start, "bytes - to", i, ")"
return i, szKey
class FixedFileInfo:
"""
DWORD dwSignature; //Contains the value 0xFEEFO4BD
DWORD dwStrucVersion; // binary version number of this structure.
// The high-order word of this member contains
// the major version number, and the low-order
// word contains the minor version number.
DWORD dwFileVersionMS; // most significant 32 bits of the file's binary
// version number
DWORD dwFileVersionLS; //
DWORD dwProductVersionMS; // most significant 32 bits of the binary version
// number of the product with which this file was
// distributed
DWORD dwProductVersionLS; //
DWORD dwFileFlagsMask; // bitmask that specifies the valid bits in
// dwFileFlags. A bit is valid only if it was
// defined when the file was created.
DWORD dwFileFlags; // VS_FF_DEBUG, VS_FF_PATCHED etc.
DWORD dwFileOS; // VOS_NT, VOS_WINDOWS32 etc.
DWORD dwFileType; // VFT_APP etc.
DWORD dwFileSubtype; // 0 unless VFT_DRV or VFT_FONT or VFT_VXD
DWORD dwFileDateMS;
DWORD dwFileDateLS;
"""
def __init__(self, filevers=(0, 0, 0, 0), prodvers=(0, 0, 0, 0),
mask=0x3f, flags=0x0, OS=0x40004, fileType=0x1,
subtype=0x0, date=(0, 0)):
self.sig = 0xfeef04bdL
self.strucVersion = 0x10000
self.fileVersionMS = (filevers[0] << 16) | (filevers[1] & 0xffff)
self.fileVersionLS = (filevers[2] << 16) | (filevers[3] & 0xffff)
self.productVersionMS = (prodvers[0] << 16) | (prodvers[1] & 0xffff)
self.productVersionLS = (prodvers[2] << 16) | (prodvers[3] & 0xffff)
self.fileFlagsMask = mask
self.fileFlags = flags
self.fileOS = OS
self.fileType = fileType
self.fileSubtype = subtype
self.fileDateMS = date[0]
self.fileDateLS = date[1]
def fromRaw(self, data, i):
(self.sig,
self.strucVersion,
self.fileVersionMS,
self.fileVersionLS,
self.productVersionMS,
self.productVersionLS,
self.fileFlagsMask,
self.fileFlags,
self.fileOS,
self.fileType,
self.fileSubtype,
self.fileDateMS,
self.fileDateLS) = struct.unpack('13l', data[i:i+52])
return i+52
def toRaw(self):
return struct.pack('L12l', self.sig,
self.strucVersion,
self.fileVersionMS,
self.fileVersionLS,
self.productVersionMS,
self.productVersionLS,
self.fileFlagsMask,
self.fileFlags,
self.fileOS,
self.fileType,
self.fileSubtype,
self.fileDateMS,
self.fileDateLS)
def __repr__(self, indent=''):
fv = (self.fileVersionMS >> 16, self.fileVersionMS & 0xffff,
self.fileVersionLS >> 16, self.fileVersionLS & 0xFFFF)
pv = (self.productVersionMS >> 16, self.productVersionMS & 0xffff,
self.productVersionLS >> 16, self.productVersionLS & 0xFFFF)
fd = (self.fileDateMS, self.fileDateLS)
tmp = ["FixedFileInfo(",
"filevers=%s," % fv,
"prodvers=%s," % pv,
"mask=%s," % hex(self.fileFlagsMask),
"flags=%s," % hex(self.fileFlags),
"OS=%s," % hex(self.fileOS),
"fileType=%s," % hex(self.fileType),
"subtype=%s," % hex(self.fileSubtype),
"date=%s" % fd,
")"
]
return ('\n'+indent+' ').join(tmp)
##StringFileInfo {
##};
class StringFileInfo:
"""
WORD wLength; // length of the version resource
WORD wValueLength; // length of the Value member in the current
// VS_VERSION_INFO structure
WORD wType; // 1 means text, 0 means binary
WCHAR szKey[]; // Contains the Unicode string 'StringFileInfo'.
WORD Padding[];
StringTable Children[]; // list of zero or more String structures
"""
def __init__(self, kids=None):
self.name = "StringFileInfo"
self.kids = kids or []
def fromRaw(self, sublen, vallen, name, data, i, limit):
self.name = name
while i < limit:
st = StringTable()
j = st.fromRaw(data, i, limit)
if TEST and data[i:j] != st.toRaw():
rd = data[i:j]
sd = st.toRaw()
for x in range(0, len(rd), 16):
rds = rd[x:x+16]
sds = sd[x:x+16]
if rds != sds:
print "rd[%s:%s+16]: %r" % (x, x, rds)
print "sd[%s:%s+16]: %r" % (x, x, sds)
print
print ("raw: len %d, wLength %d"
% (len(rd), struct.unpack('h', rd[:2])[0]))
print (" st: len %d, wLength %d"
% (len(sd), struct.unpack('h', sd[:2])[0]))
self.kids.append(st)
i = j
return i
def toRaw(self):
if type(self.name) is STRINGTYPE:
self.name = pywintypes.Unicode(self.name)
vallen = 0
typ = 1
sublen = 6 + 2*len(self.name) + 2
pad = ''
if sublen % 4:
pad = '\000\000'
tmp = ''.join([kid.toRaw() for kid in self.kids])
sublen = sublen + len(pad) + len(tmp)
if tmp[-2:] == '\000\000':
sublen = sublen - 2
return (struct.pack('hhh', sublen, vallen, typ)
+ getRaw(self.name) + '\000\000' + pad + tmp)
def __repr__(self, indent=''):
newindent = indent + ' '
tmp = [kid.__repr__(newindent)
for kid in self.kids]
tmp = ', \n'.join(tmp)
return ("%sStringFileInfo(\n%s[\n%s\n%s])"
% (indent, newindent, tmp, newindent))
class StringTable:
"""
WORD wLength;
WORD wValueLength;
WORD wType;
WCHAR szKey[];
String Children[]; // list of zero or more String structures.
"""
def __init__(self, name=None, kids=None):
self.name = name or ''
self.kids = kids or []
def fromRaw(self, data, i, limit):
#print "Parsing StringTable"
i, (cpsublen, cpwValueLength, cpwType, self.name) = parseCodePage(data, i, limit) # should be code page junk
#i = ((i + 3) / 4) * 4
while i < limit:
ss = StringStruct()
j = ss.fromRaw(data, i, limit)
if TEST and data[i:j] != ss.toRaw():
print "raw:", `data[i:j]`
print " ss:", `ss.toRaw()`
i = j
self.kids.append(ss)
i = ((i + 3) / 4) * 4
return i
def toRaw(self):
if type(self.name) is STRINGTYPE:
self.name = pywintypes.Unicode(self.name)
vallen = 0
typ = 1
sublen = 6 + 2*len(self.name) + 2
tmp = []
for kid in self.kids:
raw = kid.toRaw()
if len(raw) % 4:
raw = raw + '\000\000'
tmp.append(raw)
tmp = ''.join(tmp)
sublen += len(tmp)
if tmp[-2:] == '\000\000':
sublen -= 2
return (struct.pack('hhh', sublen, vallen, typ)
+ getRaw(self.name) + '\000\000' + tmp)
def __repr__(self, indent=''):
newindent = indent + ' '
tmp = map(repr, self.kids)
tmp = (',\n%s' % newindent).join(tmp)
return ("%sStringTable(\n%s%r,\n%s[%s])"
% (indent, newindent, self.name, newindent, tmp))
class StringStruct:
"""
WORD wLength;
WORD wValueLength;
WORD wType;
WCHAR szKey[];
WORD Padding[];
String Value[];
"""
def __init__(self, name=None, val=None):
self.name = name or ''
self.val = val or ''
def fromRaw(self, data, i, limit):
i, (sublen, vallen, typ, self.name) = parseCommon(data, i)
limit = i + sublen
i = ((i + 3) / 4) * 4
i, self.val = parseUString(data, i, limit)
return i
def toRaw(self):
if type(self.name) is STRINGTYPE:
self.name = pywintypes.Unicode(self.name)
if type(self.val) is STRINGTYPE:
self.val = pywintypes.Unicode(self.val)
vallen = len(self.val) + 1
typ = 1
sublen = 6 + 2*len(self.name) + 2
pad = ''
if sublen % 4:
pad = '\000\000'
sublen = sublen + len(pad) + 2*vallen
return (struct.pack('hhh', sublen, vallen, typ)
+ getRaw(self.name) + '\000\000' + pad
+ getRaw(self.val) + '\000\000')
def __repr__(self, indent=''):
return "StringStruct(%r, %r)" % (self.name, self.val)
def parseCodePage(data, i, limit):
#print "Parsing CodePage"
i, (sublen, wValueLength, wType, nm) = parseCommon(data, i)
#i = ((i + 3) / 4) * 4
return i, (sublen, wValueLength, wType, nm)
class VarFileInfo:
"""
WORD wLength; // length of the version resource
WORD wValueLength; // length of the Value member in the current
// VS_VERSION_INFO structure
WORD wType; // 1 means text, 0 means binary
WCHAR szKey[]; // Contains the Unicode string 'VarFileInfo'.
WORD Padding[];
Var Children[]; // list of zero or more Var structures
"""
def __init__(self, kids=None):
self.kids = kids or []
def fromRaw(self, sublen, vallen, name, data, i, limit):
self.sublen = sublen
self.vallen = vallen
self.name = name
i = ((i + 3) / 4) * 4
while i < limit:
vs = VarStruct()
j = vs.fromRaw(data, i, limit)
self.kids.append(vs)
if TEST and data[i:j] != vs.toRaw():
print "raw:", `data[i:j]`
print "cmp:", `vs.toRaw()`
i = j
return i
def toRaw(self):
self.vallen = 0
self.wType = 1
self.name = pywintypes.Unicode('VarFileInfo')
sublen = 6 + 2*len(self.name) + 2
pad = ''
if sublen % 4:
pad = '\000\000'
tmp = ''.join([kid.toRaw() for kid in self.kids])
self.sublen = sublen + len(pad) + len(tmp)
return (struct.pack('hhh', self.sublen, self.vallen, self.wType)
+ getRaw(self.name) + '\000\000' + pad + tmp)
def __repr__(self, indent=''):
tmp = map(repr, self.kids)
return "%sVarFileInfo([%s])" % (indent, ', '.join(tmp))
STRINGTYPE = type('')
class VarStruct:
"""
WORD wLength; // length of the version resource
WORD wValueLength; // length of the Value member in the current
// VS_VERSION_INFO structure
WORD wType; // 1 means text, 0 means binary
WCHAR szKey[]; // Contains the Unicode string 'Translation'
// or a user-defined key string value
WORD Padding[]; //
WORD Value[]; // list of one or more values that are language
// and code-page identifiers
"""
def __init__(self, name=None, kids=None):
self.name = name or ''
self.kids = kids or []
def fromRaw(self, data, i, limit):
i, (self.sublen, self.wValueLength, self.wType, self.name) = parseCommon(data, i)
i = ((i + 3) / 4) * 4
for j in range(self.wValueLength/2):
kid = struct.unpack('h', data[i:i+2])[0]
self.kids.append(kid)
i += 2
return i
def toRaw(self):
self.wValueLength = len(self.kids) * 2
self.wType = 0
if type(self.name) is STRINGTYPE:
self.name = pywintypes.Unicode(self.name)
sublen = 6 + 2*len(self.name) + 2
pad = ''
if sublen % 4:
pad = '\000\000'
self.sublen = sublen + len(pad) + self.wValueLength
tmp = ''.join([struct.pack('h', kid) for kid in self.kids])
return (struct.pack('hhh', self.sublen, self.wValueLength, self.wType)
+ getRaw(self.name) + '\000\000' + pad + tmp)
def __repr__(self, indent=''):
return "VarStruct(%r, %r)" % (self.name, self.kids)
def SetVersion(exenm, versionfile):
txt = open(versionfile, 'rU').read()
vs = eval(txt)
hdst = win32api.BeginUpdateResource(exenm, 0)
win32api.UpdateResource(hdst, RT_VERSION, 1, vs.toRaw())
win32api.EndUpdateResource (hdst, 0)
if __name__ == '__main__':
import sys
TEST = 1
if len(sys.argv) < 2:
decode('c:/Program Files/Netscape/Communicator/Program/netscape.exe')
else:
print "Examining", sys.argv[1]
decode(sys.argv[1])
| 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
import PyInstaller.log as logging
logger = logging.getLogger('PyInstaller.build.winresource')
from PyInstaller.compat import set
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.
"""
if types: types = set(types)
if names: names = set(names)
if languages: languages = set(languages)
res = {}
try:
# logger.debug("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:
# logger.debug("Enumerating resources of type %s", 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:
# logger.debug("Enumerating resources of type %s name %s", type_, 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):
# logger.info('%s: %s', exception.args[1:3])
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]:
logger.info("Updating resource type %s name %s language %s",
type_, name, 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)
"""
if types: types = set(types)
if names: names = set(names)
if langauges: languages = set(languages)
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 |
#
# Copyright (C) 2012, Martin Zibricky
#
# 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
# This is a fake 'site' module available in default Python Library.
#
# The real 'site' does some magic to find paths to other possible
# Python modules. We do not want this behaviour for frozen applications.
#
# Fake 'site' makes PyInstaller to work with distutils and to work inside
# virtualenv environment.
# TODO test the following code stub from real 'site' module.
# Prefixes for site-packages; add additional prefixes like /usr/local here
PREFIXES = []
# Enable per user site-packages directory
# set it to False to disable the feature or True to force the feature
ENABLE_USER_SITE = False
# for distutils.commands.install
# These values are initialized by the getuserbase() and getusersitepackages()
# functions, through the main() function when Python starts.
USER_SITE = None
USER_BASE = None
| 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 py_compile
import imp
import tempfile
import UserList
import bindepend
from PyInstaller.loader import archive, carchive
import PyInstaller.depend.imptracker
import PyInstaller.depend.modules
from PyInstaller import HOMEPATH, CONFIGDIR, PLATFORM
from PyInstaller import is_win, is_unix, is_aix, is_darwin, is_cygwin
from PyInstaller import is_py23, is_py24
import PyInstaller.compat as compat
from PyInstaller.compat import hashlib, set
from PyInstaller.depend import dylib
from PyInstaller.utils import misc
import PyInstaller.log as logging
if is_win:
from PyInstaller.utils import winmanifest
logger = logging.getLogger('PyInstaller.build')
STRINGTYPE = type('')
TUPLETYPE = type((None,))
UNCOMPRESSED, COMPRESSED = range(2)
DEFAULT_BUILDPATH = os.path.join('SPECPATH', 'build',
'pyi.TARGET_PLATFORM', 'SPECNAME')
SPEC = None
SPECPATH = None
BUILDPATH = None
WARNFILE = None
NOCONFIRM = None
# Some modules are included if they are detected at build-time or
# if a command-line argument is specified. (e.g. --ascii)
HIDDENIMPORTS = []
rthooks = {}
def _save_data(filename, data):
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
outf = open(filename, 'w')
pprint.pprint(data, outf)
outf.close()
def _load_data(filename):
return eval(open(filename, 'rU').read())
def setupUPXFlags():
f = compat.getenv("UPX", "")
if is_win and is_py24:
# 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
compat.setenv("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 = os.path.join(BUILDPATH, "localpycos")
new_toc = []
for (nm, fnm, typ) in toc:
if typ != 'PYMODULE':
new_toc.append((nm, fnm, typ))
continue
# Trim the terminal "c" or "o"
source_fnm = fnm[:-1]
# We need to perform a build ourselves if the source is newer
# than the compiled, or the compiled doesn't exist, or if it
# has been written by a different Python version.
needs_compile = (mtime(source_fnm) > mtime(fnm)
or
open(fnm, 'rb').read()[:4] != imp.get_magic())
if needs_compile:
try:
py_compile.compile(source_fnm, fnm)
logger.debug("compiled %s", 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 = os.path.join(basepath, *leading)
if not os.path.exists(leading):
os.makedirs(leading)
fnm = os.path.join(leading, mod_name + ext)
needs_compile = (mtime(source_fnm) > mtime(fnm)
or
open(fnm, 'rb').read()[:4] != imp.get_magic())
if needs_compile:
py_compile.compile(source_fnm, fnm)
logger.debug("compiled %s", source_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 in ('EXTENSION', 'DEPENDENCY'):
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
#--- functons for checking guts ---
def _check_guts_eq(attr, old, new, last_build):
"""
rebuild is required if values differ
"""
if old != new:
logger.info("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:
logger.info("building because %s changed", fnm)
return True
elif pyc and mtime(fnm[:-1]) > last_build:
logger.info("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 _check_path_overlap(path):
"""
Check that path does not overlap with BUILDPATH or SPECPATH (i.e.
BUILDPATH and SPECPATH may not start with path, which could be
caused by a faulty hand-edited specfile)
Raise SystemExit if there is overlap, return True otherwise
"""
specerr = 0
if BUILDPATH.startswith(path):
logger.error('Specfile error: The output path "%s" contains '
'BUILDPATH (%s)', path, BUILDPATH)
specerr += 1
if SPECPATH.startswith(path):
logger.error('Specfile error: The output path "%s" contains '
'SPECPATH (%s)', path, SPECPATH)
specerr += 1
if specerr:
raise SystemExit('Error: Please edit/recreate the specfile (%s) '
'and set a different output name (e.g. "dist").'
% SPEC)
return True
def _rmtree(path):
"""
Remove directory and all its contents, but only after user confirmation,
or if the -y option is set
"""
if 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:
raise SystemExit('Error: The output directory "%s" is not empty. '
'Please remove all its contents or use the '
'-y option (remove output directory without '
'confirmation).' % path)
if choice.strip().lower() == 'y':
logger.info('Removing dir %s', path)
shutil.rmtree(path)
else:
raise SystemExit('User aborted')
def check_egg(pth):
"""Check if path points to a file inside a python egg file (or to an egg
directly)."""
if is_py23:
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 is_win:
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):
# Get a (per class) unique number to avoid conflicts between
# toc objects
self.invcnum = self.__class__.invcnum
self.__class__.invcnum += 1
self.out = os.path.join(BUILDPATH, 'out%02d-%s.toc' %
(self.invcnum, self.__class__.__name__))
self.outnm = os.path.basename(self.out)
self.dependencies = TOC()
def __postinit__(self):
logger.info("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:
logger.info("building because %s %s", os.path.basename(self.out), missing)
return None
if len(data) != len(self.GUTS):
logger.info("building because %s is bad", self.outnm)
return None
for i, (attr, func) in enumerate(self.GUTS):
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):
_old_scripts = set((
absnormpath(os.path.join(HOMEPATH, "support", "_mountzlib.py")),
absnormpath(os.path.join(CONFIGDIR, "support", "useUnicode.py")),
absnormpath(os.path.join(CONFIGDIR, "support", "useTK.py")),
absnormpath(os.path.join(HOMEPATH, "support", "useUnicode.py")),
absnormpath(os.path.join(HOMEPATH, "support", "useTK.py")),
absnormpath(os.path.join(HOMEPATH, "support", "unpackTK.py")),
absnormpath(os.path.join(HOMEPATH, "support", "removeTK.py")),
))
def __init__(self, scripts=None, pathex=None, hiddenimports=None,
hookspath=None, excludes=None):
Target.__init__(self)
# Include initialization Python code in PyInstaller analysis.
_init_code_path = os.path.join(HOMEPATH, 'PyInstaller', 'loader')
self.inputs = [
os.path.join(HOMEPATH, "support", "_pyi_bootstrap.py"),
os.path.join(_init_code_path, 'archive.py'),
os.path.join(_init_code_path, 'carchive.py'),
os.path.join(_init_code_path, 'iu.py'),
]
for script in scripts:
if absnormpath(script) in self._old_scripts:
logger.warn('Ignoring obsolete auto-added script %s', script)
continue
if not os.path.exists(script):
raise ValueError("script '%s' not found" % script)
self.inputs.append(script)
self.pathex = []
if pathex:
self.pathex = [absnormpath(path) for path in pathex]
self.hiddenimports = hiddenimports or []
# Include modules detected at build time. Like 'codecs' and encodings.
self.hiddenimports.extend(HIDDENIMPORTS)
self.hookspath = hookspath
self.excludes = excludes
self.scripts = TOC()
self.pure = TOC()
self.binaries = TOC()
self.zipfiles = TOC()
self.datas = TOC()
self.dependencies = 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),
('hiddenimports', _check_guts_eq),
)
def check_guts(self, last_build):
if last_build == 0:
logger.info("building %s because %s non existent", self.__class__.__name__, self.outnm)
return True
for fnm in self.inputs:
if mtime(fnm) > last_build:
logger.info("building because %s changed", fnm)
return True
data = Target.get_guts(self, last_build)
if not data:
return True
scripts, pure, binaries, zipfiles, datas, hiddenimports = data[-6:]
self.scripts = TOC(scripts)
self.pure = TOC(pure)
self.binaries = TOC(binaries)
self.zipfiles = TOC(zipfiles)
self.datas = TOC(datas)
self.hiddenimports = hiddenimports
return False
def assemble(self):
logger.info("running Analysis %s", os.path.basename(self.out))
# Reset seen variable to correctly discover dependencies
# if there are multiple Analysis in a single specfile.
bindepend.seen = {}
python = sys.executable
if not is_win:
while os.path.islink(python):
python = os.path.join(os.path.dirname(python), os.readlink(python))
depmanifest = None
else:
depmanifest = winmanifest.Manifest(type_="win32", name=specnm,
processorArchitecture=winmanifest.processor_architecture(),
version=(1, 0, 0, 0))
depmanifest.filename = os.path.join(BUILDPATH,
specnm + ".exe.manifest")
binaries = [] # binaries to bundle
# Always add Python's dependencies first
# This ensures that its assembly depencies under Windows get pulled in
# first, so that .pyd files analyzed later which may not have their own
# manifest and may depend on DLLs which are part of an assembly
# referenced by Python's manifest, don't cause 'lib not found' messages
binaries.extend(bindepend.Dependencies([('', python, '')],
manifest=depmanifest)[1:])
###################################################
# Scan inputs and prepare:
dirs = {} # input directories
pynms = [] # python filenames with no extension
for script in self.inputs:
if not os.path.exists(script):
raise SystemExit("Error: Analysis: script %s not found!" % script)
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 importTracker and analyze scripts
importTracker = PyInstaller.depend.imptracker.ImportTracker(
dirs.keys() + self.pathex, self.hookspath, self.excludes)
PyInstaller.__pathex__ = self.pathex[:]
scripts = [] # will contain scripts to bundle
for i, script in enumerate(self.inputs):
logger.info("Analyzing %s", script)
importTracker.analyze_script(script)
scripts.append((pynms[i], script, 'PYSOURCE'))
PyInstaller.__pathex__ = []
# analyze the script's hidden imports
for modnm in self.hiddenimports:
if modnm in importTracker.modules:
logger.info("Hidden import %r has been found otherwise", modnm)
continue
logger.info("Analyzing hidden import %r", modnm)
importTracker.analyze_one(modnm)
if not modnm in importTracker.modules:
logger.error("Hidden import %r not found", modnm)
###################################################
# Fills pure, binaries and rthookcs lists to TOC
pure = [] # pure python modules
zipfiles = [] # zipfiles to bundle
datas = [] # datafiles to bundle
rthooks = [] # rthooks if needed
# Find rthooks.
logger.info("Looking for run-time hooks")
for modnm, mod in importTracker.modules.items():
rthooks.extend(_findRTHook(modnm))
# Analyze rthooks. Runtime hooks has to be also analyzed.
# Otherwise some dependencies could be missing.
# Data structure in format:
# ('rt_hook_mod_name', '/rt/hook/file/name.py', 'PYSOURCE')
for hook_mod, hook_file, mod_type in rthooks:
logger.info("Analyzing rthook %s", hook_file)
importTracker.analyze_script(hook_file)
for modnm, mod in importTracker.modules.items():
# FIXME: why can we have a mod == None here?
if mod is None:
continue
datas.extend(mod.datas)
if isinstance(mod, PyInstaller.depend.modules.BuiltinModule):
pass
elif isinstance(mod, PyInstaller.depend.modules.ExtensionModule):
binaries.append((mod.__name__, mod.__file__, 'EXTENSION'))
# allows hooks to specify additional dependency
# on other shared libraries loaded at runtime (by dlopen)
binaries.extend(mod.binaries)
elif isinstance(mod, (PyInstaller.depend.modules.PkgInZipModule, PyInstaller.depend.modules.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, mod.__file__, 'PYMODULE'))
# Add remaining binary dependencies
binaries.extend(bindepend.Dependencies(binaries,
manifest=depmanifest))
if is_win:
depmanifest.writeprettyxml()
self.fixMissingPythonLib(binaries)
if zipfiles:
scripts.insert(-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 = tuple([getattr(self, g[0]) for g in self.GUTS])
if oldstuff != newstuff:
_save_data(self.out, newstuff)
wf = open(WARNFILE, 'w')
for ln in importTracker.getwarnings():
wf.write(ln + '\n')
wf.close()
logger.info("Warnings written to %s", WARNFILE)
return 1
logger.info("%s no change!", self.out)
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 is_aix:
# Shared libs on AIX are archives with shared object members, thus the ".a" suffix.
names = ('libpython%d.%d.a' % sys.version_info[:2],)
elif is_unix:
# Other *nix platforms.
names = ('libpython%d.%d.so' % sys.version_info[:2],)
elif is_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]
logger.info('Looking for Python library %s', name)
if is_unix:
lib = bindepend.findLibrary(name)
if lib is None:
raise IOError("Python library not found!")
elif is_darwin:
# On MacPython, Analysis.assemble is able to find the libpython with
# no additional help, asking for sys.executable 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).
# This happens on Mac OS X when Python is compiled as Framework.
# Python compiled as Framework contains same values in sys.prefix
# and exec_prefix. That's why we can use just sys.prefix.
# In virtualenv PyInstaller is not able to find Python library.
# We need special care for this case.
if compat.is_virtualenv:
py_prefix = sys.real_prefix
else:
py_prefix = sys.prefix
logger.info('Looking for Python library in %s', py_prefix)
lib = os.path.join(py_prefix, name)
if not os.path.exists(lib):
raise IOError("Python library not found!")
binaries.append((os.path.basename(lib), lib, 'BINARY'))
def _findRTHook(modnm):
rslt = []
for script in rthooks.get(modnm) or []:
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
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'
# Level of zlib compression.
self.level = level
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):
if not os.path.exists(self.name):
logger.info("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):
logger.info("building PYZ %s", 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 = hashlib.md5(data).digest()
return digest
def checkCache(fnm, strip=0, upx=0, dist_nm=None):
"""
Cache prevents preprocessing binary files again and again.
'dist_nm' Filename relative to dist directory. We need it on Mac
to determine level of paths for @loader_path like
'@loader_path/../../' for qt4 plugins.
"""
# On darwin a cache is required anyway to keep the libaries
# with relative install names. Caching on darwin does not work
# since we need to modify binary headers to use relative paths
# to dll depencies and starting with '@loader_path'.
if ((not strip and not upx and not is_darwin and not is_win)
or fnm.lower().endswith(".manifest")):
return fnm
if strip:
strip = 1
else:
strip = 0
if upx:
upx = 1
else:
upx = 0
# Load cache index
# Make cachedir per Python major/minor version.
# This allows parallel building of executables with different
# Python versions as one user.
pyver = ('py%d%s') % (sys.version_info[0], sys.version_info[1])
cachedir = os.path.join(CONFIGDIR, 'bincache%d%d_%s' % (strip, upx, pyver))
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 basenm in cache_index:
if digest != cache_index[basenm]:
os.remove(cachedfile)
else:
# On Mac OS X we need relative paths to dll dependencies
# starting with @executable_path
if is_darwin:
dylib.mac_set_relative_dylib_deps(cachedfile, dist_nm)
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", cachedfile]
else:
if strip:
# -S = strip only debug symbols.
# The default strip behaviour breaks some shared libraries
# under Mac OSX
cmd = ["strip", "-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:
logger.error(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:
logger.error("Cannot parse manifest resource %s, "
"%s from", name, language)
logger.error(cachedfile)
logger.exception(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)
_depNames = set([dep.name for dep in
manifest.dependentAssemblies])
for pydep in pyasm:
if not pydep.name in _depNames:
logger.info("Adding %r to dependent "
"assemblies of %r",
pydep.name, cachedfile)
manifest.dependentAssemblies.append(pydep)
_depNames.update(pydep.name)
if len(manifest.dependentAssemblies) > olen:
try:
manifest.update_resources(os.path.abspath(cachedfile),
[name],
[language])
except Exception, e:
logger.error(os.path.abspath(cachedfile))
raise
if cmd:
try:
compat.exec_command(*cmd)
except OSError, e:
raise SystemExit("Execution failed: %s" % e)
# update cache index
cache_index[basenm] = digest
_save_data(cacheindexfn, cache_index)
# On Mac OS X we need relative paths to dll dependencies
# starting with @executable_path
if is_darwin:
dylib.mac_set_relative_dylib_deps(cachedfile, dist_nm)
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',
'DEPENDENCY': 'd'}
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:
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
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):
if not os.path.exists(self.name):
logger.info("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):
logger.info("building PKG %s", 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', 'DEPENDENCY'):
if self.exclude_binaries and typ != 'DEPENDENCY':
self.dependencies.append((inm, fnm, typ))
else:
fnm = checkCache(fnm, self.strip_binaries,
self.upx_binaries and (is_win or is_cygwin)
and config['hasUPX'], dist_nm=inm)
# 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 fnm in seen:
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 is_win or is_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 is_win:
filename = os.path.join(BUILDPATH, specnm + ".exe.manifest")
self.manifest = winmanifest.create_manifest(filename, self.manifest,
self.console)
self.toc.append((os.path.basename(self.name) + ".manifest", filename,
'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),
('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):
if not os.path.exists(self.name):
logger.info("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):
logger.info("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, resources = data[3:6]
if (icon or versrsrc or resources) and not config['hasRsrcUpdate']:
# todo: really ignore :-)
logger.info("ignoring icon, version, manifest and resources = platform not capable")
mtm = data[-1]
crypt = data[-2]
if crypt != self.crypt:
logger.info("rebuilding %s because crypt option changed", self.outnm)
return 1
if mtm != mtime(self.name):
logger.info("rebuilding %s because mtimes don't match", self.outnm)
return True
if mtm < mtime(self.pkg.out):
logger.info("rebuilding %s because pkg is more recent", self.outnm)
return True
return False
def _bootloader_file(self, exe):
if not self.console:
exe = exe + 'w'
if self.debug:
exe = exe + '_d'
return os.path.join("support", "loader", PLATFORM, exe)
def assemble(self):
logger.info("building EXE from %s", 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 is_win or is_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(1, len(res)):
try:
res[i] = int(res[i])
except ValueError:
pass
resfile = res[0]
restype = resname = reslang = None
if len(res) > 1:
restype = res[1]
if len(res) > 2:
resname = res[2]
if len(res) > 3:
reslang = res[3]
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:
logger.exception(exc)
continue
if not restype or not resname:
logger.error("resource type and/or name not specified")
continue
if "*" in (restype, resname):
logger.error("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:
logger.exception(exc)
trash.append(tmpnm)
exe = tmpnm
exe = checkCache(exe, self.strip, self.upx and config['hasUPX'])
self.copy(exe, outf)
if self.append_pkg:
logger.info("Appending archive to EXE %s", self.name)
self.copy(self.pkg.name, outf)
else:
logger.info("Copying archive to %s", self.pkgname)
shutil.copy2(self.pkg.name, self.pkgname)
outf.close()
os.chmod(self.name, 0755)
guts = (self.name, self.console, self.debug, self.icon,
self.versrsrc, self.resources, self.strip, self.upx,
self.crypt, mtime(self.name))
assert len(guts) == len(self.GUTS)
_save_data(self.out, guts)
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):
logger.info("building DLL %s", 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):
# COLLECT always needs to be executed, since it will clean the output
# directory anyway to make sure there is no existing cruft accumulating
return 1
def assemble(self):
if _check_path_overlap(self.name) and os.path.isdir(self.name):
_rmtree(self.name)
logger.info("building COLLECT %s", os.path.basename(self.out))
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 (is_win or is_cygwin)
and config['hasUPX'], dist_nm=inm)
if typ != 'DEPENDENCY':
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 is_darwin:
return
# icns icon for app bundle.
self.icon = kws.get('icon', os.path.join(os.path.dirname(__file__),
'..', 'source', 'images', 'icon-windowed.icns'))
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:
logger.info("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")
else:
self.name = os.path.join(SPECPATH, self.name)
break
self.__postinit__()
GUTS = (('toc', _check_guts_eq), # additional check below
)
def check_guts(self, last_build):
# BUNDLE always needs to be executed, since it will clean the output
# directory anyway to make sure there is no existing cruft accumulating
return 1
def assemble(self):
if _check_path_overlap(self.name) and os.path.isdir(self.name):
_rmtree(self.name)
logger.info("building BUNDLE %s", os.path.basename(self.out))
# 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"))
# Copy icns icon to Resources directory.
if os.path.exists(self.icon):
shutil.copy(self.icon, os.path.join(self.name, 'Contents', 'Resources'))
else:
logger.warn("icon not found %s" % self.icon)
# Key/values for a minimal Info.plist file
info_plist_dict = {"CFBundleDisplayName": self.appname,
"CFBundleName": self.appname,
# Fix for #156 - 'MacOS' must be in the name - not sure why
"CFBundleExecutable": 'MacOS/%s' % os.path.basename(self.exename),
"CFBundleIconFile": os.path.basename(self.icon),
"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:
# Copy files from cache. This ensures that are used files with relative
# paths to dynamic library dependencies (@executable_path)
if typ in ('EXTENSION', 'BINARY'):
fnm = checkCache(fnm, dist_nm=inm)
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)
## For some hooks copy resource to ./Contents/Resources dir.
# PyQt4 hook: On Mac Qt requires resources 'qt_menu.nib'.
# It is copied from dist directory.
qt_menu_dir = os.path.join(self.name, 'Contents', 'MacOS', 'qt_menu.nib')
qt_menu_dest = os.path.join(self.name, 'Contents', 'Resources', 'qt_menu.nib')
if os.path.exists(qt_menu_dir):
shutil.copytree(qt_menu_dir, qt_menu_dest)
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:
logger.info("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:
logger.info("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):
logger.info("building Tree %s", 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
logger.info("%s no change!", self.out)
return 0
class MERGE(object):
"""
Merge repeated dependencies from other executables into the first
execuable. Data and binary files are then present only once and some
disk space is thus reduced.
"""
def __init__(self, *args):
"""
Repeated dependencies are then present only once in the first
executable in the 'args' list. Other executables depend on the
first one. Other executables have to extract necessary files
from the first executable.
args dependencies in a list of (Analysis, id, filename) tuples.
Replace id with the correct filename.
"""
# The first Analysis object with all dependencies.
# Any item from the first executable cannot be removed.
self._main = None
self._dependencies = {}
self._id_to_path = {}
for _, i, p in args:
self._id_to_path[i] = p
# Get the longest common path
self._common_prefix = os.path.dirname(os.path.commonprefix([os.path.abspath(a.scripts[-1][1]) for a, _, _ in args]))
if self._common_prefix[-1] != os.sep:
self._common_prefix += os.sep
logger.info("Common prefix: %s", self._common_prefix)
self._merge_dependencies(args)
def _merge_dependencies(self, args):
"""
Filter shared dependencies to be only in first executable.
"""
for analysis, _, _ in args:
path = os.path.abspath(analysis.scripts[-1][1]).replace(self._common_prefix, "", 1)
path = os.path.splitext(path)[0]
if path in self._id_to_path:
path = self._id_to_path[path]
self._set_dependencies(analysis, path)
def _set_dependencies(self, analysis, path):
"""
Syncronize the Analysis result with the needed dependencies.
"""
for toc in (analysis.binaries, analysis.datas):
for i, tpl in enumerate(toc):
if not tpl[1] in self._dependencies.keys():
logger.debug("Adding dependency %s located in %s" % (tpl[1], path))
self._dependencies[tpl[1]] = path
else:
dep_path = self._get_relative_path(path, self._dependencies[tpl[1]])
logger.debug("Referencing %s to be a dependecy for %s, located in %s" % (tpl[1], path, dep_path))
analysis.dependencies.append((":".join((dep_path, tpl[0])), tpl[1], "DEPENDENCY"))
toc[i] = (None, None, None)
# Clean the list
toc[:] = [tpl for tpl in toc if tpl != (None, None, None)]
# TODO move this function to PyInstaller.compat module (probably improve
# function compat.relpath()
def _get_relative_path(self, startpath, topath):
start = startpath.split(os.sep)[:-1]
start = ['..'] * len(start)
if start:
start.append(topath)
return os.sep.join(start)
else:
return topath
def TkTree():
raise SystemExit('TkTree has been removed in PyInstaller 2.0. '
'Please update your spec-file. See '
'http://www.pyinstaller.org/wiki/MigrateTo2.0 for details')
def TkPKG():
raise SystemExit('TkPKG has been removed in PyInstaller 2.0. '
'Please update your spec-file. See '
'http://www.pyinstaller.org/wiki/MigrateTo2.0 for details')
def build(spec, buildpath):
global SPECPATH, BUILDPATH, WARNFILE, rthooks, SPEC, specnm
rthooks = _load_data(os.path.join(HOMEPATH, 'support', 'rthooks.dat'))
SPEC = spec
SPECPATH, specnm = os.path.split(spec)
specnm = os.path.splitext(specnm)[0]
if SPECPATH == '':
SPECPATH = os.getcwd()
BUILDPATH = os.path.join(SPECPATH, 'build',
"pyi." + sys.platform, specnm)
# Check and adjustment for build path
if buildpath != DEFAULT_BUILDPATH:
bpath = buildpath
if os.path.isabs(bpath):
BUILDPATH = bpath
else:
BUILDPATH = os.path.join(SPECPATH, bpath)
WARNFILE = os.path.join(BUILDPATH, 'warn%s.txt' % specnm)
if not os.path.exists(BUILDPATH):
os.makedirs(BUILDPATH)
# Executing the specfile (it's a valid python file)
execfile(spec)
def __add_options(parser):
parser.add_option('--buildpath', default=DEFAULT_BUILDPATH,
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', 'SPECNAME'))
parser.add_option('--upx-dir', default=None,
help='Directory containing UPX (default: search in path)')
parser.add_option("-a", "--ascii", action="store_true",
help="do NOT include unicode encodings "
"(default: included if available)")
def main(specfile, buildpath, noconfirm, ascii=False, **kw):
global config
global icon, versioninfo, winresource, winmanifest, pyasm
global HIDDENIMPORTS, NOCONFIRM
NOCONFIRM = noconfirm
# Test unicode support.
if not ascii:
HIDDENIMPORTS.extend(misc.get_unicode_modules())
# FIXME: this should be a global import, but can't due to recursive imports
import PyInstaller.configure as configure
config = configure.get_config(kw.get('upx_dir'))
if config['hasRsrcUpdate']:
from PyInstaller.utils import icon, versioninfo, winresource
pyasm = bindepend.getAssemblies(sys.executable)
else:
pyasm = None
if config['hasUPX']:
setupUPXFlags()
if not config['useELFEXE']:
EXE.append_pkg = 0
build(specfile, buildpath)
| 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
from PyInstaller import HOMEPATH
from PyInstaller import is_win, is_cygwin, is_darwin
onefiletmplt = """# -*- mode: python -*-
a = Analysis(%(scripts)s,
pathex=%(pathex)s,
hiddenimports=%(hiddenimports)r,
hookspath=%(hookspath)r)
pyz = PYZ(a.pure)
exe = EXE(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)
"""
onedirtmplt = """# -*- mode: python -*-
a = Analysis(%(scripts)s,
pathex=%(pathex)s,
hiddenimports=%(hiddenimports)r,
hookspath=%(hookspath)r)
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(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=%(strip)s,
upx=%(upx)s,
name=os.path.join(%(distdir)s, '%(name)s'))
"""
comsrvrtmplt = """# -*- mode: python -*-
a = Analysis(%(scripts)s,
pathex=%(pathex)s,
hiddenimports=%(hiddenimports)r,
hookspath=%(hookspath)r)
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'))
"""
bundleexetmplt = """app = BUNDLE(exe,
name=os.path.join(%(distdir)s, '%(exename)s.app'))
"""
bundletmplt = """app = BUNDLE(coll,
name=os.path.join(%(distdir)s, '%(name)s.app'))
"""
def quote_win_filepath( path ):
# quote all \ with another \ after using normpath to clean up the path
return os.path.normpath(path).replace('\\', '\\\\')
# 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 = (
(HOMEPATH, "HOMEPATH"),
)
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 __add_options(parser):
"""
Add the `Makespec` options to a option-parser instance or a
option group.
"""
g = parser.add_option_group('What to generate')
g.add_option("-F", "--onefile", dest="onefile",
action="store_true", default=False,
help="create a single file deployment")
g.add_option("-D", "--onedir", dest="onefile",
action="store_false",
help="create a single directory deployment (default)")
g.add_option("-o", "--out",
dest="workdir", metavar="DIR",
help="generate the spec file in the specified directory "
"(default: current directory)")
g.add_option("-n", "--name",
help="name to assign to the project "
"(default: first script's basename)")
g = parser.add_option_group('What to bundle, where to search')
g.add_option("-p", "--paths", 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('--hidden-import',
action='append',
metavar="MODULENAME", dest='hiddenimports',
help='import hidden in the script(s). This option can '
'be used multiple times.')
g.add_option("--additional-hooks-dir", action="append", dest="hookspath",
help="additional path to search for hooks "
"(may be given several times)")
g = parser.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 for "
"packaging. This will make the packaged executable be "
"more verbose when run."))
g.add_option("-s", "--strip", action="store_true",
help="strip the exe and shared libs "
"(don't try this on Windows)")
g.add_option("--noupx", action="store_true", default=False,
help="do not use UPX even if available (works differently "
"between Windows and *nix)")
#p.add_option("-Y", "--crypt", metavar="FILE",
# help="encrypt pyc/pyo files")
g = parser.add_option_group('Windows and Mac OS X specific options')
g.add_option("-c", "--console", "--nowindowed", dest="console",
action="store_true", default=True,
help="use a console subsystem executable (default)")
g.add_option("-w", "--windowed", "--noconsole", dest="console",
action="store_false",
help="use a windowed subsystem executable, which on Windows "
"does not open the console when the program is launched."
'On Mac OS X it allows running gui applications and also'
'creates an .app bundle.'
'Mandatory for gui applications on Mac OS X')
g.add_option("-i", "--icon", dest="icon_file",
metavar="FILE.ICO or FILE.EXE,ID or FILE.ICNS",
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. "
"If FILE is an .icns file, add the icon to the final "
".app bundle on Mac OS X (for Mac not yet implemented)")
g = parser.add_option_group('Windows specific options')
g.add_option("--version-file",
dest="version_file", metavar="FILE",
help="add a version resource from FILE to the exe")
g.add_option("-m", "--manifest", metavar="FILE or XML",
help="add manifest FILE or XML to the exe")
g.add_option("-r", "--resource", 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.")
def main(scripts, name=None, onefile=0,
console=True, debug=False, strip=0, noupx=0, comserver=0,
workdir=None, pathex=[], version_file=None,
icon_file=None, manifest=None, resources=[], crypt=None,
hiddenimports=None, hookspath=None, **kwargs):
if not name:
name = os.path.splitext(os.path.basename(scripts[0]))[0]
distdir = "dist"
builddir = os.path.join('build', 'pyi.' + sys.platform, name)
pathex = pathex[:]
if workdir is None:
workdir = os.getcwd()
pathex.append(workdir)
else:
pathex.append(os.getcwd())
if workdir == HOMEPATH:
workdir = os.path.join(HOMEPATH, 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:
resources = map(quote_win_filepath, resources)
exe_options = "%s, resources=%s" % (exe_options, repr(resources))
hiddenimports = hiddenimports or []
scripts = map(Path, scripts)
d = {'scripts':scripts,
'pathex' :pathex,
'hiddenimports': hiddenimports,
'hookspath': hookspath,
#'exename': '',
'name': name,
'distdir': repr(distdir),
'builddir': repr(builddir),
'debug': debug,
'strip': strip,
'upx' : not noupx,
'crypt' : repr(crypt),
'crypted': crypt is not None,
'console': console or debug,
'exe_options': exe_options}
if is_win or is_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 is_win and not is_darwin:
d['console'] = True
specfnm = os.path.join(workdir, name+'.spec')
specfile = open(specfnm, 'w')
if onefile:
specfile.write(onefiletmplt % d)
if not console:
specfile.write(bundleexetmplt % d)
elif comserver:
specfile.write(comsrvrtmplt % d)
if not console:
specfile.write(bundletmplt % d)
else:
specfile.write(onedirtmplt % d)
if not console:
specfile.write(bundletmplt % d)
specfile.close()
return specfnm
| Python |
#! -*- mode: python; coding: utf-8 -*-
"""
Logging module for PyInstaller
"""
#
# Copyright 2011 by Hartmut Goebel <h.goebel@goebel-consult.de>
#
# 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/>.
#
__all__ = ['getLogger', 'INFO', 'WARN', 'DEBUG', 'ERROR', 'FATAL']
import logging
from logging import getLogger, INFO, WARN, DEBUG, ERROR, FATAL
FORMAT = '%(relativeCreated)d %(levelname)s: %(message)s'
try:
logging.basicConfig(format=FORMAT, level=logging.INFO)
except TypeError:
# In Python 2.3 basicConfig does not accept arguments
# :todo: remove when dropping Python 2.3 compatibility
logging.basicConfig()
root = logging.getLogger()
assert len(root.handlers) == 1
root.handlers[0].setFormatter(logging.Formatter(FORMAT))
root.setLevel(logging.INFO)
logger = getLogger('PyInstaller')
def __add_options(parser):
levels = ('DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
parser.add_option('--log-level',
choices=levels,
default='INFO',
dest='loglevel',
help=('Log level '
'(default: %%default, choose one of %s)'
% ', '.join(levels))
)
def __process_options(parser, opts):
try:
level = getattr(logging, opts.loglevel.upper())
except AttributeError:
parser.error('Unknown log level `%s`' % opts.loglevel)
logger.setLevel(level)
| Python |
# Subclass of Archive that can be understood by a C program (see launch.c).
# 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 archive
import struct
import sys
try:
import zlib
except ImportError:
zlib = archive.DummyZlib()
class CTOC:
"""A class encapsulating the table of contents of a CArchive.
When written to disk, it is easily read from C."""
ENTRYSTRUCT = '!iiiibc' #(structlen, dpos, dlen, ulen, flag, typcd) followed by name
def __init__(self):
self.data = []
def frombinary(self, s):
"""Decode the binary string into an in memory list.
S is a binary string."""
entrylen = struct.calcsize(self.ENTRYSTRUCT)
p = 0
while p<len(s):
(slen, dpos, dlen, ulen, flag, typcd) = struct.unpack(self.ENTRYSTRUCT,
s[p:p+entrylen])
nmlen = slen - entrylen
p = p + entrylen
(nm,) = struct.unpack(`nmlen`+'s', s[p:p+nmlen])
p = p + nmlen
# version 4
# self.data.append((dpos, dlen, ulen, flag, typcd, nm[:-1]))
# version 5
# nm may have up to 15 bytes of padding
pos = nm.find('\0')
if pos < 0:
self.data.append((dpos, dlen, ulen, flag, typcd, nm))
else:
self.data.append((dpos, dlen, ulen, flag, typcd, nm[:pos]))
#end version 5
def tobinary(self):
"""Return self as a binary string."""
entrylen = struct.calcsize(self.ENTRYSTRUCT)
rslt = []
for (dpos, dlen, ulen, flag, typcd, nm) in self.data:
nmlen = len(nm) + 1 # add 1 for a '\0'
# version 4
# rslt.append(struct.pack(self.ENTRYSTRUCT+`nmlen`+'s',
# nmlen+entrylen, dpos, dlen, ulen, flag, typcd, nm+'\0'))
# version 5
# align to 16 byte boundary so xplatform C can read
toclen = nmlen + entrylen
if toclen % 16 == 0:
pad = '\0'
else:
padlen = 16 - (toclen % 16)
pad = '\0'*padlen
nmlen = nmlen + padlen
rslt.append(struct.pack(self.ENTRYSTRUCT+`nmlen`+'s',
nmlen+entrylen, dpos, dlen, ulen, flag, typcd, nm+pad))
# end version 5
return ''.join(rslt)
def add(self, dpos, dlen, ulen, flag, typcd, nm):
"""Add an entry to the table of contents.
DPOS is data position.
DLEN is data length.
ULEN is the uncompressed data len.
FLAG says if the data is compressed.
TYPCD is the "type" of the entry (used by the C code)
NM is the entry's name."""
self.data.append((dpos, dlen, ulen, flag, typcd, nm))
def get(self, ndx):
"""return the toc entry (tuple) at index NDX"""
return self.data[ndx]
def __getitem__(self, ndx):
return self.data[ndx]
def find(self, name):
"""Return the index of the toc entry with name NAME.
Return -1 for failure."""
for i, nm in enumerate(self.data):
if nm[-1] == name:
return i
return -1
class CArchive(archive.Archive):
"""An Archive subclass that an hold arbitrary data.
Easily handled from C or from Python."""
MAGIC = 'MEI\014\013\012\013\016'
HDRLEN = 0
TOCTMPLT = CTOC
TRLSTRUCT = '!8siiii'
TRLLEN = 24
LEVEL = 9
def __init__(self, path=None, start=0, len=0):
"""Constructor.
PATH is path name of file (create an empty CArchive if path is None).
START is the seekposition within PATH.
LEN is the length of the CArchive (if 0, then read till EOF). """
self.len = len
archive.Archive.__init__(self, path, start)
def checkmagic(self):
"""Verify that self is a valid CArchive.
Magic signature is at end of the archive."""
#magic is at EOF; if we're embedded, we need to figure where that is
if self.len:
self.lib.seek(self.start+self.len, 0)
else:
self.lib.seek(0, 2)
filelen = self.lib.tell()
if self.len:
self.lib.seek(self.start+self.len-self.TRLLEN, 0)
else:
self.lib.seek(-self.TRLLEN, 2)
(magic, totallen, tocpos, toclen, pyvers) = struct.unpack(self.TRLSTRUCT,
self.lib.read(self.TRLLEN))
if magic != self.MAGIC:
raise RuntimeError("%s is not a valid %s archive file"
% (self.path, self.__class__.__name__))
self.pkgstart = filelen - totallen
if self.len:
if totallen != self.len or self.pkgstart != self.start:
raise RuntimeError, "Problem with embedded archive in %s" % self.path
self.tocpos, self.toclen = tocpos, toclen
def loadtoc(self):
"""Load the table of contents into memory."""
self.toc = self.TOCTMPLT()
self.lib.seek(self.pkgstart+self.tocpos)
tocstr = self.lib.read(self.toclen)
self.toc.frombinary(tocstr)
def extract(self, name):
"""Get the contents of an entry.
NAME is an entry name.
Return the tuple (ispkg, contents).
For non-Python resoures, ispkg is meaningless (and 0).
Used by the import mechanism."""
if type(name) == type(''):
ndx = self.toc.find(name)
if ndx == -1:
return None
else:
ndx = name
(dpos, dlen, ulen, flag, typcd, nm) = self.toc.get(ndx)
self.lib.seek(self.pkgstart+dpos)
rslt = self.lib.read(dlen)
if flag == 2:
global AES
import AES
key = rslt[:32]
# Note: keep this in sync with bootloader's code
rslt = AES.new(key, AES.MODE_CFB, "\0"*AES.block_size).decrypt(rslt[32:])
if flag == 1 or flag == 2:
rslt = zlib.decompress(rslt)
if typcd == 'M':
return (1, rslt)
return (0, rslt)
def contents(self):
"""Return the names of the entries"""
rslt = []
for (dpos, dlen, ulen, flag, typcd, nm) in self.toc:
rslt.append(nm)
return rslt
def add(self, entry):
"""Add an ENTRY to the CArchive.
ENTRY must have:
entry[0] is name (under which it will be saved).
entry[1] is fullpathname of the file.
entry[2] is a flag for it's storage format (0==uncompressed,
1==compressed)
entry[3] is the entry's type code.
Version 5:
If the type code is 'o':
entry[0] is the runtime option
eg: v (meaning verbose imports)
u (menaing unbuffered)
W arg (warning option arg)
s (meaning do site.py processing."""
(nm, pathnm, flag, typcd) = entry[:4]
# version 5 - allow type 'o' = runtime option
try:
if typcd in ('o', 'd'):
s = ''
flag = 0
elif typcd == 's':
# If it's a source code file, add \0 terminator as it will be
# executed as-is by the bootloader.
s = open(pathnm, 'rU').read()
s = s + '\n\0'
else:
s = open(pathnm, 'rb').read()
except IOError:
print "Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd)
raise
ulen = len(s)
assert flag in range(3)
if flag == 1 or flag == 2:
s = zlib.compress(s, self.LEVEL)
if flag == 2:
global AES
import AES, Crypt
key = Crypt.gen_random_key(32)
# Note: keep this in sync with bootloader's code
s = key + AES.new(key, AES.MODE_CFB, "\0"*AES.block_size).encrypt(s)
dlen = len(s)
where = self.lib.tell()
if typcd == 'm':
if pathnm.find('.__init__.py') > -1:
typcd = 'M'
self.toc.add(where, dlen, ulen, flag, typcd, nm)
self.lib.write(s)
def save_toc(self, tocpos):
"""Save the table of contents to disk."""
self.tocpos = tocpos
tocstr = self.toc.tobinary()
self.toclen = len(tocstr)
self.lib.write(tocstr)
def save_trailer(self, tocpos):
"""Save the trailer to disk.
CArchives can be opened from the end - the trailer points
back to the start. """
totallen = tocpos + self.toclen + self.TRLLEN
pyvers = sys.version_info[0]*10 + sys.version_info[1]
trl = struct.pack(self.TRLSTRUCT, self.MAGIC, totallen,
tocpos, self.toclen, pyvers)
self.lib.write(trl)
def openEmbedded(self, name):
"""Open a CArchive of name NAME embedded within this CArchive."""
ndx = self.toc.find(name)
if ndx == -1:
raise KeyError, "Member '%s' not found in %s" % (name, self.path)
(dpos, dlen, ulen, flag, typcd, nm) = self.toc.get(ndx)
if flag:
raise ValueError, "Cannot open compressed archive %s in place"
return CArchive(self.path, self.pkgstart+dpos, dlen)
| Python |
#
# Copyright (C) 2005-2011, 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
#
### **NOTE** This module is used during bootstrap.
### Import *ONLY* builtin modules.
### List of built-in modules: sys.builtin_module_names
import sys
import imp
import marshal
import zipimport
def debug(msg):
if 0:
sys.stderr.write(msg + "\n")
sys.stderr.flush()
#=======================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.
# A shadowpath (a dictionary mapping the names in
# sys.path to their owners) is used so that sys.path
# (or a package's __path__) is still a bunch of strings,
class OwnerError(IOError):
def __str__(self):
return "<OwnerError %s>" % self.message
class Owner:
"""
Base class for loading Python bytecode from different places.
"""
def __init__(self, path):
self.path = path
def __str__(self):
return self.path
def getmod(self, nm):
return None
class DirOwner(Owner):
"""
Load bytecode of Python modules from file system.
"""
def __init__(self, path):
if path == '':
path = _os_getcwd()
if not pathisdir(path):
raise OwnerError("%s is not a directory" % path)
Owner.__init__(self, path)
def getmod(self, nm, getsuffixes=imp.get_suffixes,
loadco=marshal.loads, newmod=imp.new_module):
pth = _os_path_join(self.path, nm)
possibles = [(pth, 0, None)]
if pathisdir(pth) and caseOk(pth):
possibles.insert(0, (_os_path_join(pth, '__init__'), 1, pth))
py = pyc = None
for pth, ispkg, pkgpth in possibles:
for ext, mode, typ in getsuffixes():
attempt = pth + ext
try:
st = _os_stat(attempt)
except OSError, e:
assert e.errno == 2 # [Errno 2] No such file or directory
else:
# Check case
if not caseOk(attempt):
continue
if typ == imp.C_EXTENSION:
fp = open(attempt, 'rb')
mod = imp.load_module(nm, fp, attempt, (ext, mode, typ))
if hasattr(mod, "__setattr__"):
mod.__file__ = attempt
else:
# Some modules (eg: Python for .NET) have no __setattr__
# and dict entry have to be set
mod.__dict__["__file__"] = attempt
return mod
elif typ == imp.PY_SOURCE:
py = (attempt, st)
else:
pyc = (attempt, st)
if py or pyc:
break
if py is None and pyc is None:
return None
while 1:
if pyc is None or py and pyc[1][8] < py[1][8]:
try:
bytecode = compile(open(py[0], 'rU').read() + '\n', py[0], 'exec')
break
except SyntaxError, e:
print "Invalid syntax in %s" % py[0]
print e.args
raise
elif pyc:
stuff = open(pyc[0], 'rb').read()
try:
bytecode = loadco(stuff[8:])
break
except (ValueError, EOFError):
pyc = None
else:
return None
mod = newmod(nm)
mod.__file__ = bytecode.co_filename
if ispkg:
mod.__path__ = [pkgpth]
subimporter = PathImportDirector(mod.__path__)
mod.__importsub__ = subimporter.getmod
mod.__co__ = bytecode
return mod
class ZipOwner(Owner):
"""
Load bytecode of Python modules from .egg files.
"""
def __init__(self, path):
try:
self.__zip = zipimport.zipimporter(path)
except zipimport.ZipImportError, e:
raise OwnerError('%s: %s' % (str(e), path))
Owner.__init__(self, path)
def getmod(self, nm, newmod=imp.new_module):
# We cannot simply use zipimport.load_module here
# because it both loads (= create module object)
# and imports (= execute bytecode). Instead, our
# getmod() functions are supposed to only load the modules.
# Note that imp.load_module() does the right thing, instead.
debug('zipimport try: %s within %s' % (nm, self.__zip))
try:
bytecode = self.__zip.get_code(nm)
mod = newmod(nm)
mod.__file__ = bytecode.co_filename
if self.__zip.is_package(nm):
mod.__path__ = [_os_path_join(self.path, nm)]
subimporter = PathImportDirector(mod.__path__)
mod.__importsub__ = subimporter.getmod
if self.path.endswith(".egg"):
# Fixup some additional special attribute so that
# pkg_resources works correctly.
# TODO: couldn't we fix these attributes always,
# for all zip files?
mod.__file__ = _os_path_join(
_os_path_join(self.path, nm), "__init__.py")
mod.__loader__ = self.__zip
mod.__co__ = bytecode
return mod
except zipimport.ZipImportError:
debug('zipimport not found %s' % nm)
return None
# Define order where to look for Python modules first.
# 1. PYZOwner: look in executable created by PyInstaller.
# (_pyi_bootstrap.py will insert it (archive.PYZOwner) in front later.)
# 2. ZipOwner: zip files (.egg files)
# 3. DirOwner: file system
# 4. Owner: module not found
_globalownertypes = [
ZipOwner,
DirOwner,
Owner,
]
#===================Import Directors====================================#
# ImportDirectors live on the metapath
# There's one for builtins, one for frozen modules, and one for sys.path
# 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):
# Return initialized built-in module object or None
# if there is no built-in module with that name.
return imp.init_builtin(nm)
class PathImportDirector(ImportDirector):
def __init__(self, pathlist=None, importers=None, ownertypes=None):
self.path = pathlist
if ownertypes == None:
self.ownertypes = _globalownertypes
else:
self.ownertypes = ownertypes
if importers:
self.shadowpath = importers
else:
self.shadowpath = {}
self.building = {}
def __str__(self):
return str(self.path or sys.path)
def getmod(self, nm):
mod = None
for thing in (self.path or sys.path):
if isinstance(thing, basestring):
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 path in self.building:
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)
except OwnerError:
pass
else:
break
del self.building[path]
return owner
def getDescr(fnm):
ext = getpathext(fnm)
for (suffix, mode, typ) in imp.get_suffixes():
if suffix == ext:
return (suffix, mode, typ)
#=================ImportManager============================#
# The one-and-only ImportManager
# ie, the builtin import
UNTRIED = -1
class ImportManagerException(Exception):
def __init__(self, args):
self.args = args
def __repr__(self):
return "<%s: %s>" % (self.__name__, self.args)
class ImportManager:
# really the equivalent of builtin import
def __init__(self):
self.metapath = [
BuiltinImportDirector(),
PathImportDirector()
]
self.threaded = 0
self.rlock = None
self.locker = None
self.setThreaded()
def setThreaded(self):
thread = sys.modules.get('thread', None)
if thread and not self.threaded:
#debug("iu setting threaded")
self.threaded = 1
self.rlock = thread.allocate_lock()
self._get_ident = thread.get_ident
def install(self):
import __builtin__
__builtin__.__import__ = self.importHook
__builtin__.reload = self.reloadHook
def importHook(self, name, globals=None, locals=None, fromlist=None, level=-1):
__globals_name = None
if globals:
__globals_name = globals.get('__name__')
# first see if we could be importing a relative name
debug("importHook(%s, %s, locals, %s, %s)" % (name, __globals_name, fromlist, level))
_sys_modules_get = sys.modules.get
_self_doimport = self.doimport
threaded = self.threaded
# break the name being imported up so we get:
# a.b.c -> [a, b, c]
nmparts = namesplit(name)
if not globals:
contexts = [None]
if level > 0:
raise RuntimeError("Relative import requires 'globals'")
elif level == 0:
# absolute import, do not try relative
contexts = [None]
else: # level != 0
importernm = globals.get('__name__', '')
ispkg = hasattr(_sys_modules_get(importernm), '__path__')
debug('importernm %s' % importernm)
if level < 0:
# behaviour up to Python 2.4 (and default in Python 2.5)
# add the package to searched contexts
contexts = [None]
else:
# relative import, do not try absolute
if not importernm:
raise RuntimeError("Relative import requires package")
# level=1 => current package
# level=2 => previous package => drop 1 level
if level > 1:
importernm = importernm.split('.')[:-level + 1]
importernm = '.'.join(importernm)
contexts = [None]
if importernm:
if ispkg:
# If you use the "from __init__ import" syntax, the package
# name will have a __init__ in it. We want to strip it.
if importernm[-len(".__init__"):] == ".__init__":
importernm = importernm[:-len(".__init__")]
contexts.insert(0, importernm)
else:
pkgnm = packagename(importernm)
if pkgnm:
contexts.insert(0, pkgnm)
# so contexts is [pkgnm, None], [pkgnm] or just [None]
for context in contexts:
ctx = context
i = 0
for i, nm in enumerate(nmparts):
debug(" importHook trying %s in %s" % (nm, ctx))
if ctx:
fqname = ctx + '.' + nm
else:
fqname = nm
if threaded:
self._acquire()
try:
mod = _sys_modules_get(fqname, UNTRIED)
if mod is UNTRIED:
debug('trying %s %s %s' % (nm, ctx, fqname))
mod = _self_doimport(nm, ctx, fqname)
finally:
if threaded:
self._release()
if mod:
ctx = fqname
else:
break
else:
# no break, point i beyond end
i = i + 1
if i:
break
if i < len(nmparts):
if ctx and hasattr(sys.modules[ctx], nmparts[i]):
debug("importHook done with %s %s %s (case 1)" % (name, __globals_name, fromlist))
return sys.modules[nmparts[0]]
# Some executables may fail if 'fqname' is not in sys.modules.
try:
del sys.modules[fqname]
except KeyError:
pass
raise ImportError("No module named %s" % fqname)
if not fromlist:
debug("importHook done with %s %s %s (case 2)" % (name, __globals_name, fromlist))
if context:
return sys.modules[context + '.' + nmparts[0]]
return sys.modules[nmparts[0]]
bottommod = sys.modules[ctx]
if hasattr(bottommod, '__path__'):
fromlist = list(fromlist)
i = 0
while i < len(fromlist):
nm = fromlist[i]
if nm == '*':
fromlist[i:i + 1] = list(getattr(bottommod, '__all__', []))
if i >= len(fromlist):
break
nm = fromlist[i]
i = i + 1
if not hasattr(bottommod, nm):
if threaded:
self._acquire()
try:
mod = self.doimport(nm, ctx, ctx + '.' + nm)
finally:
if threaded:
self._release()
debug("importHook done with %s %s %s (case 3)" % (name, __globals_name, fromlist))
return bottommod
def doimport(self, nm, parentnm, fqname, reload=0):
# Not that nm is NEVER a dotted name at this point
debug("doimport(%s, %s, %s)" % (nm, parentnm, fqname))
if parentnm:
parent = sys.modules[parentnm]
if hasattr(parent, '__path__'):
importfunc = getattr(parent, '__importsub__', None)
if not importfunc:
subimporter = PathImportDirector(parent.__path__)
importfunc = parent.__importsub__ = subimporter.getmod
debug("using parent's importfunc: %s" % importfunc)
mod = importfunc(nm)
if mod and not reload:
setattr(parent, nm, mod)
else:
debug("..parent not a package")
return None
else:
parent = None
# now we're dealing with an absolute import
for director in self.metapath:
mod = director.getmod(nm)
if mod:
break
if mod:
if hasattr(mod, "__setattr__"):
mod.__name__ = fqname
else:
# Some modules (eg: Python for .NET) have no __setattr__
# and dict entry have to be set
mod.__dict__["__name__"] = fqname
if reload:
sys.modules[fqname].__dict__.update(mod.__dict__)
else:
sys.modules[fqname] = mod
if hasattr(mod, '__co__'):
co = mod.__co__
del mod.__co__
try:
if reload:
exec co in sys.modules[fqname].__dict__
else:
exec co in mod.__dict__
except:
# In Python 2.4 and above, sys.modules is left clean
# after a broken import. We need to do the same to
# achieve perfect compatibility (see ticket #32).
if sys.version_info >= (2, 4):
# FIXME: how can we recover from a broken reload()?
# Should we save the mod dict and restore it in case
# of failure?
if not reload:
# Some modules (eg: dbhash.py) cleanup
# sys.modules themselves. We should then
# be lenient and avoid errors.
sys.modules.pop(fqname, None)
if hasattr(parent, nm):
delattr(parent, nm)
raise
if fqname == 'thread' and not self.threaded:
#debug("thread detected!")
self.setThreaded()
else:
sys.modules[fqname] = None
debug("..found %s when looking for %s" % (mod, fqname))
return mod
def reloadHook(self, mod):
fqnm = mod.__name__
nm = namesplit(fqnm)[-1]
parentnm = packagename(fqnm)
newmod = self.doimport(nm, parentnm, fqnm, reload=1)
#mod.__dict__.update(newmod.__dict__)
return newmod
def _acquire(self):
if self.rlock.locked():
if self.locker == self._get_ident():
self.lockcount = self.lockcount + 1
#debug("_acquire incrementing lockcount to %s" % self.lockcount)
return
self.rlock.acquire()
self.locker = self._get_ident()
self.lockcount = 0
#debug("_acquire first time!")
def _release(self):
if self.lockcount:
self.lockcount = self.lockcount - 1
#debug("_release decrementing lockcount to %s" % self.lockcount)
else:
self.locker = None
self.rlock.release()
#debug("_release releasing lock!")
#========= some helper functions =============================#
def packagename(s):
"""
For package name like 'module.submodule.subsubmodule' returns
'module.submodule'. If name does not contain any dots '.',
empty string '' is returned.
"""
i = s.rfind('.')
if i >= 0:
return s[:i]
else:
return ''
def namesplit(s):
"""
Split package name at the position of dot '.'.
Examples:
'module.submodule' => ['module', 'submodule']
'module' => ['module']
'' => []
"""
rslt = []
# Ensure that for empty string '' an empty list is returned.
if s:
rslt = s.split('.')
return rslt
def getpathext(fnm):
i = fnm.rfind('.')
if i >= 0:
return fnm[i:]
else:
return ''
def pathisdir(pathname):
"Local replacement for os.path.isdir()."
try:
s = _os_stat(pathname)
except OSError:
return None
return (s[0] & 0170000) == 0040000
_os_stat = _os_path_join = _os_getcwd = _os_path_dirname = None
_os_environ = _os_listdir = _os_path_basename = None
_os_sep = None
def _os_bootstrap():
"""
Set up 'os' module replacement functions for use during import bootstrap.
"""
global _os_stat, _os_getcwd, _os_environ, _os_listdir
global _os_path_join, _os_path_dirname, _os_path_basename
global _os_sep
names = sys.builtin_module_names
join = dirname = environ = listdir = basename = None
mindirlen = 0
# Only 'posix' and 'nt' os specific modules are supported.
# 'dos', 'os2' and 'mac' (MacOS 9) are not supported.
if 'posix' in names:
from posix import stat, getcwd, environ, listdir
sep = _os_sep = '/'
mindirlen = 1
elif 'nt' in names:
from nt import stat, getcwd, environ, listdir
sep = _os_sep = '\\'
mindirlen = 3
else:
raise ImportError('no os specific module found')
if join is None:
def join(a, b, sep=sep):
if a == '':
return b
lastchar = a[-1:]
if lastchar == '/' or lastchar == sep:
return a + b
return a + sep + b
if dirname is None:
def dirname(a, sep=sep, mindirlen=mindirlen):
for i in range(len(a) - 1, -1, -1):
c = a[i]
if c == '/' or c == sep:
if i < mindirlen:
return a[:i + 1]
return a[:i]
return ''
if basename is None:
def basename(p):
i = p.rfind(sep)
if i == -1:
return p
else:
return p[i + len(sep):]
def _listdir(dir, cache=None):
# The cache is not used. It was found to cause problems
# with programs that dynamically add python modules to be
# reimported by that same program (i.e., plugins), because
# the cache is only built once at the beginning, and never
# updated. So, we must really list the directory again.
return listdir(dir)
_os_stat = stat
_os_getcwd = getcwd
_os_path_join = join
_os_path_dirname = dirname
_os_environ = environ
_os_listdir = _listdir
_os_path_basename = basename
_os_bootstrap()
if 'PYTHONCASEOK' not in _os_environ:
def caseOk(filename):
files = _os_listdir(_os_path_dirname(filename))
return _os_path_basename(filename) in files
else:
def caseOk(filename):
return True
| 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
def debug(msg):
if 0:
sys.stderr.write(msg + "\n")
sys.stderr.flush()
_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes())
for nm in ('nt', 'posix'):
if nm in sys.builtin_module_names:
mod = __import__(nm)
_listdir = mod.listdir
_environ = mod.environ
break
versuffix = '%d%d' % sys.version_info[:2] # :todo: is this still used?
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):
## pass
####### 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:
error = RuntimeError
def decompress(self, data):
raise RuntimeError, "zlib required but cannot be imported"
def compress(self, data, lvl):
raise RuntimeError, "zlib required but cannot be imported"
# Used by PYZOwner
import iu
class ZlibArchive(Archive):
"""
ZlibArchive - an archive with compressed entries. Archive is read
from the executable created by PyInstaller.
"""
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], 'rU').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 = txt.replace('\r\n', '\n')
try:
import os
co = compile(txt, self.os.path.join(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):
"""
Load bytecode of Python modules from the executable created by PyInstaller.
Python bytecode is zipped and appended to the executable.
NOTE: PYZ format cannot be replaced by zipimport module.
The problem is that we have no control over zipimport; for instance,
it doesn't work if the zip file is embedded into a PKG appended
to an executable, like we create in one-file.
"""
def __init__(self, path):
try:
# Unzip zip archive bundled with the executable.
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, bytecode = rslt
mod = newmod(nm)
# Replace bytecode.co_filename by something more meaningful:
# e.g. /absolute/path/frozen_executable?12345/os/path.pyc
# Paths from developer machine are masked.
try:
# Python packages points to files __init__.pyc.
if ispkg:
mod.__file__ = iu._os_path_join(iu._os_path_join(self.path,
nm.replace('.', iu._os_sep)), '__init__.pyc')
else:
mod.__file__ = iu._os_path_join(self.path,
nm.replace('.', iu._os_sep) + '.pyc')
except AttributeError:
raise ImportError("PYZ entry '%s' (%s) is not a valid code object"
% (nm, repr(bytecode)))
# Python has modules and packages. A Python package is container
# for several modules or packages.
if ispkg:
# Since PYTHONHOME is set in bootloader, 'sys.prefix' points to the
# correct path where PyInstaller should find bundled dynamic
# libraries. In one-file mode it points to the tmp directory where
# bundled files are extracted at execution time.
localpath = sys.prefix
# A python packages has to have __path__ attribute.
mod.__path__ = [iu._os_path_dirname(mod.__file__), self.path, localpath,
]
debug("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__ = bytecode
return mod
class PkgInPYZImporter:
def __init__(self, name, owner):
self.name = name
self.owner = owner
def getmod(self, nm):
debug("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)
| Python |
#
| 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
import os
import sys
import re
from glob import glob
# Required for extracting eggs.
import zipfile
from PyInstaller import is_win, is_unix, is_aix, is_cygwin, is_darwin, is_py26
from PyInstaller.depend import dylib
from PyInstaller.utils import winutils
import PyInstaller.compat as compat
from PyInstaller.compat import set
import PyInstaller.log as logging
logger = logging.getLogger('PyInstaller.build.bindepend')
seen = {}
if is_win:
if is_py26:
try:
import win32api
import pywintypes
except ImportError:
raise SystemExit("Error: PyInstaller for Python 2.6+ on Windows "
"needs pywin32.\r\nPlease install from "
"http://sourceforge.net/projects/pywin32/")
from PyInstaller.utils.winmanifest import RT_MANIFEST
from PyInstaller.utils.winmanifest import GetManifestResources
from PyInstaller.utils.winmanifest import Manifest
try:
from PyInstaller.utils.winmanifest import winresource
except ImportError, detail:
winresource = None
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 + winutils.get_system_path()
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, mod.lower())
if os.path.exists(npth):
return npth
return ''
def _getImports_pe(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 PyInstaller.lib.pefile as pefile
dlls = set()
# By default library pefile parses all PE information.
# We are only interested in the list of dependent dlls.
# Performance is improved by reading only needed information.
# https://code.google.com/p/pefile/wiki/UsageExamples
pe = pefile.PE(pth, fast_load=True)
pe.parse_data_directories(directories=[
pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT']])
# Some libraries have no other binary dependencies. Use empty list
# in that case. Otherwise pefile would return None.
# e.g. C:\windows\system32\kernel32.dll on Wine
for entry in getattr(pe, 'DIRECTORY_ENTRY_IMPORT', []):
dlls.add(entry.dll)
return dlls
def _extract_from_egg(toc):
"""
Ensure all binary modules in zipped eggs get extracted and
included with the frozen executable.
The supplied toc is directly modified to make changes effective.
return modified table of content
"""
for item in toc:
# Item is a tupple
# (mod_name, path, type)
modname, pth, typ = item
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
# Replace value in original data structure.
toc.remove(item)
toc.append((modname, pth, typ))
return toc
def Dependencies(lTOC, 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
"""
# Extract all necessary binary modules from Python eggs to be included
# directly with PyInstaller.
lTOC = _extract_from_egg(lTOC)
for nm, pth, typ in lTOC:
if seen.get(nm.upper(), 0):
continue
logger.debug("Analyzing %s", pth)
seen[nm.upper()] = 1
if is_win:
for ftocnm, fn in selectAssemblies(pth, manifest):
lTOC.append((ftocnm, fn, 'BINARY'))
for lib, npth in selectImports(pth, xtrapath):
if seen.get(lib.upper(), 0) or seen.get(npth.upper(), 0):
continue
seen[npth.upper()] = 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
egg_cache = compat.getenv('PYTHON_EGG_CACHE')
if egg_cache is not None:
return egg_cache
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, compat.getenv(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:
raise SystemExit("Error: %s %s" % (eggpth, e))
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 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:
logger.info('Cannot get manifest resource from non-PE '
'file %s', 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:
logger.error("Can not parse manifest resource %s, %s"
"from %s", name, language, pth)
logger.exception(exc)
else:
if manifest.dependentAssemblies:
logger.debug("Dependent assemblies of %s:", pth)
logger.debug(", ".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 manifest:
_depNames = set([dep.name for dep in manifest.dependentAssemblies])
for assembly in getAssemblies(pth):
if seen.get(assembly.getid().upper(), 0):
continue
if manifest and not assembly.name in _depNames:
# Add assembly as dependency to our final output exe's manifest
logger.info("Adding %s to dependent assemblies "
"of final executable", assembly.name)
manifest.dependentAssemblies.append(assembly)
_depNames.add(assembly.name)
if not dylib.include_library(assembly.name):
logger.debug("Skipping assembly %s", assembly.getid())
continue
if assembly.optional:
logger.debug("Skipping optional assembly %s", 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):
logger.debug("Adding %s", ftocnm)
seen[nm.upper()] = 1
seen[fn.upper()] = 1
rv.append((ftocnm, fn))
else:
#logger.info("skipping %s part of assembly %s dependency of %s",
# ftocnm, assembly.name, pth)
pass
else:
logger.error("Assembly %s not found", assembly.getid())
return rv
def selectImports(pth, 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)
for lib in dlls:
if seen.get(lib.upper(), 0):
continue
if not is_win and not is_cygwin:
# all other platforms
npth = lib
lib = os.path.basename(lib)
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 not dylib.include_library(candidatelib):
if (candidatelib.find('libpython') < 0 and
candidatelib.find('Python.framework') < 0):
# skip libs not containing (libpython or Python.framework)
if not seen.get(npth.upper(), 0):
logger.debug("Skipping %s dependency of %s",
lib, os.path.basename(pth))
continue
else:
pass
if npth:
if not seen.get(npth.upper(), 0):
logger.debug("Adding %s dependency of %s",
lib, os.path.basename(pth))
rv.append((lib, npth))
else:
logger.error("lib not found: %s dependency of %s", lib, pth)
return rv
def _getImports_ldd(pth):
"""
Find the binary dependencies of PTH.
This implementation is for ldd platforms (mostly unix).
"""
rslt = set()
if is_aix:
# Match libs of the form 'archive.a(sharedobject.so)'
# Will not match the fake lib '/unix'
lddPattern = re.compile(r"\s+(.*?)(\(.*\))")
else:
lddPattern = re.compile(r"\s+(.*?)\s+=>\s+(.*?)\s+\(.*\)")
for line in compat.exec_command('ldd', pth).strip().splitlines():
m = lddPattern.search(line)
if m:
if is_aix:
lib = m.group(1)
name = os.path.basename(lib) + m.group(2)
else:
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):
# Add lib if it is not already found.
if lib not in rslt:
rslt.add(lib)
else:
logger.error('Can not find %s in path %s (needed by %s)',
name, lib, pth)
return rslt
def _getImports_macholib(pth):
"""
Find the binary dependencies of PTH.
This implementation is for Mac OS X and uses library macholib.
"""
from PyInstaller.lib.macholib.MachO import MachO
from PyInstaller.lib.macholib.mach_o import LC_RPATH
from PyInstaller.lib.macholib.dyld import dyld_find
rslt = set()
seen = set() # Libraries read from binary headers.
## Walk through mach binary headers.
m = MachO(pth)
for header in m.headers:
for idx, name, lib in header.walkRelocatables():
# Sometimes some libraries are present multiple times.
if lib not in seen:
seen.add(lib)
# Walk through mach binary headers and look for LC_RPATH.
# macholib can't handle @rpath. LC_RPATH has to be read
# from the MachO header.
# TODO Do we need to remove LC_RPATH from MachO load commands?
# Will it cause any harm to leave them untouched?
# Removing LC_RPATH should be implemented when getting
# files from the bincache if it is necessary.
run_paths = set()
for header in m.headers:
for command in header.commands:
# A command is a tupple like:
# (<macholib.mach_o.load_command object at 0x>,
# <macholib.mach_o.rpath_command object at 0x>,
# '../lib\x00\x00')
cmd_type = command[0].cmd
if cmd_type == LC_RPATH:
rpath = command[2]
# Remove trailing '\x00' characters.
# e.g. '../lib\x00\x00'
rpath = rpath.rstrip('\x00')
# Make rpath absolute. According to Apple doc LC_RPATH
# is always relative to the binary location.
rpath = os.path.normpath(os.path.join(os.path.dirname(pth), rpath))
run_paths.update([rpath])
## Try to find files in file system.
# In cases with @loader_path or @executable_path
# try to look in the same directory as the checked binary is.
# This seems to work in most cases.
exec_path = os.path.abspath(os.path.dirname(pth))
for lib in seen:
# Suppose that @rpath is not used for system libraries and
# using macholib can be avoided.
# macholib can't handle @rpath.
if lib.startswith('@rpath'):
lib = lib.replace('@rpath', '.') # Make path relative.
final_lib = None # Absolute path to existing lib on disk.
# Try multiple locations.
for run_path in run_paths:
# @rpath may contain relative value. Use exec_path as
# base path.
if not os.path.isabs(run_path):
run_path = os.path.join(exec_path, run_path)
# Stop looking for lib when found in first location.
if os.path.exists(os.path.join(run_path, lib)):
final_lib = os.path.abspath(os.path.join(run_path, lib))
rslt.add(final_lib)
break
# Log error if no existing file found.
if not final_lib:
logger.error('Can not find path %s (needed by %s)', lib, pth)
# Macholib has to be used to get absolute path to libraries.
else:
# macholib can't handle @loader_path. It has to be
# handled the same way as @executable_path.
# It is also replaced by 'exec_path'.
if lib.startswith('@loader_path'):
lib = lib.replace('@loader_path', '@executable_path')
try:
lib = dyld_find(lib, executable_path=exec_path)
rslt.add(lib)
except ValueError:
logger.error('Can not find path %s (needed by %s)', lib, pth)
return rslt
def getImports(pth):
"""
Forwards to the correct getImports implementation for the platform.
"""
if is_win or is_cygwin:
if pth.lower().endswith(".manifest"):
return []
try:
return _getImports_pe(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 logger.isEnabledFor(logging.WARN):
# logg excaption only if level >= warn
logger.warn('Can not get binary dependencies for file: %s', pth)
logger.exception(exception)
return []
elif is_darwin:
return _getImports_macholib(pth)
else:
return _getImports_ldd(pth)
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 is_unix, "Current implementation for Unix only (Linux, Solaris, AIX)"
lib = None
# Look in the LD_LIBRARY_PATH
lp = compat.getenv('LD_LIBRARY_PATH', '')
for path in lp.split(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, compat.exec_command('/sbin/ldconfig', '-p'))
if m:
lib = m.group(0)
# Look in the known safe paths
if lib is None:
paths = ['/lib', '/usr/lib']
if is_aix:
paths.append('/opt/freeware/lib')
for path in paths:
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 = os.path.dirname(lib)
return os.path.join(dir, getSoname(lib))
def getSoname(filename):
"""
Return the soname of a library.
"""
cmd = ["objdump", "-p", "-j", ".dynamic", filename]
m = re.search(r'\s+SONAME\s+([^\s]+)', compat.exec_command(*cmd))
if m:
return m.group(1)
| 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 shutil
import re
import time
import inspect
from PyInstaller import HOMEPATH, PLATFORM
from PyInstaller import is_win, is_unix, is_darwin, is_py24, get_version
import PyInstaller.build as build
import PyInstaller.compat as compat
import PyInstaller.log as logging
import PyInstaller.depend.modules
import PyInstaller.depend.imptracker
logger = logging.getLogger('PyInstaller.configure')
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.
logger.info("trying to build crypt support...")
from distutils.core import run_setup
cwd = os.getcwd()
args = sys.argv[:]
try:
os.chdir(os.path.join(HOMEPATH, "source", "crypto"))
dist = run_setup("setup.py", ["install"])
if dist.have_run.get("install", 0):
config["useCrypt"] = 1
logger.info("... crypto support available")
else:
config["useCrypt"] = 0
logger.info("... error building crypto support")
finally:
os.chdir(cwd)
sys.argv = args
def test_RsrcUpdate(config):
config['hasRsrcUpdate'] = 0
if not is_win:
return
# only available on windows
logger.info("Testing for ability to set icons, version resources...")
try:
import win32api
from PyInstaller.utils import icon, versioninfo
except ImportError, detail:
logger.info('... resource update unavailable - %s', detail)
return
test_exe = os.path.join(HOMEPATH, 'support', 'loader', PLATFORM, 'runw.exe')
if not os.path.exists(test_exe):
config['hasRsrcUpdate'] = 0
logger.error('... 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(compat.getenv('TEMP'), 'me_test_exe.tmp')
shutil.copyfile(test_exe, rw_test_exe)
try:
hexe = win32api.BeginUpdateResource(rw_test_exe, 0)
except:
logger.info('... resource update unavailable - win32api.BeginUpdateResource failed')
else:
win32api.EndUpdateResource(hexe, 1)
config['hasRsrcUpdate'] = 1
logger.info('... resource update available')
os.remove(rw_test_exe)
def test_UPX(config, upx_dir):
logger.debug('Testing for UPX ...')
cmd = "upx"
if upx_dir:
cmd = os.path.normpath(os.path.join(upx_dir, cmd))
hasUPX = 0
try:
vers = compat.exec_command(cmd, '-V').strip().splitlines()
if vers:
v = vers[0].split()[1]
hasUPX = tuple(map(int, v.split(".")))
if is_win and is_py24 and hasUPX < (1, 92):
logger.error('UPX is too old! Python 2.4 under Windows requires UPX 1.92+')
hasUPX = 0
except Exception, e:
if isinstance(e, OSError) and e.errno == 2:
# No such file or directory
pass
else:
logger.info('An exception occured when testing for UPX:')
logger.info(' %r', e)
if hasUPX:
is_available = 'available'
else:
is_available = 'not available'
logger.info('UPX is %s.', is_available)
config['hasUPX'] = hasUPX
config['upx_dir'] = upx_dir
def find_PYZ_dependencies(config):
logger.debug("Computing PYZ dependencies")
# We need to import `archive` from `PyInstaller` directory, but
# not from package `PyInstaller`
import PyInstaller.loader
a = PyInstaller.depend.imptracker.ImportTracker([
os.path.dirname(inspect.getsourcefile(PyInstaller.loader)),
os.path.join(HOMEPATH, 'support')])
a.analyze_r('archive')
mod = a.modules['archive']
toc = build.TOC([(mod.__name__, mod.__file__, 'PYMODULE')])
for i, (nm, fnm, typ) in enumerate(toc):
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, PyInstaller.depend.modules.BuiltinModule):
tmp.append((imported.__name__, imported.__file__, imported.typ))
toc.extend(tmp)
toc.reverse()
config['PYZ_dependencies'] = toc.data
def get_config(upx_dir, **kw):
if is_darwin and compat.architecture() == '64bit':
logger.warn('You are running 64-bit Python: created binaries will only'
' work on Mac OS X 10.6+.\nIf you need 10.4-10.5 compatibility,'
' run Python as a 32-bit binary with this command:\n\n'
' VERSIONER_PYTHON_PREFER_32_BIT=yes arch -i386 %s\n' % sys.executable)
# wait several seconds for user to see this message
time.sleep(4)
# if not set by Make.py we can assume Windows
config = {'useELFEXE': 1}
test_Crypt(config)
test_RsrcUpdate(config)
test_UPX(config, upx_dir)
find_PYZ_dependencies(config)
return config
| Python |
#
# Copyright (C) 2011 by Hartmut Goebel
#
# 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
__all__ = ('HOMEPATH', 'CONFIGDIR', 'PLATFORM',
'VERSION', 'get_version',
'is_py23', 'is_py24', 'is_py25', 'is_py26', 'is_py27',
'is_win', 'is_cygwin', 'is_darwin', 'is_unix', 'is_linux',
'is_solar', 'is_aix')
import os
import sys
# Fail hard if Python does not have minimum required version
if sys.version_info < (2, 3):
raise SystemExit('PyInstaller requires at least Python 2.3, sorry.')
# Extend PYTHONPATH with 3rd party libraries bundled with PyInstaller.
# (otherwise e.g. macholib won't work on Mac OS X)
from PyInstaller import lib
sys.path.insert(0, lib.__path__[0])
from PyInstaller import compat
from PyInstaller.utils import git
VERSION = (2, 0, 0)
is_py23 = compat.is_py23
is_py24 = compat.is_py24
is_py25 = compat.is_py25
is_py26 = compat.is_py26
is_py27 = compat.is_py27
is_win = compat.is_win
is_cygwin = compat.is_cygwin
is_darwin = compat.is_darwin
is_linux = compat.is_linux
is_solar = compat.is_solar
is_aix = compat.is_aix
is_unix = compat.is_unix
HOMEPATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if is_win:
CONFIGDIR = compat.getenv('APPDATA')
if not CONFIGDIR:
CONFIGDIR = os.path.expanduser('~\\Application Data')
elif is_darwin:
CONFIGDIR = os.path.expanduser('~/Library/Application Support')
else:
# According to XDG specification
# http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
CONFIGDIR = compat.getenv('XDG_DATA_HOME')
if not CONFIGDIR:
CONFIGDIR = os.path.expanduser('~/.local/share')
CONFIGDIR = os.path.join(CONFIGDIR, 'pyinstaller')
PLATFORM = compat.system() + '-' + compat.architecture()
# path extensions for module seach
# :fixme: this should not be a global variable
__pathex__ = []
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if len(VERSION) >= 4 and VERSION[3]:
version = '%s%s' % (version, VERSION[3])
# include git revision in version string
if VERSION[3] == 'dev' and VERSION[4] > 0:
version = '%s-%s' % (version, VERSION[4])
return version
| Python |
"""
Python 2.4-like compatibility library for Python 2.3
"""
from itertools import izip, imap
try:
from itertools import tee, groupby
except ImportError:
pass
#
# builtins from 2.4
#
try:
set, frozenset
except NameError:
from sets import Set as set, ImmutableSet as frozenset
try:
sorted
except NameError:
def sorted(iterable, cmp=None, key=None, reverse=False):
if key is not None:
a, b = tee(iterable)
iterable = izip(imap(key, iterable), iterable)
if cmp is not None:
iterable = list(iterable)
iterable.sort(cmp)
else:
iterable = isorted(iterable)
if key is not None:
iterable = [v for (k,v) in iterable]
if type(iterable) is not list:
iterable = list(iterable)
if reverse:
iterable.reverse()
return iterable
try:
reversed
except NameError:
def reversed(iterable):
lst = list(iterable)
pop = lst.pop
while lst:
yield pop()
#
# itertools functions from 2.4
#
try:
tee
except NameError:
def tee(iterable, n=2):
def gen(next, data={}, cnt=[0]):
for i in count():
if i == cnt[0]:
item = data[i] = next()
cnt[0] += 1
else:
item = data.pop(i)
yield item
return tuple(imap(gen, repeat(iter(iterable), n)))
try:
groupby
except NameError:
class groupby(object):
def __init__(self, iterable, key=None):
if key is None:
key = lambda x: x
self.keyfunc = key
self.it = iter(iterable)
self.tgtkey = self.currkey = self.currvalue = xrange(0)
def __iter__(self):
return self
def next(self):
while self.currkey == self.tgtkey:
self.currvalue = self.it.next() # Exit on StopIteration
self.currkey = self.keyfunc(self.currvalue)
self.tgtkey = self.currkey
return (self.currkey, self._grouper(self.tgtkey))
def _grouper(self, tgtkey):
while self.currkey == tgtkey:
yield self.currvalue
self.currvalue = self.it.next() # Exit on StopIteration
self.currkey = self.keyfunc(self.currvalue)
#
# operators from 2.4
#
try:
from operator import attrgetter, itemgetter
except ImportError:
def attrgetter(attr):
def attrgetter(obj):
return getattr(obj, attr)
return attrgetter
def itemgetter(item):
def itemgetter(obj):
return obj[item]
return itemgetter
#
# deque from 2.4's collections
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259179/
#
try:
from collections import deque
except ImportError:
class deque(object):
def __init__(self, iterable=()):
self.data = dict(enumerate(iterable))
self.left = 0
self.right = len(self.data)
def append(self, x):
self.data[self.right] = x
self.right += 1
def appendleft(self, x):
self.left -= 1
self.data[self.left] = x
def pop(self):
if self.left == self.right:
raise IndexError('cannot pop from empty deque')
self.right -= 1
return self.data[self.right]
def popleft(self):
if self.left == self.right:
raise IndexError('cannot pop from empty deque')
x = self.data[self.left]
self.left += 1
return x
def __len__(self):
return self.right - self.left
def __iter__(self):
return imap(self.data.__getitem__, xrange(self.left, self.right))
def __repr__(self):
return 'deque(%r)' % (list(self),)
def __getstate__(self):
return (tuple(self),)
def __setstate__(self, s):
self.__init__(s[0])
def __hash__(self):
raise TypeError
def __copy__(self):
return self.__class__(self)
def __deepcopy__(self, memo={}):
from copy import deepcopy
result = self.__class__()
memo[id(self)] = result
result.__init__(deepcopy(tuple(self), memo))
return result
#
# new functions
#
import heapq as _heapq
def isorted(iterable):
lst = list(iterable)
_heapq.heapify(lst)
pop = _heapq.heappop
while lst:
yield pop(lst)
def ireversed(iterable):
if isinstance(iterable, (list, tuple)):
for i in xrange(len(iterable)-1, -1, -1):
yield iterable[i]
else:
for obj in reversed(iterable):
yield obj
| Python |
"""
altgraph.Graph - Base Graph class
=================================
..
#--Version 2.1
#--Bob Ippolito October, 2004
#--Version 2.0
#--Istvan Albert June, 2004
#--Version 1.0
#--Nathan Denny, May 27, 1999
"""
from altgraph import GraphError
from collections import deque
class Graph(object):
"""
The Graph class represents a directed graph with *N* nodes and *E* edges.
Naming conventions:
- the prefixes such as *out*, *inc* and *all* will refer to methods
that operate on the outgoing, incoming or all edges of that node.
For example: :py:meth:`inc_degree` will refer to the degree of the node
computed over the incoming edges (the number of neighbours linking to
the node).
- the prefixes such as *forw* and *back* will refer to the
orientation of the edges used in the method with respect to the node.
For example: :py:meth:`forw_bfs` will start at the node then use the outgoing
edges to traverse the graph (goes forward).
"""
def __init__(self, edges=None):
"""
Initialization
"""
self.next_edge = 0
self.nodes, self.edges = {}, {}
self.hidden_edges, self.hidden_nodes = {}, {}
if edges is not None:
for item in edges:
if len(item) == 2:
head, tail = item
self.add_edge(head, tail)
elif len(item) == 3:
head, tail, data = item
self.add_edge(head, tail, data)
else:
raise GraphError("Cannot create edge from %s"%(item,))
def __repr__(self):
return '<Graph: %d nodes, %d edges>' % (
self.number_of_nodes(), self.number_of_edges())
def add_node(self, node, node_data=None):
"""
Adds a new node to the graph. Arbitrary data can be attached to the
node via the node_data parameter. Adding the same node twice will be
silently ignored.
The node must be a hashable value.
"""
#
# the nodes will contain tuples that will store incoming edges,
# outgoing edges and data
#
# index 0 -> incoming edges
# index 1 -> outgoing edges
if node in self.hidden_nodes:
# Node is present, but hidden
return
if node not in self.nodes:
self.nodes[node] = ([], [], node_data)
def add_edge(self, head_id, tail_id, edge_data=1, create_nodes=True):
"""
Adds a directed edge going from head_id to tail_id.
Arbitrary data can be attached to the edge via edge_data.
It may create the nodes if adding edges between nonexisting ones.
:param head_id: head node
:param tail_id: tail node
:param edge_data: (optional) data attached to the edge
:param create_nodes: (optional) creates the head_id or tail_id node in case they did not exist
"""
# shorcut
edge = self.next_edge
# add nodes if on automatic node creation
if create_nodes:
self.add_node(head_id)
self.add_node(tail_id)
# update the corresponding incoming and outgoing lists in the nodes
# index 0 -> incoming edges
# index 1 -> outgoing edges
try:
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
except KeyError:
raise GraphError('Invalid nodes %s -> %s' % (head_id, tail_id))
# store edge information
self.edges[edge] = (head_id, tail_id, edge_data)
self.next_edge += 1
def hide_edge(self, edge):
"""
Hides an edge from the graph. The edge may be unhidden at some later
time.
"""
try:
head_id, tail_id, edge_data = self.hidden_edges[edge] = self.edges[edge]
self.nodes[tail_id][0].remove(edge)
self.nodes[head_id][1].remove(edge)
del self.edges[edge]
except KeyError:
raise GraphError('Invalid edge %s' % edge)
def hide_node(self, node):
"""
Hides a node from the graph. The incoming and outgoing edges of the
node will also be hidden. The node may be unhidden at some later time.
"""
try:
all_edges = self.all_edges(node)
self.hidden_nodes[node] = (self.nodes[node], all_edges)
for edge in all_edges:
self.hide_edge(edge)
del self.nodes[node]
except KeyError:
raise GraphError('Invalid node %s' % node)
def restore_node(self, node):
"""
Restores a previously hidden node back into the graph and restores
all of its incoming and outgoing edges.
"""
try:
self.nodes[node], all_edges = self.hidden_nodes[node]
for edge in all_edges:
self.restore_edge(edge)
del self.hidden_nodes[node]
except KeyError:
raise GraphError('Invalid node %s' % node)
def restore_edge(self, edge):
"""
Restores a previously hidden edge back into the graph.
"""
try:
head_id, tail_id, data = self.hidden_edges[edge]
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
self.edges[edge] = head_id, tail_id, data
del self.hidden_edges[edge]
except KeyError:
raise GraphError('Invalid edge %s' % edge)
def restore_all_edges(self):
"""
Restores all hidden edges.
"""
for edge in self.hidden_edges.keys():
try:
self.restore_edge(edge)
except GraphError:
pass
def restore_all_nodes(self):
"""
Restores all hidden nodes.
"""
for node in self.hidden_nodes.keys():
self.restore_node(node)
def __contains__(self, node):
"""
Test whether a node is in the graph
"""
return node in self.nodes
def edge_by_id(self, edge):
"""
Returns the edge that connects the head_id and tail_id nodes
"""
try:
head, tail, data = self.edges[edge]
except KeyError:
head, tail = None, None
raise GraphError('Invalid edge %s' % edge)
return (head, tail)
def edge_by_node(self, head, tail):
"""
Returns the edge that connects the head_id and tail_id nodes
"""
for edge in self.out_edges(head):
if self.tail(edge) == tail:
return edge
return None
def number_of_nodes(self):
"""
Returns the number of nodes
"""
return len(self.nodes)
def number_of_edges(self):
"""
Returns the number of edges
"""
return len(self.edges)
def __iter__(self):
"""
Iterates over all nodes in the graph
"""
return iter(self.nodes)
def node_list(self):
"""
Return a list of the node ids for all visible nodes in the graph.
"""
return self.nodes.keys()
def edge_list(self):
"""
Returns an iterator for all visible nodes in the graph.
"""
return self.edges.keys()
def number_of_hidden_edges(self):
"""
Returns the number of hidden edges
"""
return len(self.hidden_edges)
def number_of_hidden_nodes(self):
"""
Returns the number of hidden nodes
"""
return len(self.hidden_nodes)
def hidden_node_list(self):
"""
Returns the list with the hidden nodes
"""
return self.hidden_nodes.keys()
def hidden_edge_list(self):
"""
Returns a list with the hidden edges
"""
return self.hidden_edges.keys()
def describe_node(self, node):
"""
return node, node data, outgoing edges, incoming edges for node
"""
incoming, outgoing, data = self.nodes[node]
return node, data, outgoing, incoming
def describe_edge(self, edge):
"""
return edge, edge data, head, tail for edge
"""
head, tail, data = self.edges[edge]
return edge, data, head, tail
def node_data(self, node):
"""
Returns the data associated with a node
"""
return self.nodes[node][2]
def edge_data(self, edge):
"""
Returns the data associated with an edge
"""
return self.edges[edge][2]
def head(self, edge):
"""
Returns the node of the head of the edge.
"""
return self.edges[edge][0]
def tail(self, edge):
"""
Returns node of the tail of the edge.
"""
return self.edges[edge][1]
def out_nbrs(self, node):
"""
List of nodes connected by outgoing edges
"""
l = map(self.tail, self.out_edges(node))
#l.sort()
return l
def inc_nbrs(self, node):
"""
List of nodes connected by incoming edges
"""
l = map(self.head, self.inc_edges(node))
#l.sort()
return l
def all_nbrs(self, node):
"""
List of nodes connected by incoming and outgoing edges
"""
l = dict.fromkeys( self.inc_nbrs(node) + self.out_nbrs(node) )
return list(l)
def out_edges(self, node):
"""
Returns a list of the outgoing edges
"""
try:
return list(self.nodes[node][1])
except KeyError:
raise GraphError('Invalid node %s' % node)
return None
def inc_edges(self, node):
"""
Returns a list of the incoming edges
"""
try:
return list(self.nodes[node][0])
except KeyError:
raise GraphError('Invalid node %s' % node)
return None
def all_edges(self, node):
"""
Returns a list of incoming and outging edges.
"""
return set(self.inc_edges(node) + self.out_edges(node))
def out_degree(self, node):
"""
Returns the number of outgoing edges
"""
return len(self.out_edges(node))
def inc_degree(self, node):
"""
Returns the number of incoming edges
"""
return len(self.inc_edges(node))
def all_degree(self, node):
"""
The total degree of a node
"""
return self.inc_degree(node) + self.out_degree(node)
def _topo_sort(self, forward=True):
"""
Topological sort.
Returns a list of nodes where the successors (based on outgoing and
incoming edges selected by the forward parameter) of any given node
appear in the sequence after that node.
"""
topo_list = []
queue = deque()
indeg = {}
# select the operation that will be performed
if forward:
get_edges = self.out_edges
get_degree = self.inc_degree
get_next = self.tail
else:
get_edges = self.inc_edges
get_degree = self.out_degree
get_next = self.head
for node in self.node_list():
degree = get_degree(node)
if degree:
indeg[node] = degree
else:
queue.append(node)
while queue:
curr_node = queue.popleft()
topo_list.append(curr_node)
for edge in get_edges(curr_node):
tail_id = get_next(edge)
if tail_id in indeg:
indeg[tail_id] -= 1
if indeg[tail_id] == 0:
queue.append(tail_id)
if len(topo_list) == len(self.node_list()):
valid = True
else:
# the graph has cycles, invalid topological sort
valid = False
return (valid, topo_list)
def forw_topo_sort(self):
"""
Topological sort.
Returns a list of nodes where the successors (based on outgoing edges)
of any given node appear in the sequence after that node.
"""
return self._topo_sort(forward=True)
def back_topo_sort(self):
"""
Reverse topological sort.
Returns a list of nodes where the successors (based on incoming edges)
of any given node appear in the sequence after that node.
"""
return self._topo_sort(forward=False)
def _bfs_subgraph(self, start_id, forward=True):
"""
Private method creates a subgraph in a bfs order.
The forward parameter specifies whether it is a forward or backward
traversal.
"""
if forward:
get_bfs = self.forw_bfs
get_nbrs = self.out_nbrs
else:
get_bfs = self.back_bfs
get_nbrs = self.inc_nbrs
g = Graph()
bfs_list = get_bfs(start_id)
for node in bfs_list:
g.add_node(node)
for node in bfs_list:
for nbr_id in get_nbrs(node):
g.add_edge(node, nbr_id)
return g
def forw_bfs_subgraph(self, start_id):
"""
Creates and returns a subgraph consisting of the breadth first
reachable nodes based on their outgoing edges.
"""
return self._bfs_subgraph(start_id, forward=True)
def back_bfs_subgraph(self, start_id):
"""
Creates and returns a subgraph consisting of the breadth first
reachable nodes based on the incoming edges.
"""
return self._bfs_subgraph(start_id, forward=False)
def iterdfs(self, start, end=None, forward=True):
"""
Collecting nodes in some depth first traversal.
The forward parameter specifies whether it is a forward or backward
traversal.
"""
visited, stack = set([start]), deque([start])
if forward:
get_edges = self.out_edges
get_next = self.tail
else:
get_edges = self.inc_edges
get_next = self.head
while stack:
curr_node = stack.pop()
yield curr_node
if curr_node == end:
break
for edge in sorted(get_edges(curr_node)):
tail = get_next(edge)
if tail not in visited:
visited.add(tail)
stack.append(tail)
def iterdata(self, start, end=None, forward=True, condition=None):
"""
Perform a depth-first walk of the graph (as ``iterdfs``)
and yield the item data of every node where condition matches. The
condition callback is only called when node_data is not None.
"""
visited, stack = set([start]), deque([start])
if forward:
get_edges = self.out_edges
get_next = self.tail
else:
get_edges = self.inc_edges
get_next = self.head
get_data = self.node_data
while stack:
curr_node = stack.pop()
curr_data = get_data(curr_node)
if curr_data is not None:
if condition is not None and not condition(curr_data):
continue
yield curr_data
if curr_node == end:
break
for edge in get_edges(curr_node):
tail = get_next(edge)
if tail not in visited:
visited.add(tail)
stack.append(tail)
def _iterbfs(self, start, end=None, forward=True):
"""
The forward parameter specifies whether it is a forward or backward
traversal. Returns a list of tuples where the first value is the hop
value the second value is the node id.
"""
queue, visited = deque([(start, 0)]), set([start])
# the direction of the bfs depends on the edges that are sampled
if forward:
get_edges = self.out_edges
get_next = self.tail
else:
get_edges = self.inc_edges
get_next = self.head
while queue:
curr_node, curr_step = queue.popleft()
yield (curr_node, curr_step)
if curr_node == end:
break
for edge in get_edges(curr_node):
tail = get_next(edge)
if tail not in visited:
visited.add(tail)
queue.append((tail, curr_step + 1))
def forw_bfs(self, start, end=None):
"""
Returns a list of nodes in some forward BFS order.
Starting from the start node the breadth first search proceeds along
outgoing edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=True)]
def back_bfs(self, start, end=None):
"""
Returns a list of nodes in some backward BFS order.
Starting from the start node the breadth first search proceeds along
incoming edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=False)]
def forw_dfs(self, start, end=None):
"""
Returns a list of nodes in some forward DFS order.
Starting with the start node the depth first search proceeds along
outgoing edges.
"""
return list(self.iterdfs(start, end, forward=True))
def back_dfs(self, start, end=None):
"""
Returns a list of nodes in some backward DFS order.
Starting from the start node the depth first search proceeds along
incoming edges.
"""
return list(self.iterdfs(start, end, forward=False))
def connected(self):
"""
Returns :py:data:`True` if the graph's every node can be reached from every
other node.
"""
node_list = self.node_list()
for node in node_list:
bfs_list = self.forw_bfs(node)
if len(bfs_list) != len(node_list):
return False
return True
def clust_coef(self, node):
"""
Computes and returns the local clustering coefficient of node. The
local cluster coefficient is proportion of the actual number of edges between
neighbours of node and the maximum number of edges between those neighbours.
See <http://en.wikipedia.org/wiki/Clustering_coefficient#Local_clustering_coefficient>
for a formal definition.
"""
num = 0
nbr_set = set(self.out_nbrs(node))
if node in nbr_set:
nbr_set.remove(node) # loop defense
for nbr in nbr_set:
sec_set = set(self.out_nbrs(nbr))
if nbr in sec_set:
sec_set.remove(nbr) # loop defense
num += len(nbr_set & sec_set)
nbr_num = len(nbr_set)
if nbr_num:
clust_coef = float(num) / (nbr_num * (nbr_num - 1))
else:
clust_coef = 0.0
return clust_coef
def get_hops(self, start, end=None, forward=True):
"""
Computes the hop distance to all nodes centered around a specified node.
First order neighbours are at hop 1, their neigbours are at hop 2 etc.
Uses :py:meth:`forw_bfs` or :py:meth:`back_bfs` depending on the value of the forward
parameter. If the distance between all neighbouring nodes is 1 the hop
number corresponds to the shortest distance between the nodes.
:param start: the starting node
:param end: ending node (optional). When not specified will search the whole graph.
:param forward: directionality parameter (optional). If C{True} (default) it uses L{forw_bfs} otherwise L{back_bfs}.
:return: returns a list of tuples where each tuple contains the node and the hop.
Typical usage::
>>> print graph.get_hops(1, 8)
>>> [(1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (7, 4), (8, 5)]
# node 1 is at 0 hops
# node 2 is at 1 hop
# ...
# node 8 is at 5 hops
"""
if forward:
return list(self._iterbfs(start=start, end=end, forward=True))
else:
return list(self._iterbfs(start=start, end=end, forward=False))
| Python |
'''
altgraph.GraphAlgo - Graph algorithms
=====================================
'''
from altgraph import GraphError
def dijkstra(graph, start, end=None):
"""
Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the start node to all nodes nearer than or equal to the end node.
Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.
This code does not verify this property for all edges (only the edges examined until the end
vertex is reached), but will correctly compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.
*Adapted to altgraph by Istvan Albert, Pennsylvania State University - June, 9 2004*
"""
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = _priorityDictionary() # estimated distances of non-final vertices
Q[start] = 0
for v in Q:
D[v] = Q[v]
if v == end: break
for w in graph.out_nbrs(v):
edge_id = graph.edge_by_node(v,w)
vwLength = D[v] + graph.edge_data(edge_id)
if w in D:
if vwLength < D[w]:
raise GraphError("Dijkstra: found better path to already-final vertex")
elif w not in Q or vwLength < Q[w]:
Q[w] = vwLength
P[w] = v
return (D,P)
def shortest_path(graph, start, end):
"""
Find a single shortest path from the given start node to the given end node.
The input has the same conventions as dijkstra(). The output is a list of the nodes
in order along the shortest path.
**Note that the distances must be stored in the edge data as numeric data**
"""
D,P = dijkstra(graph, start, end)
Path = []
while 1:
Path.append(end)
if end == start: break
end = P[end]
Path.reverse()
return Path
#
# Utility classes and functions
#
class _priorityDictionary(dict):
'''
Priority dictionary using binary heaps (internal use only)
David Eppstein, UC Irvine, 8 Mar 2002
Implements a data structure that acts almost like a dictionary, with two modifications:
1. D.smallest() returns the value x minimizing D[x]. For this to work correctly,
all values D[x] stored in the dictionary must be comparable.
2. iterating "for x in D" finds and removes the items from D in sorted order.
Each item is not removed until the next item is requested, so D[x] will still
return a useful value until the next iteration of the for-loop.
Each operation takes logarithmic amortized time.
'''
def __init__(self):
'''
Initialize priorityDictionary by creating binary heap of pairs (value,key).
Note that changing or removing a dict entry will not remove the old pair from the heap
until it is found by smallest() or until the heap is rebuilt.
'''
self.__heap = []
dict.__init__(self)
def smallest(self):
'''
Find smallest item after removing deleted items from front of heap.
'''
if len(self) == 0:
raise IndexError, "smallest of empty priorityDictionary"
heap = self.__heap
while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]:
lastItem = heap.pop()
insertionPoint = 0
while 1:
smallChild = 2*insertionPoint+1
if smallChild+1 < len(heap) and heap[smallChild] > heap[smallChild+1] :
smallChild += 1
if smallChild >= len(heap) or lastItem <= heap[smallChild]:
heap[insertionPoint] = lastItem
break
heap[insertionPoint] = heap[smallChild]
insertionPoint = smallChild
return heap[0][1]
def __iter__(self):
'''
Create destructive sorted iterator of priorityDictionary.
'''
def iterfn():
while len(self) > 0:
x = self.smallest()
yield x
del self[x]
return iterfn()
def __setitem__(self,key,val):
'''
Change value stored in dictionary and add corresponding pair to heap.
Rebuilds the heap if the number of deleted items gets large, to avoid memory leakage.
'''
dict.__setitem__(self,key,val)
heap = self.__heap
if len(heap) > 2 * len(self):
self.__heap = [(v,k) for k,v in self.iteritems()]
self.__heap.sort() # builtin sort probably faster than O(n)-time heapify
else:
newPair = (val,key)
insertionPoint = len(heap)
heap.append(None)
while insertionPoint > 0 and newPair < heap[(insertionPoint-1)//2]:
heap[insertionPoint] = heap[(insertionPoint-1)//2]
insertionPoint = (insertionPoint-1)//2
heap[insertionPoint] = newPair
def setdefault(self,key,val):
'''
Reimplement setdefault to pass through our customized __setitem__.
'''
if key not in self:
self[key] = val
return self[key]
| Python |
'''
altgraph.Dot - Interface to the dot language
============================================
The :py:mod:`~altgraph.Dot` module provides a simple interface to the
file format used in the `graphviz <http://www.research.att.com/sw/tools/graphviz/>`_
program. The module is intended to offload the most tedious part of the process
(the **dot** file generation) while transparently exposing most of its features.
To display the graphs or to generate image files the `graphviz <http://www.research.att.com/sw/tools/graphviz/>`_
package needs to be installed on the system, moreover the :command:`dot` and :command:`dotty` programs must
be accesible in the program path so that they can be ran from processes spawned
within the module.
Example usage
-------------
Here is a typical usage::
from altgraph import Graph, Dot
# create a graph
edges = [ (1,2), (1,3), (3,4), (3,5), (4,5), (5,4) ]
graph = Graph.Graph(edges)
# create a dot representation of the graph
dot = Dot.Dot(graph)
# display the graph
dot.display()
# save the dot representation into the mydot.dot file
dot.save_dot(file_name='mydot.dot')
# save dot file as gif image into the graph.gif file
dot.save_img(file_name='graph', file_type='gif')
Directed graph and non-directed graph
-------------------------------------
Dot class can use for both directed graph and non-directed graph
by passing ``graphtype`` parameter.
Example::
# create directed graph(default)
dot = Dot.Dot(graph, graphtype="digraph")
# create non-directed graph
dot = Dot.Dot(graph, graphtype="graph")
Customizing the output
----------------------
The graph drawing process may be customized by passing
valid :command:`dot` parameters for the nodes and edges. For a list of all
parameters see the `graphviz <http://www.research.att.com/sw/tools/graphviz/>`_
documentation.
Example::
# customizing the way the overall graph is drawn
dot.style(size='10,10', rankdir='RL', page='5, 5' , ranksep=0.75)
# customizing node drawing
dot.node_style(1, label='BASE_NODE',shape='box', color='blue' )
dot.node_style(2, style='filled', fillcolor='red')
# customizing edge drawing
dot.edge_style(1, 2, style='dotted')
dot.edge_style(3, 5, arrowhead='dot', label='binds', labelangle='90')
dot.edge_style(4, 5, arrowsize=2, style='bold')
.. note::
dotty (invoked via :py:func:`~altgraph.Dot.display`) may not be able to
display all graphics styles. To verify the output save it to an image file
and look at it that way.
Valid attributes
----------------
- dot styles, passed via the :py:meth:`Dot.style` method::
rankdir = 'LR' (draws the graph horizontally, left to right)
ranksep = number (rank separation in inches)
- node attributes, passed via the :py:meth:`Dot.node_style` method::
style = 'filled' | 'invisible' | 'diagonals' | 'rounded'
shape = 'box' | 'ellipse' | 'circle' | 'point' | 'triangle'
- edge attributes, passed via the :py:meth:`Dot.edge_style` method::
style = 'dashed' | 'dotted' | 'solid' | 'invis' | 'bold'
arrowhead = 'box' | 'crow' | 'diamond' | 'dot' | 'inv' | 'none' | 'tee' | 'vee'
weight = number (the larger the number the closer the nodes will be)
- valid `graphviz colors <http://www.research.att.com/~erg/graphviz/info/colors.html>`_
- for more details on how to control the graph drawing process see the
`graphviz reference <http://www.research.att.com/sw/tools/graphviz/refs.html>`_.
'''
import os
from itertools import imap, ifilter
import warnings
from altgraph import GraphError
class Dot(object):
'''
A class providing a **graphviz** (dot language) representation
allowing a fine grained control over how the graph is being
displayed.
If the :command:`dot` and :command:`dotty` programs are not in the current system path
their location needs to be specified in the contructor.
'''
def __init__(self, graph=None, nodes=None, edgefn=None, nodevisitor=None, edgevisitor=None, name="G", dot='dot', dotty='dotty', neato='neato', graphtype="digraph"):
'''
Initialization.
'''
self.name, self.attr = name, {}
assert graphtype in ['graph', 'digraph']
self.type = graphtype
self.temp_dot = "tmp_dot.dot"
self.temp_neo = "tmp_neo.dot"
self.dot, self.dotty, self.neato = dot, dotty, neato
# self.nodes: node styles
# self.edges: edge styles
self.nodes, self.edges = {}, {}
if graph is not None and nodes is None:
nodes = graph
if graph is not None and edgefn is None:
def edgefn(node, graph=graph):
return graph.out_nbrs(node)
if nodes is None:
nodes = ()
seen = set()
for node in nodes:
if nodevisitor is None:
style = {}
else:
style = nodevisitor(node)
if style is not None:
self.nodes[node] = {}
self.node_style(node, **style)
seen.add(node)
if edgefn is not None:
for head in seen:
for tail in ifilter(seen.__contains__, edgefn(head)):
if edgevisitor is None:
edgestyle = {}
else:
edgestyle = edgevisitor(head, tail)
if edgestyle is not None:
if head not in self.edges:
self.edges[head] = {}
self.edges[head][tail] = {}
self.edge_style(head, tail, **edgestyle)
def style(self, **attr):
'''
Changes the overall style
'''
self.attr = attr
def display(self, mode='dot'):
'''
Displays the current graph via dotty
'''
if mode == 'neato':
self.save_dot(self.temp_neo)
neato_cmd = "%s -o %s %s" % (self.neato, self.temp_dot, self.temp_neo)
os.system(neato_cmd)
else:
self.save_dot(self.temp_dot)
plot_cmd = "%s %s" % (self.dotty, self.temp_dot)
os.system(plot_cmd)
def node_style(self, node, **kwargs):
'''
Modifies a node style to the dot representation.
'''
if node not in self.edges:
self.edges[node] = {}
self.nodes[node] = kwargs
def all_node_style(self, **kwargs):
'''
Modifies all node styles
'''
for node in self.nodes:
self.node_style(node, **kwargs)
def edge_style(self, head, tail, **kwargs):
'''
Modifies an edge style to the dot representation.
'''
if tail not in self.nodes:
raise GraphError("invalid node %s" % (tail,))
try:
if tail not in self.edges[head]:
self.edges[head][tail]= {}
self.edges[head][tail] = kwargs
except KeyError:
raise GraphError("invalid edge %s -> %s " % (head, tail) )
def iterdot(self):
# write graph title
if self.type == 'digraph':
yield 'digraph %s {\n' % (self.name,)
elif self.type == 'graph':
yield 'graph %s {\n' % (self.name,)
else:
raise GraphError("unsupported graphtype %s" % (self.type,))
# write overall graph attributes
for attr_name, attr_value in self.attr.iteritems():
yield '%s="%s";' % (attr_name, attr_value)
yield '\n'
# some reusable patterns
cpatt = '%s="%s",' # to separate attributes
epatt = '];\n' # to end attributes
# write node attributes
for node_name, node_attr in self.nodes.iteritems():
yield '\t"%s" [' % (node_name,)
for attr_name, attr_value in node_attr.iteritems():
yield cpatt % (attr_name, attr_value)
yield epatt
# write edge attributes
for head in self.edges:
for tail in self.edges[head]:
if self.type == 'digraph':
yield '\t"%s" -> "%s" [' % (head, tail)
else:
yield '\t"%s" -- "%s" [' % (head, tail)
for attr_name, attr_value in self.edges[head][tail].iteritems():
yield cpatt % (attr_name, attr_value)
yield epatt
# finish file
yield '}\n'
def __iter__(self):
return self.iterdot()
def save_dot(self, file_name=None):
'''
Saves the current graph representation into a file
'''
if not file_name:
warnings.warn(DeprecationWarning, "always pass a file_name")
file_name = self.temp_dot
fp = open(file_name, "w")
try:
for chunk in self.iterdot():
fp.write(chunk)
finally:
fp.close()
def save_img(self, file_name=None, file_type="gif", mode='dot'):
'''
Saves the dot file as an image file
'''
if not file_name:
warnings.warn(DeprecationWarning, "always pass a file_name")
file_name = "out"
if mode == 'neato':
self.save_dot(self.temp_neo)
neato_cmd = "%s -o %s %s" % (self.neato, self.temp_dot, self.temp_neo)
os.system(neato_cmd)
plot_cmd = self.dot
else:
self.save_dot(self.temp_dot)
plot_cmd = self.dot
file_name = "%s.%s" % (file_name, file_type)
create_cmd = "%s -T%s %s -o %s" % (plot_cmd, file_type, self.temp_dot, file_name)
os.system(create_cmd)
| Python |
"""
altgraph.ObjectGraph - Graph of objects with an identifier
==========================================================
A graph of objects that have a "graphident" attribute.
graphident is the key for the object in the graph
"""
from itertools import imap
from altgraph import GraphError
from altgraph.Graph import Graph
from altgraph.GraphUtil import filter_stack
class ObjectGraph(object):
"""
A graph of objects that have a "graphident" attribute.
graphident is the key for the object in the graph
"""
def __init__(self, graph=None, debug=0):
if graph is None:
graph = Graph()
self.graphident = self
self.graph = graph
self.debug = debug
self.indent = 0
graph.add_node(self, None)
def __repr__(self):
return '<%s>' % (type(self).__name__,)
def flatten(self, condition=None, start=None):
"""
Iterate over the subgraph that is entirely reachable by condition
starting from the given start node or the ObjectGraph root
"""
if start is None:
start = self
start = self.getRawIdent(start)
return self.graph.iterdata(start=start, condition=condition)
def nodes(self):
for ident in self.graph:
node = self.graph.node_data(ident)
if node is not None:
yield self.graph.node_data(ident)
def get_edges(self, node):
start = self.getRawIdent(node)
_, _, outraw, incraw = self.graph.describe_node(start)
def iter_edges(lst, n):
seen = set()
for tpl in imap(self.graph.describe_edge, lst):
ident = tpl[n]
if ident not in seen:
yield self.findNode(ident)
seen.add(ident)
return iter_edges(outraw, 3), iter_edges(incraw, 2)
def filterStack(self, filters):
"""
Filter the ObjectGraph in-place by removing all edges to nodes that
do not match every filter in the given filter list
Returns a tuple containing the number of: (nodes_visited, nodes_removed, nodes_orphaned)
"""
visited, removes, orphans = filter_stack(self.graph, self, filters)
for last_good, tail in orphans:
self.graph.add_edge(last_good, tail, edge_data='orphan')
for node in removes:
self.graph.hide_node(node)
return len(visited)-1, len(removes), len(orphans)
def removeNode(self, node):
"""
Remove the given node from the graph if it exists
"""
ident = self.getIdent(node)
if ident is not None:
self.graph.hide_node(ident)
def removeReference(self, fromnode, tonode):
"""
Remove all edges from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident = self.getIdent(fromnode)
toident = self.getIdent(tonode)
if fromident is not None and toident is not None:
while True:
edge = self.graph.edge_by_node(fromident, toident)
if edge is None:
break
self.graph.hide_edge(edge)
def getIdent(self, node):
"""
Get the graph identifier for a node
"""
ident = self.getRawIdent(node)
if ident is not None:
return ident
node = self.findNode(node)
if node is None:
return None
return node.graphident
def getRawIdent(self, node):
"""
Get the identifier for a node object
"""
if node is self:
return node
ident = getattr(node, 'graphident', None)
return ident
def __contains__(self, node):
return self.findNode(node) is not None
def findNode(self, node):
"""
Find the node on the graph
"""
ident = self.getRawIdent(node)
if ident is None:
ident = node
try:
return self.graph.node_data(ident)
except KeyError:
return None
def addNode(self, node):
"""
Add a node to the graph referenced by the root
"""
self.msg(4, "addNode", node)
try:
self.graph.restore_node(node.graphident)
except GraphError:
self.graph.add_node(node.graphident, node)
def createReference(self, fromnode, tonode, edge_data=None):
"""
Create a reference from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident, toident = self.getIdent(fromnode), self.getIdent(tonode)
if fromident is None or toident is None:
return
self.msg(4, "createReference", fromnode, tonode, edge_data)
self.graph.add_edge(fromident, toident, edge_data=edge_data)
def createNode(self, cls, name, *args, **kw):
"""
Add a node of type cls to the graph if it does not already exist
by the given name
"""
m = self.findNode(name)
if m is None:
m = cls(name, *args, **kw)
self.addNode(m)
return m
def msg(self, level, s, *args):
"""
Print a debug message with the given level
"""
if s and level <= self.debug:
print "%s%s %s" % (" " * self.indent, s, ' '.join(map(repr, args)))
def msgin(self, level, s, *args):
"""
Print a debug message and indent
"""
if level <= self.debug:
self.msg(level, s, *args)
self.indent = self.indent + 1
def msgout(self, level, s, *args):
"""
Dedent and print a debug message
"""
if level <= self.debug:
self.indent = self.indent - 1
self.msg(level, s, *args)
| Python |
'''
altgraph - a python graph library
=================================
altgraph is a fork of `graphlib <http://pygraphlib.sourceforge.net>`_ tailored
to use newer Python 2.3+ features, including additional support used by the
py2app suite (modulegraph and macholib, specifically).
altgraph is a python based graph (network) representation and manipulation package.
It has started out as an extension to the `graph_lib module <http://www.ece.arizona.edu/~denny/python_nest/graph_lib_1.0.1.html>`_
written by Nathan Denny it has been significantly optimized and expanded.
The :class:`altgraph.Graph.Graph` class is loosely modeled after the `LEDA <http://www.algorithmic-solutions.com/enleda.htm>`_
(Library of Efficient Datatypes) representation. The library
includes methods for constructing graphs, BFS and DFS traversals,
topological sort, finding connected components, shortest paths as well as a number
graph statistics functions. The library can also visualize graphs
via `graphviz <http://www.research.att.com/sw/tools/graphviz/>`_.
The package contains the following modules:
- the :py:mod:`altgraph.Graph` module contains the :class:`~altgraph.Graph.Graph` class that stores the graph data
- the :py:mod:`altgraph.GraphAlgo` module implements graph algorithms operating on graphs (:py:class:`~altgraph.Graph.Graph`} instances)
- the :py:mod:`altgraph.GraphStat` module contains functions for computing statistical measures on graphs
- the :py:mod:`altgraph.GraphUtil` module contains functions for generating, reading and saving graphs
- the :py:mod:`altgraph.Dot` module contains functions for displaying graphs via `graphviz <http://www.research.att.com/sw/tools/graphviz/>`_
- the :py:mod:`altgraph.ObjectGraph` module implements a graph of objects with a unique identifier
Installation
------------
Download and unpack the archive then type::
python setup.py install
This will install the library in the default location. For instructions on
how to customize the install procedure read the output of::
python setup.py --help install
To verify that the code works run the test suite::
python setup.py test
Example usage
-------------
Lets assume that we want to analyze the graph below (links to the full picture) GRAPH_IMG.
Our script then might look the following way::
from altgraph import Graph, GraphAlgo, Dot
# these are the edges
edges = [ (1,2), (2,4), (1,3), (2,4), (3,4), (4,5), (6,5),
(6,14), (14,15), (6, 15), (5,7), (7, 8), (7,13), (12,8),
(8,13), (11,12), (11,9), (13,11), (9,13), (13,10) ]
# creates the graph
graph = Graph.Graph()
for head, tail in edges:
graph.add_edge(head, tail)
# do a forward bfs from 1 at most to 20
print graph.forw_bfs(1)
This will print the nodes in some breadth first order::
[1, 2, 3, 4, 5, 7, 8, 13, 11, 10, 12, 9]
If we wanted to get the hop-distance from node 1 to node 8
we coud write::
print graph.get_hops(1, 8)
This will print the following::
[(1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (7, 4), (8, 5)]
Node 1 is at 0 hops since it is the starting node, nodes 2,3 are 1 hop away ...
node 8 is 5 hops away. To find the shortest distance between two nodes you
can use::
print GraphAlgo.shortest_path(graph, 1, 12)
It will print the nodes on one (if there are more) the shortest paths::
[1, 2, 4, 5, 7, 13, 11, 12]
To display the graph we can use the GraphViz backend::
dot = Dot.Dot(graph)
# display the graph on the monitor
dot.display()
# save it in an image file
dot.save_img(file_name='graph', file_type='gif')
..
@author: U{Istvan Albert<http://www.personal.psu.edu/staff/i/u/iua1/>}
@license: MIT License
Copyright (c) 2004 Istvan Albert unless otherwise noted.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@requires: Python 2.3 or higher
@newfield contributor: Contributors:
@contributor: U{Reka Albert <http://www.phys.psu.edu/~ralbert/>}
'''
__version__ = '0.7.0'
class GraphError(ValueError):
pass
| Python |
'''
altgraph.GraphUtil - Utility classes and functions
==================================================
'''
import random
from collections import deque
from altgraph import Graph
from altgraph import GraphError
def generate_random_graph(node_num, edge_num, self_loops=False, multi_edges=False):
'''
Generates and returns a :py:class:`~altgraph.Graph.Graph` instance with *node_num* nodes
randomly connected by *edge_num* edges.
'''
g = Graph.Graph()
if not multi_edges:
if self_loops:
max_edges = node_num * node_num
else:
max_edges = node_num * (node_num-1)
if edge_num > max_edges:
raise GraphError("inconsistent arguments to 'generate_random_graph'")
nodes = range(node_num)
for node in nodes:
g.add_node(node)
while 1:
head = random.choice(nodes)
tail = random.choice(nodes)
# loop defense
if head == tail and not self_loops:
continue
# multiple edge defense
if g.edge_by_node(head,tail) is not None and not multi_edges:
continue
# add the edge
g.add_edge(head, tail)
if g.number_of_edges() >= edge_num:
break
return g
def generate_scale_free_graph(steps, growth_num, self_loops=False, multi_edges=False):
'''
Generates and returns a :py:class:`~altgraph.Graph.Graph` instance that will have *steps* \* *growth_num* nodes
and a scale free (powerlaw) connectivity. Starting with a fully connected graph with *growth_num* nodes
at every step *growth_num* nodes are added to the graph and are connected to existing nodes with
a probability proportional to the degree of these existing nodes.
'''
# FIXME: The code doesn't seem to do what the documentation claims.
graph = Graph.Graph()
# initialize the graph
store = []
for i in range(growth_num):
#store += [ i ] * (growth_num - 1)
for j in range(i + 1, growth_num):
store.append(i)
store.append(j)
graph.add_edge(i,j)
# generate
for node in range(growth_num, steps * growth_num):
graph.add_node(node)
while ( graph.out_degree(node) < growth_num ):
nbr = random.choice(store)
# loop defense
if node == nbr and not self_loops:
continue
# multi edge defense
if graph.edge_by_node(node, nbr) and not multi_edges:
continue
graph.add_edge(node, nbr)
for nbr in graph.out_nbrs(node):
store.append(node)
store.append(nbr)
return graph
def filter_stack(graph, head, filters):
"""
Perform a walk in a depth-first order starting
at *head*.
Returns (visited, removes, orphans).
* visited: the set of visited nodes
* removes: the list of nodes where the node
data does not all *filters*
* orphans: tuples of (last_good, node),
where node is not in removes, is directly
reachable from a node in *removes* and
*last_good* is the closest upstream node that is not
in *removes*.
"""
visited, removes, orphans = set([head]), set(), set()
stack = deque([(head, head)])
get_data = graph.node_data
get_edges = graph.out_edges
get_tail = graph.tail
while stack:
last_good, node = stack.pop()
data = get_data(node)
if data is not None:
for filtfunc in filters:
if not filtfunc(data):
removes.add(node)
break
else:
last_good = node
for edge in get_edges(node):
tail = get_tail(edge)
if last_good is not node:
orphans.add((last_good, tail))
if tail not in visited:
visited.add(tail)
stack.append((last_good, tail))
orphans = [(last_good, tail) for (last_good, tail) in orphans if tail not in removes]
#orphans.sort()
return visited, removes, orphans
| Python |
'''
altgraph.GraphStat - Functions providing various graph statistics
=================================================================
'''
import sys
def degree_dist(graph, limits=(0,0), bin_num=10, mode='out'):
'''
Computes the degree distribution for a graph.
Returns a list of tuples where the first element of the tuple is the center of the bin
representing a range of degrees and the second element of the tuple are the number of nodes
with the degree falling in the range.
Example::
....
'''
deg = []
if mode == 'inc':
get_deg = graph.inc_degree
else:
get_deg = graph.out_degree
for node in graph:
deg.append( get_deg(node) )
if not deg:
return []
results = _binning(values=deg, limits=limits, bin_num=bin_num)
return results
def _binning(values, limits=(0,0), bin_num=10):
'''
Bins data that falls between certain limits, if the limits are (0, 0) the
minimum and maximum values are used.
Returns a list of tuples where the first element of the tuple is the center of the bin
and the second element of the tuple are the counts.
'''
if limits == (0, 0):
eps = 1.0/sys.maxint
min_val, max_val = min(values) - eps, max(values) + eps
else:
min_val, max_val = limits
# get bin size
bin_size = (max_val - min_val)/float(bin_num)
bins = [0] * (bin_num)
# will ignore these outliers for now
out_points = 0
for value in values:
try:
if (value - min_val) < 0:
out_points += 1
else:
index = int((value - min_val)/float(bin_size))
bins[index] += 1
except IndexError:
out_points += 1
# make it ready for an x,y plot
result = []
center = (bin_size/2) + min_val
for i, y in enumerate(bins):
x = center + bin_size * i
result.append( (x,y) )
return result
| Python |
####
#### This is a plain checkout from
#### http://hg.python.org/cpython/raw-file/v2.6.5/Lib/subprocess.py
#### with a single change at the place marked
#### "change this to use pywin32 instead of the _subprocess driver"
#### So for Windows, pywin32 is used.
####
#### When up/downgrading this module, please keep this header updated.
####
# subprocess - Subprocesses with accessible I/O streams
#
# For more information about this module, see PEP 324.
#
# This module should remain compatible with Python 2.2, see PEP 291.
#
# Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
#
# Licensed to PSF under a Contributor Agreement.
# See http://www.python.org/2.4/license for licensing details.
r"""subprocess - Subprocesses with accessible I/O streams
This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes. This module
intends to replace several other, older modules and functions, like:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
Information about how the subprocess module can be used to replace these
modules and functions can be found below.
Using the subprocess module
===========================
This module defines one class called Popen:
class Popen(args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
Arguments are:
args should be a string, or a sequence of program arguments. The
program to execute is normally the first item in the args sequence or
string, but can be explicitly set by using the executable argument.
On UNIX, with shell=False (default): In this case, the Popen class
uses os.execvp() to execute the child program. args should normally
be a sequence. A string will be treated as a sequence with the string
as the only item (the program to execute).
On UNIX, with shell=True: If args is a string, it specifies the
command string to execute through the shell. If args is a sequence,
the first item specifies the command string, and any additional items
will be treated as additional shell arguments.
On Windows: the Popen class uses CreateProcess() to execute the child
program, which operates on strings. If args is a sequence, it will be
converted to a string using the list2cmdline method. Please note that
not all MS Windows applications interpret the command line the same
way: The list2cmdline is designed for applications using the same
rules as the MS C runtime.
bufsize, if given, has the same meaning as the corresponding argument
to the built-in open() function: 0 means unbuffered, 1 means line
buffered, any other positive value means use a buffer of
(approximately) that size. A negative bufsize means to use the system
default, which usually means fully buffered. The default value for
bufsize is 0 (unbuffered).
stdin, stdout and stderr specify the executed programs' standard
input, standard output and standard error file handles, respectively.
Valid values are PIPE, an existing file descriptor (a positive
integer), an existing file object, and None. PIPE indicates that a
new pipe to the child should be created. With None, no redirection
will occur; the child's file handles will be inherited from the
parent. Additionally, stderr can be STDOUT, which indicates that the
stderr data from the applications should be captured into the same
file handle as for stdout.
If preexec_fn is set to a callable object, this object will be called
in the child process just before the child is executed.
If close_fds is true, all file descriptors except 0, 1 and 2 will be
closed before the child process is executed.
if shell is true, the specified command will be executed through the
shell.
If cwd is not None, the current directory will be changed to cwd
before the child is executed.
If env is not None, it defines the environment variables for the new
process.
If universal_newlines is true, the file objects stdout and stderr are
opened as a text files, but lines may be terminated by any of '\n',
the Unix end-of-line convention, '\r', the Macintosh convention or
'\r\n', the Windows convention. All of these external representations
are seen as '\n' by the Python program. Note: This feature is only
available if Python is built with universal newline support (the
default). Also, the newlines attribute of the file objects stdout,
stdin and stderr are not updated by the communicate() method.
The startupinfo and creationflags, if given, will be passed to the
underlying CreateProcess() function. They can specify things such as
appearance of the main window and priority for the new process.
(Windows only)
This module also defines two shortcut functions:
call(*popenargs, **kwargs):
Run command with arguments. Wait for command to complete, then
return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
check_call(*popenargs, **kwargs):
Run command with arguments. Wait for command to complete. If the
exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
check_call(["ls", "-l"])
Exceptions
----------
Exceptions raised in the child process, before the new program has
started to execute, will be re-raised in the parent. Additionally,
the exception object will have one extra attribute called
'child_traceback', which is a string containing traceback information
from the childs point of view.
The most common exception raised is OSError. This occurs, for
example, when trying to execute a non-existent file. Applications
should prepare for OSErrors.
A ValueError will be raised if Popen is called with invalid arguments.
check_call() will raise CalledProcessError, if the called process
returns a non-zero return code.
Security
--------
Unlike some other popen functions, this implementation will never call
/bin/sh implicitly. This means that all characters, including shell
metacharacters, can safely be passed to child processes.
Popen objects
=============
Instances of the Popen class have the following methods:
poll()
Check if child process has terminated. Returns returncode
attribute.
wait()
Wait for child process to terminate. Returns returncode attribute.
communicate(input=None)
Interact with process: Send data to stdin. Read data from stdout
and stderr, until end-of-file is reached. Wait for process to
terminate. The optional input argument should be a string to be
sent to the child process, or None, if no data should be sent to
the child.
communicate() returns a tuple (stdout, stderr).
Note: The data read is buffered in memory, so do not use this
method if the data size is large or unlimited.
The following attributes are also available:
stdin
If the stdin argument is PIPE, this attribute is a file object
that provides input to the child process. Otherwise, it is None.
stdout
If the stdout argument is PIPE, this attribute is a file object
that provides output from the child process. Otherwise, it is
None.
stderr
If the stderr argument is PIPE, this attribute is file object that
provides error output from the child process. Otherwise, it is
None.
pid
The process ID of the child process.
returncode
The child return code. A None value indicates that the process
hasn't terminated yet. A negative value -N indicates that the
child was terminated by signal N (UNIX only).
Replacing older functions with the subprocess module
====================================================
In this section, "a ==> b" means that b can be used as a replacement
for a.
Note: All functions in this section fail (more or less) silently if
the executed program cannot be found; this module raises an OSError
exception.
In the following examples, we assume that the subprocess module is
imported with "from subprocess import *".
Replacing /bin/sh shell backquote
---------------------------------
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
Replacing shell pipe line
-------------------------
output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
Replacing os.system()
---------------------
sts = os.system("mycmd" + " myarg")
==>
p = Popen("mycmd" + " myarg", shell=True)
pid, sts = os.waitpid(p.pid, 0)
Note:
* Calling the program through the shell is usually not required.
* It's easier to look at the returncode attribute than the
exitstatus.
A more real-world example would look like this:
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
Replacing os.spawn*
-------------------
P_NOWAIT example:
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
P_WAIT example:
retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])
Vector example:
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])
Environment example:
os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
Replacing os.popen*
-------------------
pipe = os.popen("cmd", mode='r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
pipe = os.popen("cmd", mode='w', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
(child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
child_stdout,
child_stderr) = os.popen3("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
child_stdout,
child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
the command to execute, in which case arguments will be passed
directly to the program without shell intervention. This usage can be
replaced as follows:
(child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
bufsize)
==>
p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
Return code handling translates as follows:
pipe = os.popen("cmd", 'w')
...
rc = pipe.close()
if rc != None and rc % 256:
print "There were some errors"
==>
process = Popen("cmd", 'w', shell=True, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
print "There were some errors"
Replacing popen2.*
------------------
(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen(["somestring"], shell=True, bufsize=bufsize
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
On Unix, popen2 also accepts a sequence as the command to execute, in
which case arguments will be passed directly to the program without
shell intervention. This usage can be replaced as follows:
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
except that:
* subprocess.Popen raises an exception if the execution fails
* the capturestderr argument is replaced with the stderr argument.
* stdin=PIPE and stdout=PIPE must be specified.
* popen2 closes all filedescriptors by default, but you have to specify
close_fds=True with subprocess.Popen.
"""
import sys
mswindows = (sys.platform == "win32")
import os
import types
import traceback
import gc
import signal
# Exception classes used by this module.
class CalledProcessError(Exception):
"""This exception is raised when a process run by check_call() returns
a non-zero exit status. The exit status will be stored in the
returncode attribute."""
def __init__(self, returncode, cmd):
self.returncode = returncode
self.cmd = cmd
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
if mswindows:
import threading
import msvcrt
if 1: # <-- change this to use pywin32 instead of the _subprocess driver
import pywintypes
from win32api import GetStdHandle, STD_INPUT_HANDLE, \
STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
from win32api import GetCurrentProcess, DuplicateHandle, \
GetModuleFileName, GetVersion
from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
from win32pipe import CreatePipe
from win32process import CreateProcess, STARTUPINFO, \
GetExitCodeProcess, STARTF_USESTDHANDLES, \
STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
from win32process import TerminateProcess
from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
else:
from _subprocess import *
class STARTUPINFO:
dwFlags = 0
hStdInput = None
hStdOutput = None
hStdError = None
wShowWindow = 0
class pywintypes:
error = IOError
else:
import select
import errno
import fcntl
import pickle
__all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
try:
MAXFD = os.sysconf("SC_OPEN_MAX")
except:
MAXFD = 256
# True/False does not exist on 2.2.0
#try:
# False
#except NameError:
# False = 0
# True = 1
_active = []
def _cleanup():
for inst in _active[:]:
if inst._internal_poll(_deadstate=sys.maxint) >= 0:
try:
_active.remove(inst)
except ValueError:
# This can happen if two threads create a new Popen instance.
# It's harmless that it was already removed, so ignore.
pass
PIPE = -1
STDOUT = -2
def _eintr_retry_call(func, *args):
while True:
try:
return func(*args)
except OSError, e:
if e.errno == errno.EINTR:
continue
raise
def call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete, then
return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
return Popen(*popenargs, **kwargs).wait()
def check_call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
check_call(["ls", "-l"])
"""
retcode = call(*popenargs, **kwargs)
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
if retcode:
raise CalledProcessError(retcode, cmd)
return retcode
def list2cmdline(seq):
"""
Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:
1) Arguments are delimited by white space, which is either a
space or a tab.
2) A string surrounded by double quotation marks is
interpreted as a single argument, regardless of white space
or pipe characters contained within. A quoted string can be
embedded in an argument.
3) A double quotation mark preceded by a backslash is
interpreted as a literal double quotation mark.
4) Backslashes are interpreted literally, unless they
immediately precede a double quotation mark.
5) If backslashes immediately precede a double quotation mark,
every pair of backslashes is interpreted as a literal
backslash. If the number of backslashes is odd, the last
backslash escapes the next double quotation mark as
described in rule 3.
"""
# See
# http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
# or search http://msdn.microsoft.com for
# "Parsing C++ Command-Line Arguments"
result = []
needquote = False
for arg in seq:
bs_buf = []
# Add a space to separate this argument from the others
if result:
result.append(' ')
needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
if needquote:
result.append('"')
for c in arg:
if c == '\\':
# Don't know if we need to double yet.
bs_buf.append(c)
elif c == '"':
# Double backslashes.
result.append('\\' * len(bs_buf)*2)
bs_buf = []
result.append('\\"')
else:
# Normal char
if bs_buf:
result.extend(bs_buf)
bs_buf = []
result.append(c)
# Add remaining backslashes, if any.
if bs_buf:
result.extend(bs_buf)
if needquote:
result.extend(bs_buf)
result.append('"')
return ''.join(result)
class Popen(object):
def __init__(self, args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
"""Create new Popen instance."""
_cleanup()
self._child_created = False
if not isinstance(bufsize, (int, long)):
raise TypeError("bufsize must be an integer")
if mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
if close_fds and (stdin is not None or stdout is not None or
stderr is not None):
raise ValueError("close_fds is not supported on Windows "
"platforms if you redirect stdin/stdout/stderr")
else:
# POSIX
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.universal_newlines = universal_newlines
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are None when not using PIPEs. The child objects are None
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
self._execute_child(args, executable, preexec_fn, close_fds,
cwd, env, universal_newlines,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
if mswindows:
if p2cwrite is not None:
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
if c2pread is not None:
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
if errread is not None:
errread = msvcrt.open_osfhandle(errread.Detach(), 0)
if p2cwrite is not None:
self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
if c2pread is not None:
if universal_newlines:
self.stdout = os.fdopen(c2pread, 'rU', bufsize)
else:
self.stdout = os.fdopen(c2pread, 'rb', bufsize)
if errread is not None:
if universal_newlines:
self.stderr = os.fdopen(errread, 'rU', bufsize)
else:
self.stderr = os.fdopen(errread, 'rb', bufsize)
def _translate_newlines(self, data):
data = data.replace("\r\n", "\n")
data = data.replace("\r", "\n")
return data
def __del__(self, sys=sys):
if not self._child_created:
# We didn't get to successfully create a child process.
return
# In case the child hasn't been waited on, check if it's done.
self._internal_poll(_deadstate=sys.maxint)
if self.returncode is None and _active is not None:
# Child is still running, keep us alive until we can wait on it.
_active.append(self)
def communicate(self, input=None):
"""Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.
communicate() returns a tuple (stdout, stderr)."""
# Optimization: If we are only using one pipe, or no pipe at
# all, using select() or threads is unnecessary.
if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
stdout = None
stderr = None
if self.stdin:
if input:
self.stdin.write(input)
self.stdin.close()
elif self.stdout:
stdout = self.stdout.read()
self.stdout.close()
elif self.stderr:
stderr = self.stderr.read()
self.stderr.close()
self.wait()
return (stdout, stderr)
return self._communicate(input)
def poll(self):
return self._internal_poll()
if mswindows:
#
# Windows methods
#
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tupel with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
if stdin is None and stdout is None and stderr is None:
return (None, None, None, None, None, None)
p2cread, p2cwrite = None, None
c2pread, c2pwrite = None, None
errread, errwrite = None, None
if stdin is None:
p2cread = GetStdHandle(STD_INPUT_HANDLE)
if p2cread is None:
p2cread, _ = CreatePipe(None, 0)
elif stdin == PIPE:
p2cread, p2cwrite = CreatePipe(None, 0)
elif isinstance(stdin, int):
p2cread = msvcrt.get_osfhandle(stdin)
else:
# Assuming file-like object
p2cread = msvcrt.get_osfhandle(stdin.fileno())
p2cread = self._make_inheritable(p2cread)
if stdout is None:
c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
if c2pwrite is None:
_, c2pwrite = CreatePipe(None, 0)
elif stdout == PIPE:
c2pread, c2pwrite = CreatePipe(None, 0)
elif isinstance(stdout, int):
c2pwrite = msvcrt.get_osfhandle(stdout)
else:
# Assuming file-like object
c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
c2pwrite = self._make_inheritable(c2pwrite)
if stderr is None:
errwrite = GetStdHandle(STD_ERROR_HANDLE)
if errwrite is None:
_, errwrite = CreatePipe(None, 0)
elif stderr == PIPE:
errread, errwrite = CreatePipe(None, 0)
elif stderr == STDOUT:
errwrite = c2pwrite
elif isinstance(stderr, int):
errwrite = msvcrt.get_osfhandle(stderr)
else:
# Assuming file-like object
errwrite = msvcrt.get_osfhandle(stderr.fileno())
errwrite = self._make_inheritable(errwrite)
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
def _make_inheritable(self, handle):
"""Return a duplicate of handle, which is inheritable"""
return DuplicateHandle(GetCurrentProcess(), handle,
GetCurrentProcess(), 0, 1,
DUPLICATE_SAME_ACCESS)
def _find_w9xpopen(self):
"""Find and return absolut path to w9xpopen.exe"""
w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
"w9xpopen.exe")
if not os.path.exists(w9xpopen):
# Eeek - file-not-found - possibly an embedding
# situation - see if we can locate it in sys.exec_prefix
w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
"w9xpopen.exe")
if not os.path.exists(w9xpopen):
raise RuntimeError("Cannot locate w9xpopen.exe, which is "
"needed for Popen to work with your "
"shell or platform.")
return w9xpopen
def _execute_child(self, args, executable, preexec_fn, close_fds,
cwd, env, universal_newlines,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
"""Execute program (MS Windows version)"""
if not isinstance(args, types.StringTypes):
args = list2cmdline(args)
# Process startup details
if startupinfo is None:
startupinfo = STARTUPINFO()
if None not in (p2cread, c2pwrite, errwrite):
startupinfo.dwFlags |= STARTF_USESTDHANDLES
startupinfo.hStdInput = p2cread
startupinfo.hStdOutput = c2pwrite
startupinfo.hStdError = errwrite
if shell:
startupinfo.dwFlags |= STARTF_USESHOWWINDOW
startupinfo.wShowWindow = SW_HIDE
comspec = os.environ.get("COMSPEC", "cmd.exe")
args = comspec + " /c " + args
if (GetVersion() >= 0x80000000L or
os.path.basename(comspec).lower() == "command.com"):
# Win9x, or using command.com on NT. We need to
# use the w9xpopen intermediate program. For more
# information, see KB Q150956
# (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
w9xpopen = self._find_w9xpopen()
args = '"%s" %s' % (w9xpopen, args)
# Not passing CREATE_NEW_CONSOLE has been known to
# cause random failures on win9x. Specifically a
# dialog: "Your program accessed mem currently in
# use at xxx" and a hopeful warning about the
# stability of your system. Cost is Ctrl+C wont
# kill children.
creationflags |= CREATE_NEW_CONSOLE
# Start the process
try:
hp, ht, pid, tid = CreateProcess(executable, args,
# no special security
None, None,
int(not close_fds),
creationflags,
env,
cwd,
startupinfo)
except pywintypes.error, e:
# Translate pywintypes.error to WindowsError, which is
# a subclass of OSError. FIXME: We should really
# translate errno using _sys_errlist (or simliar), but
# how can this be done from Python?
raise WindowsError(*e.args)
# Retain the process handle, but close the thread handle
self._child_created = True
self._handle = hp
self.pid = pid
ht.Close()
# Child is launched. Close the parent's copy of those pipe
# handles that only the child should have open. You need
# to make sure that no handles to the write end of the
# output pipe are maintained in this process or else the
# pipe will not close when the child process exits and the
# ReadFile will hang.
if p2cread is not None:
p2cread.Close()
if c2pwrite is not None:
c2pwrite.Close()
if errwrite is not None:
errwrite.Close()
def _internal_poll(self, _deadstate=None):
"""Check if child process has terminated. Returns returncode
attribute."""
if self.returncode is None:
if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
self.returncode = GetExitCodeProcess(self._handle)
return self.returncode
def wait(self):
"""Wait for child process to terminate. Returns returncode
attribute."""
if self.returncode is None:
obj = WaitForSingleObject(self._handle, INFINITE)
self.returncode = GetExitCodeProcess(self._handle)
return self.returncode
def _readerthread(self, fh, buffer):
buffer.append(fh.read())
def _communicate(self, input):
stdout = None # Return
stderr = None # Return
if self.stdout:
stdout = []
stdout_thread = threading.Thread(target=self._readerthread,
args=(self.stdout, stdout))
stdout_thread.setDaemon(True)
stdout_thread.start()
if self.stderr:
stderr = []
stderr_thread = threading.Thread(target=self._readerthread,
args=(self.stderr, stderr))
stderr_thread.setDaemon(True)
stderr_thread.start()
if self.stdin:
if input is not None:
self.stdin.write(input)
self.stdin.close()
if self.stdout:
stdout_thread.join()
if self.stderr:
stderr_thread.join()
# All data exchanged. Translate lists into strings.
if stdout is not None:
stdout = stdout[0]
if stderr is not None:
stderr = stderr[0]
# Translate newlines, if requested. We cannot let the file
# object do the translation: It is based on stdio, which is
# impossible to combine with select (unless forcing no
# buffering).
if self.universal_newlines and hasattr(file, 'newlines'):
if stdout:
stdout = self._translate_newlines(stdout)
if stderr:
stderr = self._translate_newlines(stderr)
self.wait()
return (stdout, stderr)
def send_signal(self, sig):
"""Send a signal to the process
"""
if sig == signal.SIGTERM:
self.terminate()
else:
raise ValueError("Only SIGTERM is supported on Windows")
def terminate(self):
"""Terminates the process
"""
TerminateProcess(self._handle, 1)
kill = terminate
else:
#
# POSIX methods
#
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tupel with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
p2cread, p2cwrite = None, None
c2pread, c2pwrite = None, None
errread, errwrite = None, None
if stdin is None:
pass
elif stdin == PIPE:
p2cread, p2cwrite = os.pipe()
elif isinstance(stdin, int):
p2cread = stdin
else:
# Assuming file-like object
p2cread = stdin.fileno()
if stdout is None:
pass
elif stdout == PIPE:
c2pread, c2pwrite = os.pipe()
elif isinstance(stdout, int):
c2pwrite = stdout
else:
# Assuming file-like object
c2pwrite = stdout.fileno()
if stderr is None:
pass
elif stderr == PIPE:
errread, errwrite = os.pipe()
elif stderr == STDOUT:
errwrite = c2pwrite
elif isinstance(stderr, int):
errwrite = stderr
else:
# Assuming file-like object
errwrite = stderr.fileno()
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
def _set_cloexec_flag(self, fd):
try:
cloexec_flag = fcntl.FD_CLOEXEC
except AttributeError:
cloexec_flag = 1
old = fcntl.fcntl(fd, fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
def _close_fds(self, but):
os.closerange(3, but)
os.closerange(but + 1, MAXFD)
def _execute_child(self, args, executable, preexec_fn, close_fds,
cwd, env, universal_newlines,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
"""Execute program (POSIX version)"""
if isinstance(args, types.StringTypes):
args = [args]
else:
args = list(args)
if shell:
args = ["/bin/sh", "-c"] + args
if executable is None:
executable = args[0]
# For transferring possible exec failure from child to parent
# The first char specifies the exception type: 0 means
# OSError, 1 means some other error.
errpipe_read, errpipe_write = os.pipe()
try:
try:
self._set_cloexec_flag(errpipe_write)
gc_was_enabled = gc.isenabled()
# Disable gc to avoid bug where gc -> file_dealloc ->
# write to stderr -> hang. http://bugs.python.org/issue1336
gc.disable()
try:
self.pid = os.fork()
except:
if gc_was_enabled:
gc.enable()
raise
self._child_created = True
if self.pid == 0:
# Child
try:
# Close parent's pipe ends
if p2cwrite is not None:
os.close(p2cwrite)
if c2pread is not None:
os.close(c2pread)
if errread is not None:
os.close(errread)
os.close(errpipe_read)
# Dup fds for child
if p2cread is not None:
os.dup2(p2cread, 0)
if c2pwrite is not None:
os.dup2(c2pwrite, 1)
if errwrite is not None:
os.dup2(errwrite, 2)
# Close pipe fds. Make sure we don't close the same
# fd more than once, or standard fds.
if p2cread is not None and p2cread not in (0,):
os.close(p2cread)
if c2pwrite is not None and c2pwrite not in (p2cread, 1):
os.close(c2pwrite)
if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
os.close(errwrite)
# Close all other fds, if asked for
if close_fds:
self._close_fds(but=errpipe_write)
if cwd is not None:
os.chdir(cwd)
if preexec_fn:
preexec_fn()
if env is None:
os.execvp(executable, args)
else:
os.execvpe(executable, args, env)
except:
exc_type, exc_value, tb = sys.exc_info()
# Save the traceback and attach it to the exception object
exc_lines = traceback.format_exception(exc_type,
exc_value,
tb)
exc_value.child_traceback = ''.join(exc_lines)
os.write(errpipe_write, pickle.dumps(exc_value))
# This exitcode won't be reported to applications, so it
# really doesn't matter what we return.
os._exit(255)
# Parent
if gc_was_enabled:
gc.enable()
finally:
# be sure the FD is closed no matter what
os.close(errpipe_write)
if p2cread is not None and p2cwrite is not None:
os.close(p2cread)
if c2pwrite is not None and c2pread is not None:
os.close(c2pwrite)
if errwrite is not None and errread is not None:
os.close(errwrite)
# Wait for exec to fail or succeed; possibly raising exception
# Exception limited to 1M
data = _eintr_retry_call(os.read, errpipe_read, 1048576)
finally:
# be sure the FD is closed no matter what
os.close(errpipe_read)
if data != "":
_eintr_retry_call(os.waitpid, self.pid, 0)
child_exception = pickle.loads(data)
for fd in (p2cwrite, c2pread, errread):
if fd is not None:
os.close(fd)
raise child_exception
def _handle_exitstatus(self, sts):
if os.WIFSIGNALED(sts):
self.returncode = -os.WTERMSIG(sts)
elif os.WIFEXITED(sts):
self.returncode = os.WEXITSTATUS(sts)
else:
# Should never happen
raise RuntimeError("Unknown child exit status!")
def _internal_poll(self, _deadstate=None):
"""Check if child process has terminated. Returns returncode
attribute."""
if self.returncode is None:
try:
pid, sts = os.waitpid(self.pid, os.WNOHANG)
if pid == self.pid:
self._handle_exitstatus(sts)
except os.error:
if _deadstate is not None:
self.returncode = _deadstate
return self.returncode
def wait(self):
"""Wait for child process to terminate. Returns returncode
attribute."""
if self.returncode is None:
pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
self._handle_exitstatus(sts)
return self.returncode
def _communicate(self, input):
read_set = []
write_set = []
stdout = None # Return
stderr = None # Return
if self.stdin:
# Flush stdio buffer. This might block, if the user has
# been writing to .stdin in an uncontrolled fashion.
self.stdin.flush()
if input:
write_set.append(self.stdin)
else:
self.stdin.close()
if self.stdout:
read_set.append(self.stdout)
stdout = []
if self.stderr:
read_set.append(self.stderr)
stderr = []
input_offset = 0
while read_set or write_set:
try:
rlist, wlist, xlist = select.select(read_set, write_set, [])
except select.error, e:
if e.args[0] == errno.EINTR:
continue
raise
if self.stdin in wlist:
# When select has indicated that the file is writable,
# we can write up to PIPE_BUF bytes without risk
# blocking. POSIX defines PIPE_BUF >= 512
chunk = input[input_offset : input_offset + 512]
bytes_written = os.write(self.stdin.fileno(), chunk)
input_offset += bytes_written
if input_offset >= len(input):
self.stdin.close()
write_set.remove(self.stdin)
if self.stdout in rlist:
data = os.read(self.stdout.fileno(), 1024)
if data == "":
self.stdout.close()
read_set.remove(self.stdout)
stdout.append(data)
if self.stderr in rlist:
data = os.read(self.stderr.fileno(), 1024)
if data == "":
self.stderr.close()
read_set.remove(self.stderr)
stderr.append(data)
# All data exchanged. Translate lists into strings.
if stdout is not None:
stdout = ''.join(stdout)
if stderr is not None:
stderr = ''.join(stderr)
# Translate newlines, if requested. We cannot let the file
# object do the translation: It is based on stdio, which is
# impossible to combine with select (unless forcing no
# buffering).
if self.universal_newlines and hasattr(file, 'newlines'):
if stdout:
stdout = self._translate_newlines(stdout)
if stderr:
stderr = self._translate_newlines(stderr)
self.wait()
return (stdout, stderr)
def send_signal(self, sig):
"""Send a signal to the process
"""
os.kill(self.pid, sig)
def terminate(self):
"""Terminate the process with SIGTERM
"""
self.send_signal(signal.SIGTERM)
def kill(self):
"""Kill the process with SIGKILL
"""
self.send_signal(signal.SIGKILL)
def _demo_posix():
#
# Example 1: Simple redirection: Get process list
#
plist = Popen(["ps"], stdout=PIPE).communicate()[0]
print "Process list:"
print plist
#
# Example 2: Change uid before executing child
#
if os.getuid() == 0:
p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
p.wait()
#
# Example 3: Connecting several subprocesses
#
print "Looking for 'hda'..."
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
print repr(p2.communicate()[0])
#
# Example 4: Catch execution error
#
print
print "Trying a weird file..."
try:
print Popen(["/this/path/does/not/exist"]).communicate()
except OSError, e:
if e.errno == errno.ENOENT:
print "The file didn't exist. I thought so..."
print "Child traceback:"
print e.child_traceback
else:
print "Error", e.errno
else:
print >>sys.stderr, "Gosh. No error."
def _demo_windows():
#
# Example 1: Connecting several subprocesses
#
print "Looking for 'PROMPT' in set output..."
p1 = Popen("set", stdout=PIPE, shell=True)
p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
print repr(p2.communicate()[0])
#
# Example 2: Simple execution of program
#
print "Executing calc..."
p = Popen("calc")
p.wait()
if __name__ == "__main__":
if mswindows:
_demo_windows()
else:
_demo_posix()
| Python |
"""Utilities for writing code that runs on Python 2 and 3"""
import sys
import types
__author__ = "Benjamin Peterson <benjamin@python.org>"
__version__ = "1.0.0"
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
MAXSIZE = sys.maxint
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, tp):
result = self._resolve()
setattr(obj, self.name, result)
# This is a bit ugly, but it avoids running this again.
delattr(tp, self.name)
return result
class MovedModule(_LazyDescr):
def __init__(self, name, old, new=None):
super(MovedModule, self).__init__(name)
if PY3:
if new is None:
new = name
self.mod = new
else:
self.mod = old
def _resolve(self):
return _import_module(self.mod)
class MovedAttribute(_LazyDescr):
def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):
super(MovedAttribute, self).__init__(name)
if PY3:
if new_mod is None:
new_mod = name
self.mod = new_mod
if new_attr is None:
if old_attr is None:
new_attr = name
else:
new_attr = old_attr
self.attr = new_attr
else:
self.mod = old_mod
if old_attr is None:
old_attr = name
self.attr = old_attr
def _resolve(self):
module = _import_module(self.mod)
return getattr(module, self.attr)
class _MovedItems(types.ModuleType):
"""Lazy loading of moved objects"""
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("StringIO", "StringIO", "io"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("cPickle", "cPickle", "pickle"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
"tkinter.colorchooser"),
MovedModule("tkinter_commondialog", "tkCommonDialog",
"tkinter.commondialog"),
MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"),
MovedModule("tkinter_font", "tkFont", "tkinter.font"),
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
del attr
moves = sys.modules["six.moves"] = _MovedItems("moves")
def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move)
def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,))
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
_func_code = "__code__"
_func_defaults = "__defaults__"
else:
_meth_func = "im_func"
_meth_self = "im_self"
_func_code = "func_code"
_func_defaults = "func_defaults"
if PY3:
def get_unbound_function(unbound):
return unbound
advance_iterator = next
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
else:
def get_unbound_function(unbound):
return unbound.im_func
def advance_iterator(it):
return it.next()
callable = callable
_add_doc(get_unbound_function,
"""Get the function out of a possibly unbound function""")
def get_method_function(meth):
"""Get the underlying function of a bound method."""
return getattr(meth, _meth_func)
def get_method_self(meth):
"""Get the self of a bound method."""
return getattr(meth, _meth_self)
def get_function_code(func):
"""Get code object of a function."""
return getattr(func, _func_code)
def get_function_defaults(func):
"""Get defaults of a function."""
return getattr(func, _func_defaults)
if PY3:
def b(s):
return s.encode("latin-1")
def u(s):
return s
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
else:
def b(s):
return s
def u(s):
return unicode(s, "unicode_escape")
import StringIO
StringIO = BytesIO = StringIO.StringIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
if PY3:
exec_ = eval("exec")
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
print_ = eval("print")
def with_metaclass(meta, base=object):
ns = dict(base=base, meta=meta)
exec_("""class NewBase(base, metaclass=meta):
pass""", ns)
return ns["NewBase"]
else:
def exec_(code, globs=None, locs=None):
"""Execute code in a namespace."""
if globs is None:
frame = sys._getframe(1)
globs = frame.f_globals
if locs is None:
locs = frame.f_locals
del frame
elif locs is None:
locs = globs
exec("""exec code in globs, locs""")
exec_("""def reraise(tp, value, tb=None):
raise tp, value, tb
""")
def print_(*args, **kwargs):
"""The new-style print function."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
else:
newline = "\n"
space = " "
if sep is None:
sep = space
if end is None:
end = newline
for i, arg in enumerate(args):
if i:
write(sep)
write(arg)
write(end)
def with_metaclass(meta, base=object):
class NewBase(base):
__metaclass__ = meta
return NewBase
_add_doc(reraise, """Reraise an exception.""")
_add_doc(with_metaclass, """Create a base class with a metaclass""")
| Python |
import os
import sys
try:
from functools import wraps
except ImportError:
# only needed for Python 2.4
def wraps(_):
def _wraps(func):
return func
return _wraps
__unittest = True
def _relpath_nt(path, start=os.path.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.path.sep)
path_list = os.path.abspath(path).split(os.path.sep)
if start_list[0].lower() != path_list[0].lower():
unc_path, rest = os.path.splitunc(path)
unc_start, rest = os.path.splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
% (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0], start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
break
else:
i += 1
rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return os.path.curdir
return os.path.join(*rel_list)
# default to posixpath definition
def _relpath_posix(path, start=os.path.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.path.sep)
path_list = os.path.abspath(path).split(os.path.sep)
# Work out how much of the filepath is shared by start and path.
i = len(os.path.commonprefix([start_list, path_list]))
rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return os.path.curdir
return os.path.join(*rel_list)
if os.path is sys.modules.get('ntpath'):
relpath = _relpath_nt
else:
relpath = _relpath_posix
| Python |
"""Unittest main program"""
import sys
import os
import types
from unittest2 import loader, runner
try:
from unittest2.signals import installHandler
except ImportError:
installHandler = None
__unittest = True
FAILFAST = " -f, --failfast Stop on first failure\n"
CATCHBREAK = " -c, --catch Catch control-C and display results\n"
BUFFEROUTPUT = " -b, --buffer Buffer stdout and stderr during test runs\n"
USAGE_AS_MAIN = """\
Usage: %(progName)s [options] [tests]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
%(failfast)s%(catchbreak)s%(buffer)s
Examples:
%(progName)s test_module - run tests from test_module
%(progName)s test_module.TestClass - run tests from
test_module.TestClass
%(progName)s test_module.TestClass.test_method - run specified test method
[tests] can be a list of any number of test modules, classes and test
methods.
Alternative Usage: %(progName)s discover [options]
Options:
-v, --verbose Verbose output
%(failfast)s%(catchbreak)s%(buffer)s -s directory Directory to start discovery ('.' default)
-p pattern Pattern to match test files ('test*.py' default)
-t directory Top level directory of project (default to
start directory)
For test discovery all test modules must be importable from the top
level directory of the project.
"""
USAGE_FROM_MODULE = """\
Usage: %(progName)s [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
%(failfast)s%(catchbreak)s%(buffer)s
Examples:
%(progName)s - run default set of tests
%(progName)s MyTestSuite - run suite 'MyTestSuite'
%(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
%(progName)s MyTestCase - run all 'test*' test methods
in MyTestCase
"""
class TestProgram(object):
"""A command-line program that runs a set of tests; this is primarily
for making test modules conveniently executable.
"""
USAGE = USAGE_FROM_MODULE
# defaults for testing
failfast = catchbreak = buffer = progName = None
def __init__(self, module='__main__', defaultTest=None,
argv=None, testRunner=None,
testLoader=loader.defaultTestLoader, exit=True,
verbosity=1, failfast=None, catchbreak=None, buffer=None):
if isinstance(module, basestring):
self.module = __import__(module)
for part in module.split('.')[1:]:
self.module = getattr(self.module, part)
else:
self.module = module
if argv is None:
argv = sys.argv
self.exit = exit
self.verbosity = verbosity
self.failfast = failfast
self.catchbreak = catchbreak
self.buffer = buffer
self.defaultTest = defaultTest
self.testRunner = testRunner
self.testLoader = testLoader
self.progName = os.path.basename(argv[0])
self.parseArgs(argv)
self.runTests()
def usageExit(self, msg=None):
if msg:
print msg
usage = {'progName': self.progName, 'catchbreak': '', 'failfast': '',
'buffer': ''}
if self.failfast != False:
usage['failfast'] = FAILFAST
if self.catchbreak != False and installHandler is not None:
usage['catchbreak'] = CATCHBREAK
if self.buffer != False:
usage['buffer'] = BUFFEROUTPUT
print self.USAGE % usage
sys.exit(2)
def parseArgs(self, argv):
if len(argv) > 1 and argv[1].lower() == 'discover':
self._do_discovery(argv[2:])
return
import getopt
long_opts = ['help', 'verbose', 'quiet', 'failfast', 'catch', 'buffer']
try:
options, args = getopt.getopt(argv[1:], 'hHvqfcb', long_opts)
for opt, value in options:
if opt in ('-h','-H','--help'):
self.usageExit()
if opt in ('-q','--quiet'):
self.verbosity = 0
if opt in ('-v','--verbose'):
self.verbosity = 2
if opt in ('-f','--failfast'):
if self.failfast is None:
self.failfast = True
# Should this raise an exception if -f is not valid?
if opt in ('-c','--catch'):
if self.catchbreak is None and installHandler is not None:
self.catchbreak = True
# Should this raise an exception if -c is not valid?
if opt in ('-b','--buffer'):
if self.buffer is None:
self.buffer = True
# Should this raise an exception if -b is not valid?
if len(args) == 0 and self.defaultTest is None:
# createTests will load tests from self.module
self.testNames = None
elif len(args) > 0:
self.testNames = args
if __name__ == '__main__':
# to support python -m unittest ...
self.module = None
else:
self.testNames = (self.defaultTest,)
self.createTests()
except getopt.error, msg:
self.usageExit(msg)
def createTests(self):
if self.testNames is None:
self.test = self.testLoader.loadTestsFromModule(self.module)
else:
self.test = self.testLoader.loadTestsFromNames(self.testNames,
self.module)
def _do_discovery(self, argv, Loader=loader.TestLoader):
# handle command line args for test discovery
self.progName = '%s discover' % self.progName
import optparse
parser = optparse.OptionParser()
parser.prog = self.progName
parser.add_option('-v', '--verbose', dest='verbose', default=False,
help='Verbose output', action='store_true')
if self.failfast != False:
parser.add_option('-f', '--failfast', dest='failfast', default=False,
help='Stop on first fail or error',
action='store_true')
if self.catchbreak != False and installHandler is not None:
parser.add_option('-c', '--catch', dest='catchbreak', default=False,
help='Catch ctrl-C and display results so far',
action='store_true')
if self.buffer != False:
parser.add_option('-b', '--buffer', dest='buffer', default=False,
help='Buffer stdout and stderr during tests',
action='store_true')
parser.add_option('-s', '--start-directory', dest='start', default='.',
help="Directory to start discovery ('.' default)")
parser.add_option('-p', '--pattern', dest='pattern', default='test*.py',
help="Pattern to match tests ('test*.py' default)")
parser.add_option('-t', '--top-level-directory', dest='top', default=None,
help='Top level directory of project (defaults to start directory)')
options, args = parser.parse_args(argv)
if len(args) > 3:
self.usageExit()
for name, value in zip(('start', 'pattern', 'top'), args):
setattr(options, name, value)
# only set options from the parsing here
# if they weren't set explicitly in the constructor
if self.failfast is None:
self.failfast = options.failfast
if self.catchbreak is None and installHandler is not None:
self.catchbreak = options.catchbreak
if self.buffer is None:
self.buffer = options.buffer
if options.verbose:
self.verbosity = 2
start_dir = options.start
pattern = options.pattern
top_level_dir = options.top
loader = Loader()
self.test = loader.discover(start_dir, pattern, top_level_dir)
def runTests(self):
if self.catchbreak:
installHandler()
if self.testRunner is None:
self.testRunner = runner.TextTestRunner
if isinstance(self.testRunner, (type, types.ClassType)):
try:
testRunner = self.testRunner(verbosity=self.verbosity,
failfast=self.failfast,
buffer=self.buffer)
except TypeError:
# didn't accept the verbosity, buffer or failfast arguments
testRunner = self.testRunner()
else:
# it is assumed to be a TestRunner instance
testRunner = self.testRunner
self.result = testRunner.run(self.test)
if self.exit:
sys.exit(not self.result.wasSuccessful())
main = TestProgram
def main_():
TestProgram.USAGE = USAGE_AS_MAIN
main(module=None)
| Python |
import signal
import weakref
from unittest2.compatibility import wraps
__unittest = True
class _InterruptHandler(object):
def __init__(self, default_handler):
self.called = False
self.default_handler = default_handler
def __call__(self, signum, frame):
installed_handler = signal.getsignal(signal.SIGINT)
if installed_handler is not self:
# if we aren't the installed handler, then delegate immediately
# to the default handler
self.default_handler(signum, frame)
if self.called:
self.default_handler(signum, frame)
self.called = True
for result in _results.keys():
result.stop()
_results = weakref.WeakKeyDictionary()
def registerResult(result):
_results[result] = 1
def removeResult(result):
return bool(_results.pop(result, None))
_interrupt_handler = None
def installHandler():
global _interrupt_handler
if _interrupt_handler is None:
default_handler = signal.getsignal(signal.SIGINT)
_interrupt_handler = _InterruptHandler(default_handler)
signal.signal(signal.SIGINT, _interrupt_handler)
def removeHandler(method=None):
if method is not None:
def inner(*args, **kwargs):
initial = signal.getsignal(signal.SIGINT)
removeHandler()
try:
return method(*args, **kwargs)
finally:
signal.signal(signal.SIGINT, initial)
inner = wraps(method)(inner)
return inner
global _interrupt_handler
if _interrupt_handler is not None:
signal.signal(signal.SIGINT, _interrupt_handler.default_handler)
| Python |
"""Test result object"""
import sys
import traceback
import unittest
from StringIO import StringIO
from unittest2 import util
from unittest2.compatibility import wraps
__unittest = True
def failfast(method):
def inner(self, *args, **kw):
if getattr(self, 'failfast', False):
self.stop()
return method(self, *args, **kw)
inner = wraps(method)(inner)
return inner
STDOUT_LINE = '\nStdout:\n%s'
STDERR_LINE = '\nStderr:\n%s'
class TestResult(unittest.TestResult):
"""Holder for test result information.
Test results are automatically managed by the TestCase and TestSuite
classes, and do not need to be explicitly manipulated by writers of tests.
Each instance holds the total number of tests run, and collections of
failures and errors that occurred among those test runs. The collections
contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
formatted traceback of the error that occurred.
"""
_previousTestClass = None
_moduleSetUpFailed = False
def __init__(self):
self.failfast = False
self.failures = []
self.errors = []
self.testsRun = 0
self.skipped = []
self.expectedFailures = []
self.unexpectedSuccesses = []
self.shouldStop = False
self.buffer = False
self._stdout_buffer = None
self._stderr_buffer = None
self._original_stdout = sys.stdout
self._original_stderr = sys.stderr
self._mirrorOutput = False
def startTest(self, test):
"Called when the given test is about to be run"
self.testsRun += 1
self._mirrorOutput = False
if self.buffer:
if self._stderr_buffer is None:
self._stderr_buffer = StringIO()
self._stdout_buffer = StringIO()
sys.stdout = self._stdout_buffer
sys.stderr = self._stderr_buffer
def startTestRun(self):
"""Called once before any tests are executed.
See startTest for a method called before each test.
"""
def stopTest(self, test):
"""Called when the given test has been run"""
if self.buffer:
if self._mirrorOutput:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
self._original_stdout.write(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
self._original_stderr.write(STDERR_LINE % error)
sys.stdout = self._original_stdout
sys.stderr = self._original_stderr
self._stdout_buffer.seek(0)
self._stdout_buffer.truncate()
self._stderr_buffer.seek(0)
self._stderr_buffer.truncate()
self._mirrorOutput = False
def stopTestRun(self):
"""Called once after all tests are executed.
See stopTest for a method called after each test.
"""
def addError(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info().
"""
self.errors.append((test, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
addError = failfast(addError)
def addFailure(self, test, err):
"""Called when an error has occurred. 'err' is a tuple of values as
returned by sys.exc_info()."""
self.failures.append((test, self._exc_info_to_string(err, test)))
self._mirrorOutput = True
addFailure = failfast(addFailure)
def addSuccess(self, test):
"Called when a test has completed successfully"
pass
def addSkip(self, test, reason):
"""Called when a test is skipped."""
self.skipped.append((test, reason))
def addExpectedFailure(self, test, err):
"""Called when an expected failure/error occured."""
self.expectedFailures.append(
(test, self._exc_info_to_string(err, test)))
def addUnexpectedSuccess(self, test):
"""Called when a test was expected to fail, but succeed."""
self.unexpectedSuccesses.append(test)
addUnexpectedSuccess = failfast(addUnexpectedSuccess)
def wasSuccessful(self):
"Tells whether or not this result was a success"
return (len(self.failures) + len(self.errors) == 0)
def stop(self):
"Indicates that the tests should be aborted"
self.shouldStop = True
def _exc_info_to_string(self, err, test):
"""Converts a sys.exc_info()-style tuple of values into a string."""
exctype, value, tb = err
# Skip test runner traceback levels
while tb and self._is_relevant_tb_level(tb):
tb = tb.tb_next
if exctype is test.failureException:
# Skip assert*() traceback levels
length = self._count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format_exception(exctype, value, tb)
if self.buffer:
output = sys.stdout.getvalue()
error = sys.stderr.getvalue()
if output:
if not output.endswith('\n'):
output += '\n'
msgLines.append(STDOUT_LINE % output)
if error:
if not error.endswith('\n'):
error += '\n'
msgLines.append(STDERR_LINE % error)
return ''.join(msgLines)
def _is_relevant_tb_level(self, tb):
return '__unittest' in tb.tb_frame.f_globals
def _count_relevant_tb_levels(self, tb):
length = 0
while tb and not self._is_relevant_tb_level(tb):
length += 1
tb = tb.tb_next
return length
def __repr__(self):
return "<%s run=%i errors=%i failures=%i>" % \
(util.strclass(self.__class__), self.testsRun, len(self.errors),
len(self.failures))
| Python |
import os
import sys
from unittest2.loader import defaultTestLoader
def collector():
# import __main__ triggers code re-execution
__main__ = sys.modules['__main__']
setupDir = os.path.abspath(os.path.dirname(__main__.__file__))
return defaultTestLoader.discover(setupDir)
| Python |
"""TestSuite"""
import sys
import unittest
from unittest2 import case, util
__unittest = True
class BaseTestSuite(unittest.TestSuite):
"""A simple test suite that doesn't provide class or module shared fixtures.
"""
def __init__(self, tests=()):
self._tests = []
self.addTests(tests)
def __repr__(self):
return "<%s tests=%s>" % (util.strclass(self.__class__), list(self))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return list(self) == list(other)
def __ne__(self, other):
return not self == other
# Can't guarantee hash invariant, so flag as unhashable
__hash__ = None
def __iter__(self):
return iter(self._tests)
def countTestCases(self):
cases = 0
for test in self:
cases += test.countTestCases()
return cases
def addTest(self, test):
# sanity checks
if not hasattr(test, '__call__'):
raise TypeError("%r is not callable" % (repr(test),))
if isinstance(test, type) and issubclass(test,
(case.TestCase, TestSuite)):
raise TypeError("TestCases and TestSuites must be instantiated "
"before passing them to addTest()")
self._tests.append(test)
def addTests(self, tests):
if isinstance(tests, basestring):
raise TypeError("tests must be an iterable of tests, not a string")
for test in tests:
self.addTest(test)
def run(self, result):
for test in self:
if result.shouldStop:
break
test(result)
return result
def __call__(self, *args, **kwds):
return self.run(*args, **kwds)
def debug(self):
"""Run the tests without collecting errors in a TestResult"""
for test in self:
test.debug()
class TestSuite(BaseTestSuite):
"""A test suite is a composite test consisting of a number of TestCases.
For use, create an instance of TestSuite, then add test case instances.
When all tests have been added, the suite can be passed to a test
runner, such as TextTestRunner. It will run the individual test cases
in the order in which they were added, aggregating the results. When
subclassing, do not forget to call the base class constructor.
"""
def run(self, result):
self._wrapped_run(result)
self._tearDownPreviousClass(None, result)
self._handleModuleTearDown(result)
return result
def debug(self):
"""Run the tests without collecting errors in a TestResult"""
debug = _DebugResult()
self._wrapped_run(debug, True)
self._tearDownPreviousClass(None, debug)
self._handleModuleTearDown(debug)
################################
# private methods
def _wrapped_run(self, result, debug=False):
for test in self:
if result.shouldStop:
break
if _isnotsuite(test):
self._tearDownPreviousClass(test, result)
self._handleModuleFixture(test, result)
self._handleClassSetUp(test, result)
result._previousTestClass = test.__class__
if (getattr(test.__class__, '_classSetupFailed', False) or
getattr(result, '_moduleSetUpFailed', False)):
continue
if hasattr(test, '_wrapped_run'):
test._wrapped_run(result, debug)
elif not debug:
test(result)
else:
test.debug()
def _handleClassSetUp(self, test, result):
previousClass = getattr(result, '_previousTestClass', None)
currentClass = test.__class__
if currentClass == previousClass:
return
if result._moduleSetUpFailed:
return
if getattr(currentClass, "__unittest_skip__", False):
return
try:
currentClass._classSetupFailed = False
except TypeError:
# test may actually be a function
# so its class will be a builtin-type
pass
setUpClass = getattr(currentClass, 'setUpClass', None)
if setUpClass is not None:
try:
setUpClass()
except Exception, e:
if isinstance(result, _DebugResult):
raise
currentClass._classSetupFailed = True
className = util.strclass(currentClass)
errorName = 'setUpClass (%s)' % className
self._addClassOrModuleLevelException(result, e, errorName)
def _get_previous_module(self, result):
previousModule = None
previousClass = getattr(result, '_previousTestClass', None)
if previousClass is not None:
previousModule = previousClass.__module__
return previousModule
def _handleModuleFixture(self, test, result):
previousModule = self._get_previous_module(result)
currentModule = test.__class__.__module__
if currentModule == previousModule:
return
self._handleModuleTearDown(result)
result._moduleSetUpFailed = False
try:
module = sys.modules[currentModule]
except KeyError:
return
setUpModule = getattr(module, 'setUpModule', None)
if setUpModule is not None:
try:
setUpModule()
except Exception, e:
if isinstance(result, _DebugResult):
raise
result._moduleSetUpFailed = True
errorName = 'setUpModule (%s)' % currentModule
self._addClassOrModuleLevelException(result, e, errorName)
def _addClassOrModuleLevelException(self, result, exception, errorName):
error = _ErrorHolder(errorName)
addSkip = getattr(result, 'addSkip', None)
if addSkip is not None and isinstance(exception, case.SkipTest):
addSkip(error, str(exception))
else:
result.addError(error, sys.exc_info())
def _handleModuleTearDown(self, result):
previousModule = self._get_previous_module(result)
if previousModule is None:
return
if result._moduleSetUpFailed:
return
try:
module = sys.modules[previousModule]
except KeyError:
return
tearDownModule = getattr(module, 'tearDownModule', None)
if tearDownModule is not None:
try:
tearDownModule()
except Exception, e:
if isinstance(result, _DebugResult):
raise
errorName = 'tearDownModule (%s)' % previousModule
self._addClassOrModuleLevelException(result, e, errorName)
def _tearDownPreviousClass(self, test, result):
previousClass = getattr(result, '_previousTestClass', None)
currentClass = test.__class__
if currentClass == previousClass:
return
if getattr(previousClass, '_classSetupFailed', False):
return
if getattr(result, '_moduleSetUpFailed', False):
return
if getattr(previousClass, "__unittest_skip__", False):
return
tearDownClass = getattr(previousClass, 'tearDownClass', None)
if tearDownClass is not None:
try:
tearDownClass()
except Exception, e:
if isinstance(result, _DebugResult):
raise
className = util.strclass(previousClass)
errorName = 'tearDownClass (%s)' % className
self._addClassOrModuleLevelException(result, e, errorName)
class _ErrorHolder(object):
"""
Placeholder for a TestCase inside a result. As far as a TestResult
is concerned, this looks exactly like a unit test. Used to insert
arbitrary errors into a test suite run.
"""
# Inspired by the ErrorHolder from Twisted:
# http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py
# attribute used by TestResult._exc_info_to_string
failureException = None
def __init__(self, description):
self.description = description
def id(self):
return self.description
def shortDescription(self):
return None
def __repr__(self):
return "<ErrorHolder description=%r>" % (self.description,)
def __str__(self):
return self.id()
def run(self, result):
# could call result.addError(...) - but this test-like object
# shouldn't be run anyway
pass
def __call__(self, result):
return self.run(result)
def countTestCases(self):
return 0
def _isnotsuite(test):
"A crude way to tell apart testcases and suites with duck-typing"
try:
iter(test)
except TypeError:
return True
return False
class _DebugResult(object):
"Used by the TestSuite to hold previous class when running in debug."
_previousTestClass = None
_moduleSetUpFailed = False
shouldStop = False
| Python |
"""Test case implementation"""
import sys
import difflib
import pprint
import re
import unittest
import warnings
if sys.version_info[:2] == (2,3):
from sets import Set as set
from sets import ImmutableSet as frozenset
from unittest2 import result
from unittest2.util import\
safe_repr, safe_str, strclass,\
unorderable_list_difference
from unittest2.compatibility import wraps
__unittest = True
DIFF_OMITTED = ('\nDiff is %s characters long. '
'Set self.maxDiff to None to see it.')
class SkipTest(Exception):
"""
Raise this exception in a test to skip it.
Usually you can use TestResult.skip() or one of the skipping decorators
instead of raising this directly.
"""
class _ExpectedFailure(Exception):
"""
Raise this when a test is expected to fail.
This is an implementation detail.
"""
def __init__(self, exc_info):
# can't use super because Python 2.4 exceptions are old style
Exception.__init__(self)
self.exc_info = exc_info
class _UnexpectedSuccess(Exception):
"""
The test was supposed to fail, but it didn't!
"""
def _id(obj):
return obj
def skip(reason):
"""
Unconditionally skip a test.
"""
def decorator(test_item):
if not (isinstance(test_item, type) and issubclass(test_item, TestCase)):
def skip_wrapper(*args, **kwargs):
raise SkipTest(reason)
skip_wrapper = wraps(test_item)(skip_wrapper)
test_item = skip_wrapper
test_item.__unittest_skip__ = True
test_item.__unittest_skip_why__ = reason
return test_item
return decorator
def skipIf(condition, reason):
"""
Skip a test if the condition is true.
"""
if condition:
return skip(reason)
return _id
def skipUnless(condition, reason):
"""
Skip a test unless the condition is true.
"""
if not condition:
return skip(reason)
return _id
def expectedFailure(func):
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception:
raise _ExpectedFailure(sys.exc_info())
raise _UnexpectedSuccess
wrapper = wraps(func)(wrapper)
return wrapper
class _AssertRaisesContext(object):
"""A context manager used to implement TestCase.assertRaises* methods."""
def __init__(self, expected, test_case, expected_regexp=None):
self.expected = expected
self.failureException = test_case.failureException
self.expected_regexp = expected_regexp
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except AttributeError:
exc_name = str(self.expected)
raise self.failureException(
"%s not raised" % (exc_name,))
if not issubclass(exc_type, self.expected):
# let unexpected exceptions pass through
return False
self.exception = exc_value # store for later retrieval
if self.expected_regexp is None:
return True
expected_regexp = self.expected_regexp
if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value)):
raise self.failureException('"%s" does not match "%s"' %
(expected_regexp.pattern, str(exc_value)))
return True
class _TypeEqualityDict(object):
def __init__(self, testcase):
self.testcase = testcase
self._store = {}
def __setitem__(self, key, value):
self._store[key] = value
def __getitem__(self, key):
value = self._store[key]
if isinstance(value, basestring):
return getattr(self.testcase, value)
return value
def get(self, key, default=None):
if key in self._store:
return self[key]
return default
class TestCase(unittest.TestCase):
"""A class whose instances are single test cases.
By default, the test code itself should be placed in a method named
'runTest'.
If the fixture may be used for many test cases, create as
many test methods as are needed. When instantiating such a TestCase
subclass, specify in the constructor arguments the name of the test method
that the instance is to execute.
Test authors should subclass TestCase for their own tests. Construction
and deconstruction of the test's environment ('fixture') can be
implemented by overriding the 'setUp' and 'tearDown' methods respectively.
If it is necessary to override the __init__ method, the base class
__init__ method must always be called. It is important that subclasses
should not change the signature of their __init__ method, since instances
of the classes are instantiated automatically by parts of the framework
in order to be run.
"""
# This attribute determines which exception will be raised when
# the instance's assertion methods fail; test methods raising this
# exception will be deemed to have 'failed' rather than 'errored'
failureException = AssertionError
# This attribute sets the maximum length of a diff in failure messages
# by assert methods using difflib. It is looked up as an instance attribute
# so can be configured by individual tests if required.
maxDiff = 80*8
# This attribute determines whether long messages (including repr of
# objects used in assert methods) will be printed on failure in *addition*
# to any explicit message passed.
longMessage = True
# Attribute used by TestSuite for classSetUp
_classSetupFailed = False
def __init__(self, methodName='runTest'):
"""Create an instance of the class that will use the named test
method when executed. Raises a ValueError if the instance does
not have a method with the specified name.
"""
self._testMethodName = methodName
self._resultForDoCleanups = None
try:
testMethod = getattr(self, methodName)
except AttributeError:
raise ValueError("no such test method in %s: %s" % \
(self.__class__, methodName))
self._testMethodDoc = testMethod.__doc__
self._cleanups = []
# Map types to custom assertEqual functions that will compare
# instances of said type in more detail to generate a more useful
# error message.
self._type_equality_funcs = _TypeEqualityDict(self)
self.addTypeEqualityFunc(dict, 'assertDictEqual')
self.addTypeEqualityFunc(list, 'assertListEqual')
self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
self.addTypeEqualityFunc(set, 'assertSetEqual')
self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
def addTypeEqualityFunc(self, typeobj, function):
"""Add a type specific assertEqual style function to compare a type.
This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.
Args:
typeobj: The data type to call this function on when both values
are of the same type in assertEqual().
function: The callable taking two arguments and an optional
msg= argument that raises self.failureException with a
useful error message when the two arguments are not equal.
"""
self._type_equality_funcs[typeobj] = function
def addCleanup(self, function, *args, **kwargs):
"""Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.
Cleanup items are called even if setUp fails (unlike tearDown)."""
self._cleanups.append((function, args, kwargs))
def setUp(self):
"Hook method for setting up the test fixture before exercising it."
def setUpClass(cls):
"Hook method for setting up class fixture before running tests in the class."
setUpClass = classmethod(setUpClass)
def tearDownClass(cls):
"Hook method for deconstructing the class fixture after running all tests in the class."
tearDownClass = classmethod(tearDownClass)
def tearDown(self):
"Hook method for deconstructing the test fixture after testing it."
def countTestCases(self):
return 1
def defaultTestResult(self):
return result.TestResult()
def shortDescription(self):
"""Returns a one-line description of the test, or None if no
description has been provided.
The default implementation of this method returns the first line of
the specified test method's docstring.
"""
doc = self._testMethodDoc
return doc and doc.split("\n")[0].strip() or None
def id(self):
return "%s.%s" % (strclass(self.__class__), self._testMethodName)
def __eq__(self, other):
if type(self) is not type(other):
return NotImplemented
return self._testMethodName == other._testMethodName
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash((type(self), self._testMethodName))
def __str__(self):
return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
def __repr__(self):
return "<%s testMethod=%s>" % \
(strclass(self.__class__), self._testMethodName)
def _addSkip(self, result, reason):
addSkip = getattr(result, 'addSkip', None)
if addSkip is not None:
addSkip(self, reason)
else:
warnings.warn("Use of a TestResult without an addSkip method is deprecated",
DeprecationWarning, 2)
result.addSuccess(self)
def run(self, result=None):
orig_result = result
if result is None:
result = self.defaultTestResult()
startTestRun = getattr(result, 'startTestRun', None)
if startTestRun is not None:
startTestRun()
self._resultForDoCleanups = result
result.startTest(self)
testMethod = getattr(self, self._testMethodName)
if (getattr(self.__class__, "__unittest_skip__", False) or
getattr(testMethod, "__unittest_skip__", False)):
# If the class or method was skipped.
try:
skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
or getattr(testMethod, '__unittest_skip_why__', ''))
self._addSkip(result, skip_why)
finally:
result.stopTest(self)
return
try:
success = False
try:
self.setUp()
except SkipTest, e:
self._addSkip(result, str(e))
except Exception:
result.addError(self, sys.exc_info())
else:
try:
testMethod()
except self.failureException:
result.addFailure(self, sys.exc_info())
except _ExpectedFailure, e:
addExpectedFailure = getattr(result, 'addExpectedFailure', None)
if addExpectedFailure is not None:
addExpectedFailure(self, e.exc_info)
else:
warnings.warn("Use of a TestResult without an addExpectedFailure method is deprecated",
DeprecationWarning)
result.addSuccess(self)
except _UnexpectedSuccess:
addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
if addUnexpectedSuccess is not None:
addUnexpectedSuccess(self)
else:
warnings.warn("Use of a TestResult without an addUnexpectedSuccess method is deprecated",
DeprecationWarning)
result.addFailure(self, sys.exc_info())
except SkipTest, e:
self._addSkip(result, str(e))
except Exception:
result.addError(self, sys.exc_info())
else:
success = True
try:
self.tearDown()
except Exception:
result.addError(self, sys.exc_info())
success = False
cleanUpSuccess = self.doCleanups()
success = success and cleanUpSuccess
if success:
result.addSuccess(self)
finally:
result.stopTest(self)
if orig_result is None:
stopTestRun = getattr(result, 'stopTestRun', None)
if stopTestRun is not None:
stopTestRun()
def doCleanups(self):
"""Execute all cleanup functions. Normally called for you after
tearDown."""
result = self._resultForDoCleanups
ok = True
while self._cleanups:
function, args, kwargs = self._cleanups.pop(-1)
try:
function(*args, **kwargs)
except Exception:
ok = False
result.addError(self, sys.exc_info())
return ok
def __call__(self, *args, **kwds):
return self.run(*args, **kwds)
def debug(self):
"""Run the test without collecting errors in a TestResult"""
self.setUp()
getattr(self, self._testMethodName)()
self.tearDown()
while self._cleanups:
function, args, kwargs = self._cleanups.pop(-1)
function(*args, **kwargs)
def skipTest(self, reason):
"""Skip this test."""
raise SkipTest(reason)
def fail(self, msg=None):
"""Fail immediately, with the given message."""
raise self.failureException(msg)
def assertFalse(self, expr, msg=None):
"Fail the test if the expression is true."
if expr:
msg = self._formatMessage(msg, "%s is not False" % safe_repr(expr))
raise self.failureException(msg)
def assertTrue(self, expr, msg=None):
"""Fail the test unless the expression is true."""
if not expr:
msg = self._formatMessage(msg, "%s is not True" % safe_repr(expr))
raise self.failureException(msg)
def _formatMessage(self, msg, standardMsg):
"""Honour the longMessage attribute when generating failure messages.
If longMessage is False this means:
* Use only an explicit message if it is provided
* Otherwise use the standard message for the assert
If longMessage is True:
* Use the standard message
* If an explicit message is provided, plus ' : ' and the explicit message
"""
if not self.longMessage:
return msg or standardMsg
if msg is None:
return standardMsg
try:
return '%s : %s' % (standardMsg, msg)
except UnicodeDecodeError:
return '%s : %s' % (safe_str(standardMsg), safe_str(msg))
def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
"""Fail unless an exception of class excClass is thrown
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with callableObj omitted or None, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
"""
if callableObj is None:
return _AssertRaisesContext(excClass, self)
try:
callableObj(*args, **kwargs)
except excClass:
return
if hasattr(excClass,'__name__'):
excName = excClass.__name__
else:
excName = str(excClass)
raise self.failureException, "%s not raised" % excName
def _getAssertEqualityFunc(self, first, second):
"""Get a detailed comparison function for the types of the two args.
Returns: A callable accepting (first, second, msg=None) that will
raise a failure exception if first != second with a useful human
readable error message for those types.
"""
#
# NOTE(gregory.p.smith): I considered isinstance(first, type(second))
# and vice versa. I opted for the conservative approach in case
# subclasses are not intended to be compared in detail to their super
# class instances using a type equality func. This means testing
# subtypes won't automagically use the detailed comparison. Callers
# should use their type specific assertSpamEqual method to compare
# subclasses if the detailed comparison is desired and appropriate.
# See the discussion in http://bugs.python.org/issue2578.
#
if type(first) is type(second):
asserter = self._type_equality_funcs.get(type(first))
if asserter is not None:
return asserter
return self._baseAssertEqual
def _baseAssertEqual(self, first, second, msg=None):
"""The default assertEqual implementation, not type specific."""
if not first == second:
standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
def assertEqual(self, first, second, msg=None):
"""Fail if the two objects are unequal as determined by the '=='
operator.
"""
assertion_func = self._getAssertEqualityFunc(first, second)
assertion_func(first, second, msg=msg)
def assertNotEqual(self, first, second, msg=None):
"""Fail if the two objects are equal as determined by the '=='
operator.
"""
if not first != second:
msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
safe_repr(second)))
raise self.failureException(msg)
def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
"""Fail if the two objects are unequal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
between the two objects is more than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
If the two objects compare equal then they will automatically
compare almost equal.
"""
if first == second:
# shortcut
return
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
if delta is not None:
if abs(first - second) <= delta:
return
standardMsg = '%s != %s within %s delta' % (safe_repr(first),
safe_repr(second),
safe_repr(delta))
else:
if places is None:
places = 7
if round(abs(second-first), places) == 0:
return
standardMsg = '%s != %s within %r places' % (safe_repr(first),
safe_repr(second),
places)
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
"""Fail if the two objects are equal as determined by their
difference rounded to the given number of decimal places
(default 7) and comparing to zero, or by comparing that the
between the two objects is less than the given delta.
Note that decimal places (from zero) are usually not the same
as significant digits (measured from the most signficant digit).
Objects that are equal automatically fail.
"""
if delta is not None and places is not None:
raise TypeError("specify delta or places not both")
if delta is not None:
if not (first == second) and abs(first - second) > delta:
return
standardMsg = '%s == %s within %s delta' % (safe_repr(first),
safe_repr(second),
safe_repr(delta))
else:
if places is None:
places = 7
if not (first == second) and round(abs(second-first), places) != 0:
return
standardMsg = '%s == %s within %r places' % (safe_repr(first),
safe_repr(second),
places)
msg = self._formatMessage(msg, standardMsg)
raise self.failureException(msg)
# Synonyms for assertion methods
# The plurals are undocumented. Keep them that way to discourage use.
# Do not add more. Do not remove.
# Going through a deprecation cycle on these would annoy many people.
assertEquals = assertEqual
assertNotEquals = assertNotEqual
assertAlmostEquals = assertAlmostEqual
assertNotAlmostEquals = assertNotAlmostEqual
assert_ = assertTrue
# These fail* assertion method names are pending deprecation and will
# be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
def _deprecate(original_func):
def deprecated_func(*args, **kwargs):
warnings.warn(
('Please use %s instead.' % original_func.__name__),
PendingDeprecationWarning, 2)
return original_func(*args, **kwargs)
return deprecated_func
failUnlessEqual = _deprecate(assertEqual)
failIfEqual = _deprecate(assertNotEqual)
failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
failUnless = _deprecate(assertTrue)
failUnlessRaises = _deprecate(assertRaises)
failIf = _deprecate(assertFalse)
def assertSequenceEqual(self, seq1, seq2,
msg=None, seq_type=None, max_diff=80*8):
"""An equality assertion for ordered sequences (like lists and tuples).
For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.
Args:
seq1: The first sequence to compare.
seq2: The second sequence to compare.
seq_type: The expected datatype of the sequences, or None if no
datatype should be enforced.
msg: Optional message to use on failure instead of a list of
differences.
max_diff: Maximum size off the diff, larger diffs are not shown
"""
if seq_type is not None:
seq_type_name = seq_type.__name__
if not isinstance(seq1, seq_type):
raise self.failureException('First sequence is not a %s: %s'
% (seq_type_name, safe_repr(seq1)))
if not isinstance(seq2, seq_type):
raise self.failureException('Second sequence is not a %s: %s'
% (seq_type_name, safe_repr(seq2)))
else:
seq_type_name = "sequence"
differing = None
try:
len1 = len(seq1)
except (TypeError, NotImplementedError):
differing = 'First %s has no length. Non-sequence?' % (
seq_type_name)
if differing is None:
try:
len2 = len(seq2)
except (TypeError, NotImplementedError):
differing = 'Second %s has no length. Non-sequence?' % (
seq_type_name)
if differing is None:
if seq1 == seq2:
return
seq1_repr = repr(seq1)
seq2_repr = repr(seq2)
if len(seq1_repr) > 30:
seq1_repr = seq1_repr[:30] + '...'
if len(seq2_repr) > 30:
seq2_repr = seq2_repr[:30] + '...'
elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
differing = '%ss differ: %s != %s\n' % elements
for i in xrange(min(len1, len2)):
try:
item1 = seq1[i]
except (TypeError, IndexError, NotImplementedError):
differing += ('\nUnable to index element %d of first %s\n' %
(i, seq_type_name))
break
try:
item2 = seq2[i]
except (TypeError, IndexError, NotImplementedError):
differing += ('\nUnable to index element %d of second %s\n' %
(i, seq_type_name))
break
if item1 != item2:
differing += ('\nFirst differing element %d:\n%s\n%s\n' %
(i, item1, item2))
break
else:
if (len1 == len2 and seq_type is None and
type(seq1) != type(seq2)):
# The sequences are the same, but have differing types.
return
if len1 > len2:
differing += ('\nFirst %s contains %d additional '
'elements.\n' % (seq_type_name, len1 - len2))
try:
differing += ('First extra element %d:\n%s\n' %
(len2, seq1[len2]))
except (TypeError, IndexError, NotImplementedError):
differing += ('Unable to index element %d '
'of first %s\n' % (len2, seq_type_name))
elif len1 < len2:
differing += ('\nSecond %s contains %d additional '
'elements.\n' % (seq_type_name, len2 - len1))
try:
differing += ('First extra element %d:\n%s\n' %
(len1, seq2[len1]))
except (TypeError, IndexError, NotImplementedError):
differing += ('Unable to index element %d '
'of second %s\n' % (len1, seq_type_name))
standardMsg = differing
diffMsg = '\n' + '\n'.join(
difflib.ndiff(pprint.pformat(seq1).splitlines(),
pprint.pformat(seq2).splitlines()))
standardMsg = self._truncateMessage(standardMsg, diffMsg)
msg = self._formatMessage(msg, standardMsg)
self.fail(msg)
def _truncateMessage(self, message, diff):
max_diff = self.maxDiff
if max_diff is None or len(diff) <= max_diff:
return message + diff
return message + (DIFF_OMITTED % len(diff))
def assertListEqual(self, list1, list2, msg=None):
"""A list-specific equality assertion.
Args:
list1: The first list to compare.
list2: The second list to compare.
msg: Optional message to use on failure instead of a list of
differences.
"""
self.assertSequenceEqual(list1, list2, msg, seq_type=list)
def assertTupleEqual(self, tuple1, tuple2, msg=None):
"""A tuple-specific equality assertion.
Args:
tuple1: The first tuple to compare.
tuple2: The second tuple to compare.
msg: Optional message to use on failure instead of a list of
differences.
"""
self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
def assertSetEqual(self, set1, set2, msg=None):
"""A set-specific equality assertion.
Args:
set1: The first set to compare.
set2: The second set to compare.
msg: Optional message to use on failure instead of a list of
differences.
assertSetEqual uses ducktyping to support
different types of sets, and is optimized for sets specifically
(parameters must support a difference method).
"""
try:
difference1 = set1.difference(set2)
except TypeError, e:
self.fail('invalid type when attempting set difference: %s' % e)
except AttributeError, e:
self.fail('first argument does not support set difference: %s' % e)
try:
difference2 = set2.difference(set1)
except TypeError, e:
self.fail('invalid type when attempting set difference: %s' % e)
except AttributeError, e:
self.fail('second argument does not support set difference: %s' % e)
if not (difference1 or difference2):
return
lines = []
if difference1:
lines.append('Items in the first set but not the second:')
for item in difference1:
lines.append(repr(item))
if difference2:
lines.append('Items in the second set but not the first:')
for item in difference2:
lines.append(repr(item))
standardMsg = '\n'.join(lines)
self.fail(self._formatMessage(msg, standardMsg))
def assertIn(self, member, container, msg=None):
"""Just like self.assertTrue(a in b), but with a nicer default message."""
if member not in container:
standardMsg = '%s not found in %s' % (safe_repr(member),
safe_repr(container))
self.fail(self._formatMessage(msg, standardMsg))
def assertNotIn(self, member, container, msg=None):
"""Just like self.assertTrue(a not in b), but with a nicer default message."""
if member in container:
standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
safe_repr(container))
self.fail(self._formatMessage(msg, standardMsg))
def assertIs(self, expr1, expr2, msg=None):
"""Just like self.assertTrue(a is b), but with a nicer default message."""
if expr1 is not expr2:
standardMsg = '%s is not %s' % (safe_repr(expr1), safe_repr(expr2))
self.fail(self._formatMessage(msg, standardMsg))
def assertIsNot(self, expr1, expr2, msg=None):
"""Just like self.assertTrue(a is not b), but with a nicer default message."""
if expr1 is expr2:
standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
self.fail(self._formatMessage(msg, standardMsg))
def assertDictEqual(self, d1, d2, msg=None):
self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
if d1 != d2:
standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
diff = ('\n' + '\n'.join(difflib.ndiff(
pprint.pformat(d1).splitlines(),
pprint.pformat(d2).splitlines())))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
def assertDictContainsSubset(self, expected, actual, msg=None):
"""Checks whether actual is a superset of expected."""
missing = []
mismatched = []
for key, value in expected.iteritems():
if key not in actual:
missing.append(key)
else:
try:
are_equal = (value == actual[key])
except UnicodeDecodeError:
are_equal = False
if not are_equal:
mismatched.append('%s, expected: %s, actual: %s' %
(safe_repr(key), safe_repr(value),
safe_repr(actual[key])))
if not (missing or mismatched):
return
standardMsg = ''
if missing:
standardMsg = 'Missing: %s' % ','.join([safe_repr(m) for m in
missing])
if mismatched:
if standardMsg:
standardMsg += '; '
standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
self.fail(self._formatMessage(msg, standardMsg))
def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
"""An unordered sequence specific comparison. It asserts that
expected_seq and actual_seq contain the same elements. It is
the equivalent of::
self.assertEqual(sorted(expected_seq), sorted(actual_seq))
Raises with an error message listing which elements of expected_seq
are missing from actual_seq and vice versa if any.
Asserts that each element has the same count in both sequences.
Example:
- [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
"""
try:
expected = expected_seq[:]
expected.sort()
actual = actual_seq[:]
actual.sort()
except TypeError:
# Unsortable items (example: set(), complex(), ...)
expected = list(expected_seq)
actual = list(actual_seq)
missing, unexpected = unorderable_list_difference(
expected, actual, ignore_duplicate=False
)
else:
return self.assertSequenceEqual(expected, actual, msg=msg)
errors = []
if missing:
errors.append('Expected, but missing:\n %s' %
safe_repr(missing))
if unexpected:
errors.append('Unexpected, but present:\n %s' %
safe_repr(unexpected))
if errors:
standardMsg = '\n'.join(errors)
self.fail(self._formatMessage(msg, standardMsg))
def assertMultiLineEqual(self, first, second, msg=None):
"""Assert that two multi-line strings are equal."""
self.assert_(isinstance(first, basestring), (
'First argument is not a string'))
self.assert_(isinstance(second, basestring), (
'Second argument is not a string'))
if first != second:
standardMsg = '%s != %s' % (safe_repr(first, True), safe_repr(second, True))
diff = '\n' + ''.join(difflib.ndiff(first.splitlines(True),
second.splitlines(True)))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
def assertLess(self, a, b, msg=None):
"""Just like self.assertTrue(a < b), but with a nicer default message."""
if not a < b:
standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
def assertLessEqual(self, a, b, msg=None):
"""Just like self.assertTrue(a <= b), but with a nicer default message."""
if not a <= b:
standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
def assertGreater(self, a, b, msg=None):
"""Just like self.assertTrue(a > b), but with a nicer default message."""
if not a > b:
standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
def assertGreaterEqual(self, a, b, msg=None):
"""Just like self.assertTrue(a >= b), but with a nicer default message."""
if not a >= b:
standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
self.fail(self._formatMessage(msg, standardMsg))
def assertIsNone(self, obj, msg=None):
"""Same as self.assertTrue(obj is None), with a nicer default message."""
if obj is not None:
standardMsg = '%s is not None' % (safe_repr(obj),)
self.fail(self._formatMessage(msg, standardMsg))
def assertIsNotNone(self, obj, msg=None):
"""Included for symmetry with assertIsNone."""
if obj is None:
standardMsg = 'unexpectedly None'
self.fail(self._formatMessage(msg, standardMsg))
def assertIsInstance(self, obj, cls, msg=None):
"""Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message."""
if not isinstance(obj, cls):
standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
self.fail(self._formatMessage(msg, standardMsg))
def assertNotIsInstance(self, obj, cls, msg=None):
"""Included for symmetry with assertIsInstance."""
if isinstance(obj, cls):
standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
self.fail(self._formatMessage(msg, standardMsg))
def assertRaisesRegexp(self, expected_exception, expected_regexp,
callable_obj=None, *args, **kwargs):
"""Asserts that the message in a raised exception matches a regexp.
Args:
expected_exception: Exception class expected to be raised.
expected_regexp: Regexp (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.
"""
if callable_obj is None:
return _AssertRaisesContext(expected_exception, self, expected_regexp)
try:
callable_obj(*args, **kwargs)
except expected_exception, exc_value:
if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value)):
raise self.failureException('"%s" does not match "%s"' %
(expected_regexp.pattern, str(exc_value)))
else:
if hasattr(expected_exception, '__name__'):
excName = expected_exception.__name__
else:
excName = str(expected_exception)
raise self.failureException, "%s not raised" % excName
def assertRegexpMatches(self, text, expected_regexp, msg=None):
"""Fail the test unless the text matches the regular expression."""
if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(text):
msg = msg or "Regexp didn't match"
msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
raise self.failureException(msg)
def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
"""Fail the test if the text matches the regular expression."""
if isinstance(unexpected_regexp, basestring):
unexpected_regexp = re.compile(unexpected_regexp)
match = unexpected_regexp.search(text)
if match:
msg = msg or "Regexp matched"
msg = '%s: %r matches %r in %r' % (msg,
text[match.start():match.end()],
unexpected_regexp.pattern,
text)
raise self.failureException(msg)
class FunctionTestCase(TestCase):
"""A test case that wraps a test function.
This is useful for slipping pre-existing test functions into the
unittest framework. Optionally, set-up and tidy-up functions can be
supplied. As with TestCase, the tidy-up ('tearDown') function will
always be called if the set-up ('setUp') function ran successfully.
"""
def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
super(FunctionTestCase, self).__init__()
self._setUpFunc = setUp
self._tearDownFunc = tearDown
self._testFunc = testFunc
self._description = description
def setUp(self):
if self._setUpFunc is not None:
self._setUpFunc()
def tearDown(self):
if self._tearDownFunc is not None:
self._tearDownFunc()
def runTest(self):
self._testFunc()
def id(self):
return self._testFunc.__name__
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self._setUpFunc == other._setUpFunc and \
self._tearDownFunc == other._tearDownFunc and \
self._testFunc == other._testFunc and \
self._description == other._description
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash((type(self), self._setUpFunc, self._tearDownFunc,
self._testFunc, self._description))
def __str__(self):
return "%s (%s)" % (strclass(self.__class__),
self._testFunc.__name__)
def __repr__(self):
return "<%s testFunc=%s>" % (strclass(self.__class__),
self._testFunc)
def shortDescription(self):
if self._description is not None:
return self._description
doc = self._testFunc.__doc__
return doc and doc.split("\n")[0].strip() or None
| Python |
"""Various utility functions."""
__unittest = True
_MAX_LENGTH = 80
def safe_repr(obj, short=False):
try:
result = repr(obj)
except Exception:
result = object.__repr__(obj)
if not short or len(result) < _MAX_LENGTH:
return result
return result[:_MAX_LENGTH] + ' [truncated]...'
def safe_str(obj):
try:
return str(obj)
except Exception:
return object.__str__(obj)
def strclass(cls):
return "%s.%s" % (cls.__module__, cls.__name__)
def sorted_list_difference(expected, actual):
"""Finds elements in only one or the other of two, sorted input lists.
Returns a two-element tuple of lists. The first list contains those
elements in the "expected" list but not in the "actual" list, and the
second contains those elements in the "actual" list but not in the
"expected" list. Duplicate elements in either input list are ignored.
"""
i = j = 0
missing = []
unexpected = []
while True:
try:
e = expected[i]
a = actual[j]
if e < a:
missing.append(e)
i += 1
while expected[i] == e:
i += 1
elif e > a:
unexpected.append(a)
j += 1
while actual[j] == a:
j += 1
else:
i += 1
try:
while expected[i] == e:
i += 1
finally:
j += 1
while actual[j] == a:
j += 1
except IndexError:
missing.extend(expected[i:])
unexpected.extend(actual[j:])
break
return missing, unexpected
def unorderable_list_difference(expected, actual, ignore_duplicate=False):
"""Same behavior as sorted_list_difference but
for lists of unorderable items (like dicts).
As it does a linear search per item (remove) it
has O(n*n) performance.
"""
missing = []
unexpected = []
while expected:
item = expected.pop()
try:
actual.remove(item)
except ValueError:
missing.append(item)
if ignore_duplicate:
for lst in expected, actual:
try:
while True:
lst.remove(item)
except ValueError:
pass
if ignore_duplicate:
while actual:
item = actual.pop()
unexpected.append(item)
try:
while True:
actual.remove(item)
except ValueError:
pass
return missing, unexpected
# anything left in actual is unexpected
return missing, actual
| Python |
"""
unittest2
unittest2 is a backport of the new features added to the unittest testing
framework in Python 2.7. It is tested to run on Python 2.4 - 2.6.
To use unittest2 instead of unittest simply replace ``import unittest`` with
``import unittest2``.
Copyright (c) 1999-2003 Steve Purcell
Copyright (c) 2003-2010 Python Software Foundation
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.
IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""
__all__ = ['TestResult', 'TestCase', 'TestSuite',
'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
'expectedFailure', 'TextTestResult', '__version__', 'collector']
__version__ = '0.5.1'
# Expose obsolete functions for backwards compatibility
__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
from unittest2.collector import collector
from unittest2.result import TestResult
from unittest2.case import \
TestCase, FunctionTestCase, SkipTest, skip, skipIf,\
skipUnless, expectedFailure
from unittest2.suite import BaseTestSuite, TestSuite
from unittest2.loader import \
TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,\
findTestCases
from unittest2.main import TestProgram, main, main_
from unittest2.runner import TextTestRunner, TextTestResult
try:
from unittest2.signals import\
installHandler, registerResult, removeResult, removeHandler
except ImportError:
# Compatibility with platforms that don't have the signal module
pass
else:
__all__.extend(['installHandler', 'registerResult', 'removeResult',
'removeHandler'])
# deprecated
_TextTestResult = TextTestResult
__unittest = True
| Python |
"""Main entry point"""
import sys
if sys.argv[0].endswith("__main__.py"):
sys.argv[0] = "unittest2"
__unittest = True
from unittest2.main import main_
main_()
| Python |
"""Loading unittests."""
import os
import re
import sys
import traceback
import types
import unittest
from fnmatch import fnmatch
from unittest2 import case, suite
try:
from os.path import relpath
except ImportError:
from unittest2.compatibility import relpath
__unittest = True
def _CmpToKey(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) == -1
return K
# what about .pyc or .pyo (etc)
# we would need to avoid loading the same tests multiple times
# from '.py', '.pyc' *and* '.pyo'
VALID_MODULE_NAME = re.compile(r'[_a-z]\w*\.py$', re.IGNORECASE)
def _make_failed_import_test(name, suiteClass):
message = 'Failed to import test module: %s' % name
if hasattr(traceback, 'format_exc'):
# Python 2.3 compatibility
# format_exc returns two frames of discover.py as well
message += '\n%s' % traceback.format_exc()
return _make_failed_test('ModuleImportFailure', name, ImportError(message),
suiteClass)
def _make_failed_load_tests(name, exception, suiteClass):
return _make_failed_test('LoadTestsFailure', name, exception, suiteClass)
def _make_failed_test(classname, methodname, exception, suiteClass):
def testFailure(self):
raise exception
attrs = {methodname: testFailure}
TestClass = type(classname, (case.TestCase,), attrs)
return suiteClass((TestClass(methodname),))
class TestLoader(unittest.TestLoader):
"""
This class is responsible for loading tests according to various criteria
and returning them wrapped in a TestSuite
"""
testMethodPrefix = 'test'
sortTestMethodsUsing = cmp
suiteClass = suite.TestSuite
_top_level_dir = None
def loadTestsFromTestCase(self, testCaseClass):
"""Return a suite of all tests cases contained in testCaseClass"""
if issubclass(testCaseClass, suite.TestSuite):
raise TypeError("Test cases should not be derived from TestSuite."
" Maybe you meant to derive from TestCase?")
testCaseNames = self.getTestCaseNames(testCaseClass)
if not testCaseNames and hasattr(testCaseClass, 'runTest'):
testCaseNames = ['runTest']
loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
return loaded_suite
def loadTestsFromModule(self, module, use_load_tests=True):
"""Return a suite of all tests cases contained in the given module"""
tests = []
for name in dir(module):
obj = getattr(module, name)
if isinstance(obj, type) and issubclass(obj, unittest.TestCase):
tests.append(self.loadTestsFromTestCase(obj))
load_tests = getattr(module, 'load_tests', None)
tests = self.suiteClass(tests)
if use_load_tests and load_tests is not None:
try:
return load_tests(self, tests, None)
except Exception, e:
return _make_failed_load_tests(module.__name__, e,
self.suiteClass)
return tests
def loadTestsFromName(self, name, module=None):
"""Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.
"""
parts = name.split('.')
if module is None:
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
parent, obj = obj, getattr(obj, part)
if isinstance(obj, types.ModuleType):
return self.loadTestsFromModule(obj)
elif isinstance(obj, type) and issubclass(obj, unittest.TestCase):
return self.loadTestsFromTestCase(obj)
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, case.TestCase)):
return self.suiteClass([parent(obj.__name__)])
elif isinstance(obj, unittest.TestSuite):
return obj
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, unittest.TestSuite):
return test
elif isinstance(test, unittest.TestCase):
return self.suiteClass([test])
else:
raise TypeError("calling %s returned %s, not a test" %
(obj, test))
else:
raise TypeError("don't know how to make test from: %s" % obj)
def loadTestsFromNames(self, names, module=None):
"""Return a suite of all tests cases found using the given sequence
of string specifiers. See 'loadTestsFromName()'.
"""
suites = [self.loadTestsFromName(name, module) for name in names]
return self.suiteClass(suites)
def getTestCaseNames(self, testCaseClass):
"""Return a sorted sequence of method names found within testCaseClass
"""
def isTestMethod(attrname, testCaseClass=testCaseClass,
prefix=self.testMethodPrefix):
return attrname.startswith(prefix) and \
hasattr(getattr(testCaseClass, attrname), '__call__')
testFnNames = filter(isTestMethod, dir(testCaseClass))
if self.sortTestMethodsUsing:
# testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
testFnNames.sort(self.sortTestMethodsUsing)
return testFnNames
def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
"""Find and return all test modules from the specified start
directory, recursing into subdirectories to find them. Only test files
that match the pattern will be loaded. (Using shell style pattern
matching.)
All test modules must be importable from the top level of the project.
If the start directory is not the top level directory then the top
level directory must be specified separately.
If a test package name (directory with '__init__.py') matches the
pattern then the package will be checked for a 'load_tests' function. If
this exists then it will be called with loader, tests, pattern.
If load_tests exists then discovery does *not* recurse into the package,
load_tests is responsible for loading all tests in the package.
The pattern is deliberately not stored as a loader attribute so that
packages can continue discovery themselves. top_level_dir is stored so
load_tests does not need to pass this argument in to loader.discover().
"""
set_implicit_top = False
if top_level_dir is None and self._top_level_dir is not None:
# make top_level_dir optional if called from load_tests in a package
top_level_dir = self._top_level_dir
elif top_level_dir is None:
set_implicit_top = True
top_level_dir = start_dir
top_level_dir = os.path.abspath(top_level_dir)
if not top_level_dir in sys.path:
# all test modules must be importable from the top level directory
# should we *unconditionally* put the start directory in first
# in sys.path to minimise likelihood of conflicts between installed
# modules and development versions?
sys.path.insert(0, top_level_dir)
self._top_level_dir = top_level_dir
is_not_importable = False
if os.path.isdir(os.path.abspath(start_dir)):
start_dir = os.path.abspath(start_dir)
if start_dir != top_level_dir:
is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))
else:
# support for discovery from dotted module names
try:
__import__(start_dir)
except ImportError:
is_not_importable = True
else:
the_module = sys.modules[start_dir]
top_part = start_dir.split('.')[0]
start_dir = os.path.abspath(os.path.dirname((the_module.__file__)))
if set_implicit_top:
self._top_level_dir = os.path.abspath(os.path.dirname(os.path.dirname(sys.modules[top_part].__file__)))
sys.path.remove(top_level_dir)
if is_not_importable:
raise ImportError('Start directory is not importable: %r' % start_dir)
tests = list(self._find_tests(start_dir, pattern))
return self.suiteClass(tests)
def _get_name_from_path(self, path):
path = os.path.splitext(os.path.normpath(path))[0]
_relpath = relpath(path, self._top_level_dir)
assert not os.path.isabs(_relpath), "Path must be within the project"
assert not _relpath.startswith('..'), "Path must be within the project"
name = _relpath.replace(os.path.sep, '.')
return name
def _get_module_from_name(self, name):
__import__(name)
return sys.modules[name]
def _match_path(self, path, full_path, pattern):
# override this method to use alternative matching strategy
return fnmatch(path, pattern)
def _find_tests(self, start_dir, pattern):
"""Used by discovery. Yields test suites it loads."""
paths = os.listdir(start_dir)
for path in paths:
full_path = os.path.join(start_dir, path)
if os.path.isfile(full_path):
if not VALID_MODULE_NAME.match(path):
# valid Python identifiers only
continue
if not self._match_path(path, full_path, pattern):
continue
# if the test file matches, load it
name = self._get_name_from_path(full_path)
try:
module = self._get_module_from_name(name)
except:
yield _make_failed_import_test(name, self.suiteClass)
else:
mod_file = os.path.abspath(getattr(module, '__file__', full_path))
realpath = os.path.splitext(mod_file)[0]
fullpath_noext = os.path.splitext(full_path)[0]
if realpath.lower() != fullpath_noext.lower():
module_dir = os.path.dirname(realpath)
mod_name = os.path.splitext(os.path.basename(full_path))[0]
expected_dir = os.path.dirname(full_path)
msg = ("%r module incorrectly imported from %r. Expected %r. "
"Is this module globally installed?")
raise ImportError(msg % (mod_name, module_dir, expected_dir))
yield self.loadTestsFromModule(module)
elif os.path.isdir(full_path):
if not os.path.isfile(os.path.join(full_path, '__init__.py')):
continue
load_tests = None
tests = None
if fnmatch(path, pattern):
# only check load_tests if the package directory itself matches the filter
name = self._get_name_from_path(full_path)
package = self._get_module_from_name(name)
load_tests = getattr(package, 'load_tests', None)
tests = self.loadTestsFromModule(package, use_load_tests=False)
if load_tests is None:
if tests is not None:
# tests loaded from package file
yield tests
# recurse into the package
for test in self._find_tests(full_path, pattern):
yield test
else:
try:
yield load_tests(self, tests, pattern)
except Exception, e:
yield _make_failed_load_tests(package.__name__, e,
self.suiteClass)
defaultTestLoader = TestLoader()
def _makeLoader(prefix, sortUsing, suiteClass=None):
loader = TestLoader()
loader.sortTestMethodsUsing = sortUsing
loader.testMethodPrefix = prefix
if suiteClass:
loader.suiteClass = suiteClass
return loader
def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
def makeSuite(testCaseClass, prefix='test', sortUsing=cmp,
suiteClass=suite.TestSuite):
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
def findTestCases(module, prefix='test', sortUsing=cmp,
suiteClass=suite.TestSuite):
return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
| Python |
"""Running tests"""
import sys
import time
import unittest
from unittest2 import result
try:
from unittest2.signals import registerResult
except ImportError:
def registerResult(_):
pass
__unittest = True
class _WritelnDecorator(object):
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream
def __getattr__(self, attr):
if attr in ('stream', '__getstate__'):
raise AttributeError(attr)
return getattr(self.stream,attr)
def writeln(self, arg=None):
if arg:
self.write(arg)
self.write('\n') # text-mode streams translate to \r\n if needed
class TextTestResult(result.TestResult):
"""A test result class that can print formatted text results to a stream.
Used by TextTestRunner.
"""
separator1 = '=' * 70
separator2 = '-' * 70
def __init__(self, stream, descriptions, verbosity):
super(TextTestResult, self).__init__()
self.stream = stream
self.showAll = verbosity > 1
self.dots = verbosity == 1
self.descriptions = descriptions
def getDescription(self, test):
doc_first_line = test.shortDescription()
if self.descriptions and doc_first_line:
return '\n'.join((str(test), doc_first_line))
else:
return str(test)
def startTest(self, test):
super(TextTestResult, self).startTest(test)
if self.showAll:
self.stream.write(self.getDescription(test))
self.stream.write(" ... ")
self.stream.flush()
def addSuccess(self, test):
super(TextTestResult, self).addSuccess(test)
if self.showAll:
self.stream.writeln("ok")
elif self.dots:
self.stream.write('.')
self.stream.flush()
def addError(self, test, err):
super(TextTestResult, self).addError(test, err)
if self.showAll:
self.stream.writeln("ERROR")
elif self.dots:
self.stream.write('E')
self.stream.flush()
def addFailure(self, test, err):
super(TextTestResult, self).addFailure(test, err)
if self.showAll:
self.stream.writeln("FAIL")
elif self.dots:
self.stream.write('F')
self.stream.flush()
def addSkip(self, test, reason):
super(TextTestResult, self).addSkip(test, reason)
if self.showAll:
self.stream.writeln("skipped %r" % (reason,))
elif self.dots:
self.stream.write("s")
self.stream.flush()
def addExpectedFailure(self, test, err):
super(TextTestResult, self).addExpectedFailure(test, err)
if self.showAll:
self.stream.writeln("expected failure")
elif self.dots:
self.stream.write("x")
self.stream.flush()
def addUnexpectedSuccess(self, test):
super(TextTestResult, self).addUnexpectedSuccess(test)
if self.showAll:
self.stream.writeln("unexpected success")
elif self.dots:
self.stream.write("u")
self.stream.flush()
def printErrors(self):
if self.dots or self.showAll:
self.stream.writeln()
self.printErrorList('ERROR', self.errors)
self.printErrorList('FAIL', self.failures)
def printErrorList(self, flavour, errors):
for test, err in errors:
self.stream.writeln(self.separator1)
self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
self.stream.writeln(self.separator2)
self.stream.writeln("%s" % err)
def stopTestRun(self):
super(TextTestResult, self).stopTestRun()
self.printErrors()
class TextTestRunner(unittest.TextTestRunner):
"""A test runner class that displays results in textual form.
It prints out the names of tests as they are run, errors as they
occur, and a summary of the results at the end of the test run.
"""
resultclass = TextTestResult
def __init__(self, stream=sys.stderr, descriptions=True, verbosity=1,
failfast=False, buffer=False, resultclass=None):
self.stream = _WritelnDecorator(stream)
self.descriptions = descriptions
self.verbosity = verbosity
self.failfast = failfast
self.buffer = buffer
if resultclass is not None:
self.resultclass = resultclass
def _makeResult(self):
return self.resultclass(self.stream, self.descriptions, self.verbosity)
def run(self, test):
"Run the given test case or test suite."
result = self._makeResult()
result.failfast = self.failfast
result.buffer = self.buffer
registerResult(result)
startTime = time.time()
startTestRun = getattr(result, 'startTestRun', None)
if startTestRun is not None:
startTestRun()
try:
test(result)
finally:
stopTestRun = getattr(result, 'stopTestRun', None)
if stopTestRun is not None:
stopTestRun()
else:
result.printErrors()
stopTime = time.time()
timeTaken = stopTime - startTime
if hasattr(result, 'separator2'):
self.stream.writeln(result.separator2)
run = result.testsRun
self.stream.writeln("Ran %d test%s in %.3fs" %
(run, run != 1 and "s" or "", timeTaken))
self.stream.writeln()
expectedFails = unexpectedSuccesses = skipped = 0
try:
results = map(len, (result.expectedFailures,
result.unexpectedSuccesses,
result.skipped))
expectedFails, unexpectedSuccesses, skipped = results
except AttributeError:
pass
infos = []
if not result.wasSuccessful():
self.stream.write("FAILED")
failed, errored = map(len, (result.failures, result.errors))
if failed:
infos.append("failures=%d" % failed)
if errored:
infos.append("errors=%d" % errored)
else:
self.stream.write("OK")
if skipped:
infos.append("skipped=%d" % skipped)
if expectedFails:
infos.append("expected failures=%d" % expectedFails)
if unexpectedSuccesses:
infos.append("unexpected successes=%d" % unexpectedSuccesses)
if infos:
self.stream.writeln(" (%s)" % (", ".join(infos),))
else:
self.stream.write("\n")
return result
| Python |
import sys
import warnings
import unittest2
def resultFactory(*_):
return unittest2.TestResult()
class OldTestResult(object):
"""An object honouring TestResult before startTestRun/stopTestRun."""
def __init__(self, *_):
self.failures = []
self.errors = []
self.testsRun = 0
self.shouldStop = False
def startTest(self, test):
pass
def stopTest(self, test):
pass
def addError(self, test, err):
self.errors.append((test, err))
def addFailure(self, test, err):
self.failures.append((test, err))
def addSuccess(self, test):
pass
def wasSuccessful(self):
return True
def printErrors(self):
pass
class LoggingResult(unittest2.TestResult):
def __init__(self, log):
self._events = log
super(LoggingResult, self).__init__()
def startTest(self, test):
self._events.append('startTest')
super(LoggingResult, self).startTest(test)
def startTestRun(self):
self._events.append('startTestRun')
super(LoggingResult, self).startTestRun()
def stopTest(self, test):
self._events.append('stopTest')
super(LoggingResult, self).stopTest(test)
def stopTestRun(self):
self._events.append('stopTestRun')
super(LoggingResult, self).stopTestRun()
def addFailure(self, *args):
self._events.append('addFailure')
super(LoggingResult, self).addFailure(*args)
def addSuccess(self, *args):
self._events.append('addSuccess')
super(LoggingResult, self).addSuccess(*args)
def addError(self, *args):
self._events.append('addError')
super(LoggingResult, self).addError(*args)
def addSkip(self, *args):
self._events.append('addSkip')
super(LoggingResult, self).addSkip(*args)
def addExpectedFailure(self, *args):
self._events.append('addExpectedFailure')
super(LoggingResult, self).addExpectedFailure(*args)
def addUnexpectedSuccess(self, *args):
self._events.append('addUnexpectedSuccess')
super(LoggingResult, self).addUnexpectedSuccess(*args)
class EqualityMixin(object):
"""Used as a mixin for TestCase"""
# Check for a valid __eq__ implementation
def test_eq(self):
for obj_1, obj_2 in self.eq_pairs:
self.assertEqual(obj_1, obj_2)
self.assertEqual(obj_2, obj_1)
# Check for a valid __ne__ implementation
def test_ne(self):
for obj_1, obj_2 in self.ne_pairs:
self.assertNotEqual(obj_1, obj_2)
self.assertNotEqual(obj_2, obj_1)
class HashingMixin(object):
"""Used as a mixin for TestCase"""
# Check for a valid __hash__ implementation
def test_hash(self):
for obj_1, obj_2 in self.eq_pairs:
try:
if not hash(obj_1) == hash(obj_2):
self.fail("%r and %r do not hash equal" % (obj_1, obj_2))
except KeyboardInterrupt:
raise
except Exception, e:
self.fail("Problem hashing %r and %r: %s" % (obj_1, obj_2, e))
for obj_1, obj_2 in self.ne_pairs:
try:
if hash(obj_1) == hash(obj_2):
self.fail("%s and %s hash equal, but shouldn't" %
(obj_1, obj_2))
except KeyboardInterrupt:
raise
except Exception, e:
self.fail("Problem hashing %s and %s: %s" % (obj_1, obj_2, e))
# copied from Python 2.6
try:
from warnings import catch_warnings
except ImportError:
class catch_warnings(object):
def __init__(self, record=False, module=None):
self._record = record
self._module = sys.modules['warnings']
self._entered = False
def __repr__(self):
args = []
if self._record:
args.append("record=True")
name = type(self).__name__
return "%s(%s)" % (name, ", ".join(args))
def __enter__(self):
if self._entered:
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
self._module.filters = self._filters[:]
self._showwarning = self._module.showwarning
if self._record:
log = []
def showwarning(*args, **kwargs):
log.append(WarningMessage(*args, **kwargs))
self._module.showwarning = showwarning
return log
else:
return None
def __exit__(self, *exc_info):
if not self._entered:
raise RuntimeError("Cannot exit %r without entering first" % self)
self._module.filters = self._filters
self._module.showwarning = self._showwarning
class WarningMessage(object):
_WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
"line")
def __init__(self, message, category, filename, lineno, file=None,
line=None):
local_values = locals()
for attr in self._WARNING_DETAILS:
setattr(self, attr, local_values[attr])
self._category_name = None
if category.__name__:
self._category_name = category.__name__
| Python |
# | Python |
#
| Python |
#
# junitxml: extensions to Python unittest to get output junitxml
# Copyright (C) 2009 Robert Collins <robertc@robertcollins.net>
#
# Copying permitted under the LGPL-3 licence, included with this library.
import unittest as unittest2
from junitxml.tests import (
test_junitxml,
)
def test_suite():
return unittest.TestLoader().loadTestsFromNames([
'junitxml.tests.test_junitxml',
])
| Python |
#
# junitxml: extensions to Python unittest to get output junitxml
# Copyright (C) 2009 Robert Collins <robertc@robertcollins.net>
#
# Copying permitted under the LGPL-3 licence, included with this library.
"""unittest compatible JUnit XML output."""
import datetime
import re
import time
import unittest2 as unittest
# same format as sys.version_info: "A tuple containing the five components of
# the version number: major, minor, micro, releaselevel, and serial. All
# values except releaselevel are integers; the release level is 'alpha',
# 'beta', 'candidate', or 'final'. The version_info value corresponding to the
# Python version 2.0 is (2, 0, 0, 'final', 0)." Additionally we use a
# releaselevel of 'dev' for unreleased under-development code.
#
# If the releaselevel is 'alpha' then the major/minor/micro components are not
# established at this point, and setup.py will use a version of next-$(revno).
# If the releaselevel is 'final', then the tarball will be major.minor.micro.
# Otherwise it is major.minor.micro~$(revno).
__version__ = (0, 6, 0, 'final', 0)
def test_suite():
import junitxml.tests
return junitxml.tests.test_suite()
class LocalTimezone(datetime.tzinfo):
def __init__(self):
self._offset = None
# It seems that the minimal possible implementation is to just return all
# None for every function, but then it breaks...
def utcoffset(self, dt):
if self._offset is None:
t = 1260423030 # arbitrary, but doesn't handle dst very well
dt = datetime.datetime
self._offset = (dt.fromtimestamp(t) - dt.utcfromtimestamp(t))
return self._offset
def dst(self, dt):
return datetime.timedelta(0)
def tzname(self, dt):
return None
def _error_name(eclass):
module = eclass.__module__
if module not in ("__main__", "builtins", "exceptions"):
return ".".join([module, eclass.__name__])
return eclass.__name__
_non_cdata = "[\0-\b\x0B-\x1F\uD800-\uDFFF\uFFFE\uFFFF]+"
if "\\u" in _non_cdata:
_non_cdata = _non_cdata.decode("unicode-escape")
def _strip_invalid_chars(s, _sub=re.compile(_non_cdata, re.UNICODE).sub):
if not isinstance(s, unicode):
try:
s = s.decode("utf-8")
except UnicodeDecodeError:
s = s.decode("ascii", "replace")
return _sub("", s).encode("utf-8")
else:
def _strip_invalid_chars(s, _sub=re.compile(_non_cdata, re.UNICODE).sub):
return _sub("", s)
def _escape_content(s):
return (_strip_invalid_chars(s)
.replace("&", "&")
.replace("<", "<")
.replace("]]>", "]]>"))
def _escape_attr(s):
return (_strip_invalid_chars(s)
.replace("&", "&")
.replace("<", "<")
.replace("]]>", "]]>")
.replace('"', """)
.replace("\t", "	")
.replace("\n", "
"))
class JUnitXmlResult(unittest.TestResult):
"""A TestResult which outputs JUnit compatible XML."""
def __init__(self, stream):
"""Create a JUnitXmlResult.
:param stream: A stream to write results to. Note that due to the
nature of JUnit XML output, nnothing will be written to the stream
until stopTestRun() is called.
"""
self.__super = super(JUnitXmlResult, self)
self.__super.__init__()
# GZ 2010-09-03: We have a problem if passed a text stream in Python 3
# as really we want to write raw UTF-8 to ensure that
# the encoding is not mangled later
self._stream = stream
self._results = []
self._set_time = None
self._test_start = None
self._run_start = None
self._tz_info = None
def startTestRun(self):
"""Start a test run."""
self._run_start = self._now()
def _get_tzinfo(self):
if self._tz_info is None:
self._tz_info = LocalTimezone()
return self._tz_info
def _now(self):
if self._set_time is not None:
return self._set_time
else:
return datetime.datetime.now(self._get_tzinfo())
def time(self, a_datetime):
self._set_time = a_datetime
if (self._run_start is not None and
self._run_start > a_datetime):
self._run_start = a_datetime
def startTest(self, test):
self.__super.startTest(test)
self._test_start = self._now()
def _duration(self, from_datetime):
try:
delta = self._now() - from_datetime
except TypeError:
n = self._now()
delta = datetime.timedelta(-1)
seconds = delta.days * 3600*24 + delta.seconds
return seconds + 0.000001 * delta.microseconds
def _test_case_string(self, test):
duration = self._duration(self._test_start)
test_id = test.id()
# Split on the last dot not inside a parameter
class_end = test_id.rfind(".", 0, test_id.find("("))
if class_end == -1:
classname, name = "", test_id
else:
classname, name = test_id[:class_end], test_id[class_end+1:]
self._results.append('<testcase classname="%s" name="%s" '
'time="%0.3f"' % (_escape_attr(classname), _escape_attr(name), duration))
def stopTestRun(self):
"""Stop a test run.
This allows JUnitXmlResult to output the XML representation of the test
run.
"""
duration = self._duration(self._run_start)
self._stream.write('<testsuite errors="%d" failures="%d" name="" '
'skips="%d" tests="%d" time="%0.3f">\n' % (len(self.errors),
len(self.failures) + len(getattr(self, "unexpectedSuccesses", ())),
len(self.skipped), self.testsRun, duration))
self._stream.write(''.join(self._results))
self._stream.write('</testsuite>\n')
def addError(self, test, error):
self.__super.addError(test, error)
self._test_case_string(test)
self._results.append('>\n')
self._results.append('<error type="%s">%s</error>\n</testcase>\n' % (
_escape_attr(_error_name(error[0])),
_escape_content(self._exc_info_to_string(error, test))))
def addFailure(self, test, error):
self.__super.addFailure(test, error)
self._test_case_string(test)
self._results.append('>\n')
self._results.append('<failure type="%s">%s</failure>\n</testcase>\n' %
(_escape_attr(_error_name(error[0])),
_escape_content(self._exc_info_to_string(error, test))))
def addSuccess(self, test):
self.__super.addSuccess(test)
self._test_case_string(test)
self._results.append('/>\n')
def addSkip(self, test, reason):
try:
self.__super.addSkip(test, reason)
except AttributeError:
# Python < 2.7|3.1
pass
self._test_case_string(test)
self._results.append('>\n')
self._results.append('<skipped message="%s"></skipped>\n</testcase>\n'% _escape_attr(reason))
def addUnexpectedSuccess(self, test):
try:
self.__super.addUnexpectedSuccess(test)
except AttributeError:
# Python < 2.7|3.1
pass
self._test_case_string(test)
self._results.append('>\n')
self._results.append('<failure type="unittest.case._UnexpectedSuccess"/>\n</testcase>\n')
def addExpectedFailure(self, test, error):
try:
self.__super.addExpectedFailure(test, error)
except AttributeError:
# Python < 2.7|3.1
pass
self._test_case_string(test)
self._results.append('/>\n')
| Python |
#!/usr/bin/env python
import os
import sys
from macholib.MachOStandalone import MachOStandalone
from macholib.util import strip_files
def standaloneApp(path):
if not os.path.isdir(path) and os.path.exists(
os.path.join(path, 'Contents')):
raise SystemExit('%s: %s does not look like an app bundle'
% (sys.argv[0], path))
files = MachOStandalone(path).run()
strip_files(files)
def main():
if not sys.argv[1:]:
raise SystemExit, 'usage: %s [appbundle ...]' % (sys.argv[0],)
for fn in sys.argv[1:]:
standaloneApp(fn)
if __name__ == '__main__':
main()
| Python |
"""
Utilities for reading and writing Mach-O headers
"""
from __future__ import print_function
import sys
import struct
from macholib.mach_o import *
from macholib.dyld import dyld_find, framework_info
from macholib.util import fileview
try:
from macholib.compat import bytes
except ImportError:
pass
try:
unicode
except NameError:
unicode = str
__all__ = ['MachO']
_RELOCATABLE = set((
# relocatable commands that should be used for dependency walking
LC_LOAD_DYLIB,
LC_LOAD_WEAK_DYLIB,
LC_PREBOUND_DYLIB,
LC_REEXPORT_DYLIB,
))
_RELOCATABLE_NAMES = {
LC_LOAD_DYLIB: 'load_dylib',
LC_LOAD_WEAK_DYLIB: 'load_weak_dylib',
LC_PREBOUND_DYLIB: 'prebound_dylib',
LC_REEXPORT_DYLIB: 'reexport_dylib',
}
def _shouldRelocateCommand(cmd):
"""
Should this command id be investigated for relocation?
"""
return cmd in _RELOCATABLE
class MachO(object):
"""
Provides reading/writing the Mach-O header of a specific existing file
"""
# filename - the original filename of this mach-o
# sizediff - the current deviation from the initial mach-o size
# header - the mach-o header
# commands - a list of (load_command, somecommand, data)
# data is either a str, or a list of segment structures
# total_size - the current mach-o header size (including header)
# low_offset - essentially, the maximum mach-o header size
# id_cmd - the index of my id command, or None
def __init__(self, filename):
# supports the ObjectGraph protocol
self.graphident = filename
self.filename = filename
# initialized by load
self.fat = None
self.headers = []
with open(filename, 'rb') as fp:
self.load(fp)
def __repr__(self):
return "<MachO filename=%r>" % (self.filename,)
def load(self, fh):
assert fh.tell() == 0
header = struct.unpack('>I', fh.read(4))[0]
fh.seek(0)
if header == FAT_MAGIC:
self.load_fat(fh)
else:
fh.seek(0, 2)
size = fh.tell()
fh.seek(0)
self.load_header(fh, 0, size)
def load_fat(self, fh):
self.fat = fat_header.from_fileobj(fh)
archs = [fat_arch.from_fileobj(fh) for i in range(self.fat.nfat_arch)]
for arch in archs:
self.load_header(fh, arch.offset, arch.size)
def rewriteLoadCommands(self, *args, **kw):
changed = False
for header in self.headers:
if header.rewriteLoadCommands(*args, **kw):
changed = True
return changed
def load_header(self, fh, offset, size):
fh.seek(offset)
header = struct.unpack('>I', fh.read(4))[0]
fh.seek(offset)
if header == MH_MAGIC:
magic, hdr, endian = MH_MAGIC, mach_header, '>'
elif header == MH_CIGAM:
magic, hdr, endian = MH_MAGIC, mach_header, '<'
elif header == MH_MAGIC_64:
magic, hdr, endian = MH_MAGIC_64, mach_header_64, '>'
elif header == MH_CIGAM_64:
magic, hdr, endian = MH_MAGIC_64, mach_header_64, '<'
else:
raise ValueError("Unknown Mach-O header: 0x%08x in %r" % (
header, fh))
hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian)
self.headers.append(hdr)
def write(self, f):
for header in self.headers:
header.write(f)
class MachOHeader(object):
"""
Provides reading/writing the Mach-O header of a specific existing file
"""
# filename - the original filename of this mach-o
# sizediff - the current deviation from the initial mach-o size
# header - the mach-o header
# commands - a list of (load_command, somecommand, data)
# data is either a str, or a list of segment structures
# total_size - the current mach-o header size (including header)
# low_offset - essentially, the maximum mach-o header size
# id_cmd - the index of my id command, or None
def __init__(self, parent, fh, offset, size, magic, hdr, endian):
self.MH_MAGIC = magic
self.mach_header = hdr
# These are all initialized by self.load()
self.parent = parent
self.offset = offset
self.size = size
self.endian = endian
self.header = None
self.commands = None
self.id_cmd = None
self.sizediff = None
self.total_size = None
self.low_offset = None
self.filetype = None
self.headers = []
self.load(fh)
def __repr__(self):
return "<%s filename=%r offset=%d size=%d endian=%r>" % (
type(self).__name__, self.parent.filename, self.offset, self.size,
self.endian)
def load(self, fh):
fh = fileview(fh, self.offset, self.size)
fh.seek(0)
self.sizediff = 0
kw = {'_endian_': self.endian}
header = self.mach_header.from_fileobj(fh, **kw)
self.header = header
if header.magic != self.MH_MAGIC:
raise ValueError("header has magic %08x, expecting %08x" % (
header.magic, self.MH_MAGIC))
cmd = self.commands = []
self.filetype = MH_FILETYPE_SHORTNAMES[header.filetype]
read_bytes = 0
low_offset = sys.maxsize
for i in range(header.ncmds):
# read the load command
cmd_load = load_command.from_fileobj(fh, **kw)
# read the specific command
klass = LC_REGISTRY.get(cmd_load.cmd, None)
if klass is None:
raise ValueError("Unknown load command: %d" % (cmd_load.cmd,))
cmd_cmd = klass.from_fileobj(fh, **kw)
if cmd_load.cmd == LC_ID_DYLIB:
# remember where this command was
if self.id_cmd is not None:
raise ValueError("This dylib already has an id")
self.id_cmd = i
if cmd_load.cmd in (LC_SEGMENT, LC_SEGMENT_64):
# for segment commands, read the list of segments
segs = []
# assert that the size makes sense
if cmd_load.cmd == LC_SEGMENT:
section_cls = section
else: # LC_SEGMENT_64
section_cls = section_64
expected_size = (
sizeof(klass) + sizeof(load_command) +
(sizeof(section_cls) * cmd_cmd.nsects)
)
if cmd_load.cmdsize != expected_size:
raise ValueError("Segment size mismatch")
# this is a zero block or something
# so the beginning is wherever the fileoff of this command is
if cmd_cmd.nsects == 0:
if cmd_cmd.filesize != 0:
low_offset = min(low_offset, cmd_cmd.fileoff)
else:
# this one has multiple segments
for j in range(cmd_cmd.nsects):
# read the segment
seg = section_cls.from_fileobj(fh, **kw)
# if the segment has a size and is not zero filled
# then its beginning is the offset of this segment
not_zerofill = ((seg.flags & S_ZEROFILL) != S_ZEROFILL)
if seg.offset > 0 and seg.size > 0 and not_zerofill:
low_offset = min(low_offset, seg.offset)
segs.append(seg)
# data is a list of segments
cmd_data = segs
else:
# data is a raw str
data_size = (
cmd_load.cmdsize - sizeof(klass) - sizeof(load_command)
)
cmd_data = fh.read(data_size)
cmd.append((cmd_load, cmd_cmd, cmd_data))
read_bytes += cmd_load.cmdsize
# make sure the header made sense
if read_bytes != header.sizeofcmds:
raise ValueError("Read %d bytes, header reports %d bytes" % (
read_bytes, header.sizeofcmds))
self.total_size = sizeof(self.mach_header) + read_bytes
self.low_offset = low_offset
# this header overwrites a segment, what the heck?
if self.total_size > low_offset:
raise ValueError("total_size > low_offset (%d > %d)" % (
self.total_size, low_offset))
def walkRelocatables(self, shouldRelocateCommand=_shouldRelocateCommand):
"""
for all relocatable commands
yield (command_index, command_name, filename)
"""
for (idx, (lc, cmd, data)) in enumerate(self.commands):
if shouldRelocateCommand(lc.cmd):
name = _RELOCATABLE_NAMES[lc.cmd]
ofs = cmd.name - sizeof(lc.__class__) - sizeof(cmd.__class__)
yield idx, name, data[ofs:data.find(b'\x00', ofs)].decode(
sys.getfilesystemencoding())
def rewriteInstallNameCommand(self, loadcmd):
"""Rewrite the load command of this dylib"""
if self.id_cmd is not None:
self.rewriteDataForCommand(self.id_cmd, loadcmd)
return True
return False
def changedHeaderSizeBy(self, bytes):
self.sizediff += bytes
if (self.total_size + self.sizediff) > self.low_offset:
print("WARNING: Mach-O header may be too large to relocate")
def rewriteLoadCommands(self, changefunc):
"""
Rewrite the load commands based upon a change dictionary
"""
data = changefunc(self.parent.filename)
changed = False
if data is not None:
if self.rewriteInstallNameCommand(
data.encode(sys.getfilesystemencoding())):
changed = True
for idx, name, filename in self.walkRelocatables():
data = changefunc(filename)
if data is not None:
if self.rewriteDataForCommand(idx, data.encode(
sys.getfilesystemencoding())):
changed = True
return changed
def rewriteDataForCommand(self, idx, data):
lc, cmd, old_data = self.commands[idx]
hdrsize = sizeof(lc.__class__) + sizeof(cmd.__class__)
align = struct.calcsize('L')
data = data + (b'\x00' * (align - (len(data) % align)))
newsize = hdrsize + len(data)
self.commands[idx] = (lc, cmd, data)
self.changedHeaderSizeBy(newsize - lc.cmdsize)
lc.cmdsize, cmd.name = newsize, hdrsize
return True
def synchronize_size(self):
if (self.total_size + self.sizediff) > self.low_offset:
raise ValueError("New Mach-O header is too large to relocate")
self.header.sizeofcmds += self.sizediff
self.total_size = sizeof(self.mach_header) + self.header.sizeofcmds
self.sizediff = 0
def write(self, fileobj):
fileobj = fileview(fileobj, self.offset, self.size)
fileobj.seek(0)
# serialize all the mach-o commands
self.synchronize_size()
self.header.to_fileobj(fileobj)
for lc, cmd, data in self.commands:
lc.to_fileobj(fileobj)
cmd.to_fileobj(fileobj)
if isinstance(data, unicode):
fileobj.write(data.encode(sys.getfilesystemencoding()))
elif isinstance(data, (bytes, str)):
fileobj.write(data)
else:
# segments..
for obj in data:
obj.to_fileobj(fileobj)
# zero out the unused space, doubt this is strictly necessary
# and is generally probably already the case
fileobj.write(b'\x00' * (self.low_offset - fileobj.tell()))
def getSymbolTableCommand(self):
for lc, cmd, data in self.commands:
if lc.cmd == LC_SYMTAB:
return cmd
return None
def getDynamicSymbolTableCommand(self):
for lc, cmd, data in self.commands:
if lc.cmd == LC_DYSYMTAB:
return cmd
return None
def main(fn):
m = MachO(fn)
seen = set()
for header in m.headers:
for idx, name, other in header.walkRelocatables():
if other not in seen:
seen.add(other)
print('\t' + name + ": " + other)
if __name__ == '__main__':
import sys
files = sys.argv[1:] or ['/bin/ls']
for fn in files:
print(fn)
main(fn)
| Python |
#!/usr/bin/env python
from __future__ import print_function
from macholib._cmdline import main as _main
def print_file(fp, path):
print(path, file=fp)
def main():
_main(print_file)
if __name__ == '__main__':
try:
main(print_file)
except KeyboardInterrupt:
pass
| Python |
"""
Utilities for reading and writing Mach-O headers
"""
import os
import sys
from altgraph.Graph import Graph
from altgraph.ObjectGraph import ObjectGraph
from macholib.mach_o import *
from macholib.dyld import dyld_find
from macholib.MachO import MachO
from macholib.itergraphreport import itergraphreport
__all__ = ['MachOGraph']
try:
unicode
except NameError:
unicode = str
class MissingMachO(object):
def __init__(self, filename):
self.graphident = filename
self.headers = ()
def __repr__(self):
return '<%s graphident=%r>' % (type(self).__name__, self.graphident)
class MachOGraph(ObjectGraph):
"""
Graph data structure of Mach-O dependencies
"""
def __init__(self, debug=0, graph=None, env=None, executable_path=None):
super(MachOGraph, self).__init__(debug=debug, graph=graph)
self.env = env
self.trans_table = {}
self.executable_path = executable_path
def locate(self, filename):
assert isinstance(filename, (str, unicode))
fn = self.trans_table.get(filename)
if fn is None:
try:
fn = dyld_find(filename, env=self.env,
executable_path=self.executable_path)
self.trans_table[filename] = fn
except ValueError:
return None
return fn
def findNode(self, name):
assert isinstance(name, (str, unicode))
data = super(MachOGraph, self).findNode(name)
if data is not None:
return data
newname = self.locate(name)
if newname is not None and newname != name:
return self.findNode(newname)
return None
def run_file(self, pathname, caller=None):
assert isinstance(pathname, (str, unicode))
self.msgin(2, "run_file", pathname)
m = self.findNode(pathname)
if m is None:
if not os.path.exists(pathname):
raise ValueError('%r does not exist' % (pathname,))
m = self.createNode(MachO, pathname)
self.createReference(caller, m, edge_data='run_file')
self.scan_node(m)
self.msgout(2, '')
return m
def load_file(self, name, caller=None):
assert isinstance(name, (str, unicode))
self.msgin(2, "load_file", name)
m = self.findNode(name)
if m is None:
newname = self.locate(name)
if newname is not None and newname != name:
return self.load_file(newname, caller=caller)
if os.path.exists(name):
m = self.createNode(MachO, name)
self.scan_node(m)
else:
m = self.createNode(MissingMachO, name)
self.msgout(2, '')
return m
def scan_node(self, node):
self.msgin(2, 'scan_node', node)
for header in node.headers:
for idx, name, filename in header.walkRelocatables():
assert isinstance(name, (str, unicode))
assert isinstance(filename, (str, unicode))
m = self.load_file(filename, caller=node)
self.createReference(node, m, edge_data=name)
self.msgout(2, '', node)
def itergraphreport(self, name='G'):
nodes = map(self.graph.describe_node, self.graph.iterdfs(self))
describe_edge = self.graph.describe_edge
return itergraphreport(nodes, describe_edge, name=name)
def graphreport(self, fileobj=None):
if fileobj is None:
fileobj = sys.stdout
fileobj.writelines(self.itergraphreport())
def main(args):
g = MachOGraph()
for arg in args:
g.run_file(arg)
g.graphreport()
if __name__ == '__main__':
main(sys.argv[1:] or ['/bin/ls'])
| Python |
"""
Class to read the symbol table from a Mach-O header
"""
from macholib.mach_o import *
__all__ = ['SymbolTable']
# XXX: Does not support 64-bit, probably broken anyway
class SymbolTable(object):
def __init__(self, macho, openfile=None):
if openfile is None:
openfile = open
self.macho = macho.headers[0]
self.symtab = macho.getSymbolTableCommand()
self.dysymtab = macho.getDynamicSymbolTableCommand()
fh = openfile(self.macho.filename, 'rb')
try:
if self.symtab is not None:
self.readSymbolTable(fh)
if self.dysymtab is not None:
self.readDynamicSymbolTable(fh)
finally:
fh.close()
def readSymbolTable(self, fh):
cmd = self.symtab
fh.seek(cmd.stroff)
strtab = fh.read(cmd.strsize)
fh.seek(cmd.symoff)
nlists = []
for i in xrange(cmd.nsyms):
cmd = nlist.from_fileobj(fh)
if cmd.n_un == 0:
nlists.append((cmd, ''))
else:
nlists.append((cmd, strtab[cmd.n_un:strtab.find(b'\x00', cmd.n_un)]))
self.nlists = nlists
def readDynamicSymbolTable(self, fh):
cmd = self.dysymtab
nlists = self.nlists
self.localsyms = nlists[cmd.ilocalsym:cmd.ilocalsym+cmd.nlocalsym]
self.extdefsyms = nlists[cmd.iextdefsym:cmd.iextdefsym+cmd.nextdefsym]
self.undefsyms = nlists[cmd.iundefsym:cmd.iundefsym+cmd.nundefsym]
#if cmd.tocoff == 0:
# self.toc = None
#else:
# self.toc = self.readtoc(fh, cmd.tocoff, cmd.ntoc)
#if cmd.modtaboff == 0:
# self.modtab = None
#else:
# self.modtab = self.readmodtab(fh, cmd.modtaboff, cmd.nmodtab)
if cmd.extrefsymoff == 0:
self.extrefsym = None
else:
self.extrefsym = self.readsym(fh, cmd.extrefsymoff, cmd.nextrefsyms)
#if cmd.indirectsymoff == 0:
# self.indirectsym = None
#else:
# self.indirectsym = self.readsym(fh, cmd.indirectsymoff, cmd.nindirectsyms)
#if cmd.extreloff == 0:
# self.extrel = None
#else:
# self.extrel = self.readrel(fh, cmd.extreloff, cmd.nextrel)
#if cmd.locreloff == 0:
# self.locrel = None
#else:
# self.locrel = self.readrel(fh, cmd.locreloff, cmd.nlocrel)
def readtoc(self, fh, off, n):
#print 'toc', off, n
fh.seek(off)
return [dylib_table_of_contents.from_fileobj(fh) for i in xrange(n)]
def readmodtab(self, fh, off, n):
#print 'modtab', off, n
fh.seek(off)
return [dylib_module.from_fileobj(fh) for i in xrange(n)]
def readsym(self, fh, off, n):
#print 'sym', off, n
fh.seek(off)
refs = []
for i in xrange(n):
ref = dylib_reference.from_fileobj(fh)
isym, flags = divmod(ref.isym_flags, 256)
refs.append((self.nlists[isym], flags))
return refs
def readrel(self, fh, off, n):
#print 'rel', off, n
fh.seek(off)
return [relocation_info.from_fileobj(fh) for i in xrange(n)]
| Python |
import os
from macholib.MachOGraph import MachOGraph, MissingMachO
from macholib.util import iter_platform_files, in_system_path, mergecopy, \
mergetree, flipwritable, has_filename_filter
from macholib.dyld import framework_info
from collections import deque
class ExcludedMachO(MissingMachO):
pass
class FilteredMachOGraph(MachOGraph):
def __init__(self, delegate, *args, **kwargs):
super(FilteredMachOGraph, self).__init__(*args, **kwargs)
self.delegate = delegate
def createNode(self, cls, name):
cls = self.delegate.getClass(name, cls)
res = super(FilteredMachOGraph, self).createNode(cls, name)
return res
def locate(self, filename):
newname = super(FilteredMachOGraph, self).locate(filename)
if newname is None:
return None
return self.delegate.locate(newname)
class MachOStandalone(object):
def __init__(self, base, dest=None, graph=None, env=None,
executable_path=None):
self.base = os.path.join(os.path.abspath(base), '')
if dest is None:
dest = os.path.join(self.base, 'Contents', 'Frameworks')
self.dest = dest
self.mm = FilteredMachOGraph(self, graph=graph, env=env,
executable_path=executable_path)
self.changemap = {}
self.excludes = []
self.pending = deque()
def getClass(self, name, cls):
if in_system_path(name):
return ExcludedMachO
for base in self.excludes:
if name.startswith(base):
return ExcludedMachO
return cls
def locate(self, filename):
if in_system_path(filename):
return filename
if filename.startswith(self.base):
return filename
for base in self.excludes:
if filename.startswith(base):
return filename
if filename in self.changemap:
return self.changemap[filename]
info = framework_info(filename)
if info is None:
res = self.copy_dylib(filename)
self.changemap[filename] = res
return res
else:
res = self.copy_framework(info)
self.changemap[filename] = res
return res
def copy_dylib(self, filename):
dest = os.path.join(self.dest, os.path.basename(filename))
if not os.path.exists(dest):
self.mergecopy(filename, dest)
return dest
def mergecopy(self, src, dest):
return mergecopy(src, dest)
def mergetree(self, src, dest):
return mergetree(src, dest)
def copy_framework(self, info):
dest = os.path.join(self.dest, info['shortname'] + '.framework')
destfn = os.path.join(self.dest, info['name'])
src = os.path.join(info['location'], info['shortname'] + '.framework')
if not os.path.exists(dest):
self.mergetree(src, dest)
self.pending.append((destfn, iter_platform_files(dest)))
return destfn
def run(self, platfiles=None, contents=None):
mm = self.mm
if contents is None:
contents = '@executable_path/..'
if platfiles is None:
platfiles = iter_platform_files(self.base)
for fn in platfiles:
mm.run_file(fn)
while self.pending:
fmwk, files = self.pending.popleft()
ref = mm.findNode(fmwk)
for fn in files:
mm.run_file(fn, caller=ref)
changemap = {}
skipcontents = os.path.join(os.path.dirname(self.dest), '')
machfiles = []
for node in mm.flatten(has_filename_filter):
machfiles.append(node)
dest = os.path.join(contents, node.filename[len(skipcontents):])
changemap[node.filename] = dest
def changefunc(path):
res = mm.locate(path)
return changemap.get(res)
for node in machfiles:
fn = mm.locate(node.filename)
if fn is None:
continue
rewroteAny = False
for header in node.headers:
if node.rewriteLoadCommands(changefunc):
rewroteAny = True
if rewroteAny:
old_mode = flipwritable(fn)
try:
with open(fn, 'rb+') as f:
for header in node.headers:
f.seek(0)
node.write(f)
f.seek(0, 2)
f.flush()
finally:
flipwritable(fn, old_mode)
allfiles = [mm.locate(node.filename) for node in machfiles]
return set(filter(None, allfiles))
| Python |
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
from macholib._cmdline import main as _main
from macholib.MachO import MachO
from macholib.mach_o import *
ARCH_MAP={
('<', '64-bit'): 'x86_64',
('<', '32-bit'): 'i386',
('>', '64-bit'): 'pp64',
('>', '32-bit'): 'ppc',
}
def print_file(fp, path):
print(path, file=fp)
m = MachO(path)
for header in m.headers:
seen = set()
if header.MH_MAGIC == MH_MAGIC_64:
sz = '64-bit'
else:
sz = '32-bit'
print(' [%s endian=%r size=%r arch=%r]' % (header.__class__.__name__,
header.endian, sz, ARCH_MAP[(header.endian, sz)]), file=fp)
for idx, name, other in header.walkRelocatables():
if other not in seen:
seen.add(other)
print('\t' + other, file=fp)
def main():
_main(print_file)
if __name__ == '__main__':
try:
sys.exit(main(print_file))
except KeyboardInterrupt:
pass
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.