home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyo (Python 2.6)
-
- from distutils.core import Command
- from distutils.spawn import spawn
- from distutils.errors import *
- import sys
- import os
- import imp
- import types
- import stat
- import marshal
- import zipfile
- import sets
- import tempfile
- import struct
- is_win64 = struct.calcsize('P') == 8
-
- def _is_debug_build():
- for ext, _, _ in imp.get_suffixes():
- if ext == '_d.pyd':
- return True
-
- return False
-
- is_debug_build = _is_debug_build()
- if is_debug_build:
- python_dll = 'python%d%d_d.dll' % sys.version_info[:2]
- else:
- python_dll = 'python%d%d.dll' % sys.version_info[:2]
- RT_BITMAP = 2
- _py_suffixes = [
- '.py',
- '.pyo',
- '.pyc',
- '.pyw']
- _c_suffixes = [] if _triple[2] == imp.C_EXTENSION else _[1]
-
- def imp_find_module(name):
- names = name.split('.')
- path = None
- for name in names:
- result = imp.find_module(name, path)
- path = [
- result[1]]
-
- return result
-
-
- def fancy_split(str, sep = ','):
- if str is None:
- return []
- if hasattr(str, 'split'):
- return [ item.strip() for item in str.split(sep) ]
- return str
-
-
- def ensure_unicode(text):
- if isinstance(text, unicode):
- return text
- return text.decode('mbcs')
-
- LOADER = '\ndef __load():\n import imp, os, sys\n try:\n dirname = os.path.dirname(__loader__.archive)\n except NameError:\n dirname = sys.prefix\n path = os.path.join(dirname, \'%s\')\n #print "py2exe extension module", __name__, "->", path\n mod = imp.load_dynamic(__name__, path)\n## mod.frozen = 1\n__load()\ndel __load\n'
-
- class Target:
-
- def __init__(self, **kw):
- self.__dict__.update(kw)
- m = self.__dict__.get('modules')
- if m and type(m) in types.StringTypes:
- self.modules = [
- m]
-
-
-
- def get_dest_base(self):
- dest_base = getattr(self, 'dest_base', None)
- if dest_base:
- return dest_base
- script = getattr(self, 'script', None)
- if script:
- return os.path.basename(os.path.splitext(script)[0])
- modules = getattr(self, 'modules', None)
- return modules[0].split('.')[-1]
-
-
- def validate(self):
- resources = getattr(self, 'bitmap_resources', []) + getattr(self, 'icon_resources', [])
- for r_id, r_filename in resources:
- if type(r_id) != type(0):
- raise DistutilsOptionError, 'Resource ID must be an integer'
- type(r_id) != type(0)
- if not os.path.isfile(r_filename):
- raise DistutilsOptionError, "Resource filename '%s' does not exist" % r_filename
- os.path.isfile(r_filename)
-
-
-
-
- def FixupTargets(targets, default_attribute):
- if not targets:
- return targets
- ret = []
- for target_def in targets:
- if type(target_def) in types.StringTypes:
- target = Target(**{
- default_attribute: target_def })
- else:
- d = getattr(target_def, '__dict__', target_def)
- if not d.has_key(default_attribute):
- raise DistutilsOptionError, "This target class requires an attribute '%s'" % default_attribute
- d.has_key(default_attribute)
- target = Target(**d)
- target.validate()
- ret.append(target)
-
- return ret
-
-
- class py2exe(Command):
- description = ''
- user_options = [
- ('optimize=', 'O', 'optimization level: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0]'),
- ('dist-dir=', 'd', 'directory to put final built distributions in (default is dist)'),
- ('excludes=', 'e', 'comma-separated list of modules to exclude'),
- ('dll-excludes=', None, 'comma-separated list of DLLs to exclude'),
- ('ignores=', None, 'comma-separated list of modules to ignore if they are not found'),
- ('includes=', 'i', 'comma-separated list of modules to include'),
- ('packages=', 'p', 'comma-separated list of packages to include'),
- ('compressed', 'c', 'create a compressed zipfile'),
- ('xref', 'x', 'create and show a module cross reference'),
- ('bundle-files=', 'b', 'bundle dlls in the zipfile or the exe. Valid levels are 1, 2, or 3 (default)'),
- ('skip-archive', None, 'do not place Python bytecode files in an archive, put them directly in the file system'),
- ('ascii', 'a', 'do not automatically include encodings and codecs'),
- ('custom-boot-script=', None, 'Python file that will be run when setting up the runtime environment')]
- boolean_options = [
- 'compressed',
- 'xref',
- 'ascii',
- 'skip-archive',
- 'retain_times']
-
- def initialize_options(self):
- self.xref = 0
- self.compressed = 0
- self.unbuffered = 0
- self.optimize = 0
- self.includes = None
- self.excludes = None
- self.ignores = None
- self.packages = None
- self.dist_dir = None
- self.dll_excludes = 'msvcr90.dll msvcp90.dll'
- self.typelibs = None
- self.bundle_files = 3
- self.skip_archive = 0
- self.ascii = 0
- self.custom_boot_script = None
- self.retain_times = 0
-
-
- def finalize_options(self):
- self.optimize = int(self.optimize)
- self.excludes = fancy_split(self.excludes)
- self.includes = fancy_split(self.includes)
- self.ignores = fancy_split(self.ignores)
- self.bundle_files = int(self.bundle_files)
- if self.bundle_files < 1 or self.bundle_files > 3:
- raise DistutilsOptionError, 'bundle-files must be 1, 2, or 3, not %s' % self.bundle_files
- self.bundle_files > 3
- if is_win64 and self.bundle_files < 3:
- raise DistutilsOptionError, 'bundle-files %d not yet supported on win64' % self.bundle_files
- self.bundle_files < 3
- if self.skip_archive:
- if self.compressed:
- raise DistutilsOptionError, "can't compress when skipping archive"
- self.compressed
- if self.distribution.zipfile is None:
- raise DistutilsOptionError, 'zipfile cannot be None when skipping archive'
- self.distribution.zipfile is None
-
- for m in self.includes:
- if m in self.excludes:
- self.excludes.remove(m)
- continue
-
- self.packages = fancy_split(self.packages)
- self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
- self.dll_excludes = [ x.lower() for x in fancy_split(self.dll_excludes) ]
-
-
- def run(self):
- build = self.reinitialize_command('build')
- build.run()
- sys_old_path = sys.path[:]
- if build.build_platlib is not None:
- sys.path.insert(0, build.build_platlib)
-
- if build.build_lib is not None:
- sys.path.insert(0, build.build_lib)
-
-
- try:
- self._run()
- finally:
- sys.path = sys_old_path
-
-
-
- def _run(self):
- self.create_directories()
- self.plat_prepare()
- self.fixup_distribution()
- dist = self.distribution
- required_modules = []
- for target in dist.com_server + dist.service + dist.ctypes_com_server:
- required_modules.extend(target.modules)
-
- required_files = [ target.script for target in dist.windows + dist.console ]
- mf = self.create_modulefinder()
- for f in dist.isapi:
- mf.load_file(f.script)
-
- orig_compile = compile
- import __builtin__
-
- def my_compile(source, filename, *args):
-
- try:
- result = orig_compile(source, filename, *args)
- except Exception:
- details = None
- raise DistutilsError, "compiling '%s' failed\n %s: %s" % (filename, details.__class__.__name__, details)
-
- return result
-
- __builtin__.compile = my_compile
- print '*** searching for required modules ***'
- self.find_needed_modules(mf, required_files, required_modules)
- print '*** parsing results ***'
- (py_files, extensions, builtins) = self.parse_mf_results(mf)
- if self.xref:
- mf.create_xref()
-
- print '*** finding dlls needed ***'
- dlls = self.find_dlls(extensions)
- self.plat_finalize(mf.modules, py_files, extensions, dlls)
- dlls = _[2]
- print '*** create binaries ***'
- self.create_binaries(py_files, extensions, dlls)
- self.fix_badmodules(mf)
- if self.other_depends:
- print
- print '*** binary dependencies ***'
- print 'Your executable(s) also depend on these dlls which are not included,'
- print 'you may or may not need to distribute them.'
- print
- print 'Make sure you have the license if you distribute any of them, and'
- print "make sure you don't distribute files belonging to the operating system."
- print
- for fnm in self.other_depends:
- print ' ', os.path.basename(fnm), '-', fnm.strip()
-
-
-
-
- def create_modulefinder(self):
- ReplacePackage = ReplacePackage
- import modulefinder
- ModuleFinder = ModuleFinder
- import py2exe.mf
- ReplacePackage('_xmlplus', 'xml')
- return ModuleFinder(excludes = self.excludes)
-
-
- def fix_badmodules(self, mf):
- builtins = {
- 'clip_dndc': 'wxPython.clip_dnd',
- 'cmndlgsc': 'wxPython.cmndlgs',
- 'controls2c': 'wxPython.controls2',
- 'controlsc': 'wxPython.controls',
- 'eventsc': 'wxPython.events',
- 'filesysc': 'wxPython.filesys',
- 'fontsc': 'wxPython.fonts',
- 'framesc': 'wxPython.frames',
- 'gdic': 'wxPython.gdi',
- 'imagec': 'wxPython.image',
- 'mdic': 'wxPython.mdi',
- 'misc2c': 'wxPython.misc2',
- 'miscc': 'wxPython.misc',
- 'printfwc': 'wxPython.printfw',
- 'sizersc': 'wxPython.sizers',
- 'stattoolc': 'wxPython.stattool',
- 'streamsc': 'wxPython.streams',
- 'utilsc': 'wxPython.utils',
- 'windows2c': 'wxPython.windows2',
- 'windows3c': 'wxPython.windows3',
- 'windowsc': 'wxPython.windows' }
- bad = mf.badmodules
- for name in mf.any_missing():
- if name in self.ignores:
- del bad[name]
- continue
-
- mod = builtins.get(name, None)
- if mod is not None:
- if mod in bad[name] and bad[name] == {
- mod: 1 }:
- del bad[name]
-
- bad[name] == {
- mod: 1 }
-
-
-
- def find_dlls(self, extensions):
- dlls = [ item.__file__ for item in extensions ]
- extra_path = []
- (dlls, unfriendly_dlls, other_depends) = self.find_dependend_dlls(dlls, extra_path + sys.path, self.dll_excludes)
- self.other_depends = other_depends
- for item in extensions:
- if item.__file__ in dlls:
- dlls.remove(item.__file__)
- continue
- []
-
- return dlls
-
-
- def create_directories(self):
- bdist_base = self.get_finalized_command('bdist').bdist_base
- self.bdist_dir = os.path.join(bdist_base, 'winexe')
- collect_name = 'collect-%d.%d' % sys.version_info[:2]
- self.collect_dir = os.path.abspath(os.path.join(self.bdist_dir, collect_name))
- self.mkpath(self.collect_dir)
- bundle_name = 'bundle-%d.%d' % sys.version_info[:2]
- self.bundle_dir = os.path.abspath(os.path.join(self.bdist_dir, bundle_name))
- self.mkpath(self.bundle_dir)
- self.temp_dir = os.path.abspath(os.path.join(self.bdist_dir, 'temp'))
- self.mkpath(self.temp_dir)
- self.dist_dir = os.path.abspath(self.dist_dir)
- self.mkpath(self.dist_dir)
- if self.distribution.zipfile is None:
- self.lib_dir = self.dist_dir
- else:
- self.lib_dir = os.path.join(self.dist_dir, os.path.dirname(self.distribution.zipfile))
- self.mkpath(self.lib_dir)
-
-
- def copy_extensions(self, extensions):
- print '*** copy extensions ***'
- for item in extensions:
- src = item.__file__
- if self.bundle_files > 2:
- dst = os.path.join(self.lib_dir, item.__pydfile__)
- self.copy_file(src, dst, preserve_mode = 0)
- self.lib_files.append(dst)
- continue
- package = '\\'.join(item.__name__.split('.')[:-1])
- if package:
- dst = os.path.join(package, os.path.basename(src))
- else:
- dst = os.path.basename(src)
- self.copy_file(src, os.path.join(self.collect_dir, dst), preserve_mode = 0)
- self.compiled_files.append(dst)
-
-
-
- def copy_dlls(self, dlls):
- print '*** copy dlls ***'
- if self.bundle_files < 3:
- self.copy_dlls_bundle_files(dlls)
- return None
- for dll in dlls:
- base = os.path.basename(dll)
- if base.lower() in self.dlls_in_exedir:
- dst = os.path.join(self.exe_dir, base)
- else:
- dst = os.path.join(self.lib_dir, base)
- (_, copied) = self.copy_file(dll, dst, preserve_mode = 0)
- if not (self.dry_run) and copied and base.lower() == python_dll.lower():
- self.patch_python_dll_winver(dst)
-
- self.lib_files.append(dst)
-
-
-
- def copy_dlls_bundle_files(self, dlls):
- for dll in dlls:
- base = os.path.basename(dll)
- if base.lower() in self.dlls_in_exedir:
- if base.lower() == python_dll.lower() and self.bundle_files < 2:
- dst = os.path.join(self.bundle_dir, base)
- else:
- dst = os.path.join(self.exe_dir, base)
- (_, copied) = self.copy_file(dll, dst, preserve_mode = 0)
- if not (self.dry_run) and copied and base.lower() == python_dll.lower():
- self.patch_python_dll_winver(dst)
-
- self.lib_files.append(dst)
- continue
-
- dst = os.path.join(self.collect_dir, os.path.basename(dll))
- self.copy_file(dll, dst, preserve_mode = 0)
- self.compiled_files.append(os.path.basename(dst))
-
-
-
- def create_binaries(self, py_files, extensions, dlls):
- dist = self.distribution
- print '*** byte compile python files ***'
- self.compiled_files = byte_compile(py_files, target_dir = self.collect_dir, optimize = self.optimize, force = 0, verbose = self.verbose, dry_run = self.dry_run)
- self.lib_files = []
- self.console_exe_files = []
- self.windows_exe_files = []
- self.service_exe_files = []
- self.comserver_files = []
- self.copy_extensions(extensions)
- self.copy_dlls(dlls)
- if dist.zipfile is None:
- (fd, archive_name) = tempfile.mkstemp()
- os.close(fd)
- else:
- archive_name = os.path.join(self.lib_dir, os.path.basename(dist.zipfile))
- arcname = self.make_lib_archive(archive_name, base_dir = self.collect_dir, files = self.compiled_files, verbose = self.verbose, dry_run = self.dry_run)
- if dist.zipfile is not None:
- self.lib_files.append(arcname)
-
- for target in self.distribution.isapi:
- print '*** copy isapi support DLL ***'
- import isapi
- if not is_debug_build or 'PyISAPI_loader_d.dll':
- pass
- src_name = 'PyISAPI_loader.dll'
- src = os.path.join(isapi.__path__[0], src_name)
- script_base = os.path.splitext(os.path.basename(target.script))[0]
- dst = os.path.join(self.exe_dir, '_' + script_base + '.dll')
- self.copy_file(src, dst, preserve_mode = 0)
-
- if self.distribution.has_data_files():
- print '*** copy data files ***'
- install_data = self.reinitialize_command('install_data')
- install_data.install_dir = self.dist_dir
- install_data.ensure_finalized()
- install_data.run()
- self.lib_files.extend(install_data.get_outputs())
-
- for target in dist.console:
- dst = self.build_executable(target, self.get_console_template(), arcname, target.script)
- self.console_exe_files.append(dst)
-
- for target in dist.windows:
- dst = self.build_executable(target, self.get_windows_template(), arcname, target.script)
- self.windows_exe_files.append(dst)
-
- for target in dist.service:
- dst = self.build_service(target, self.get_service_template(), arcname)
- self.service_exe_files.append(dst)
-
- for target in dist.isapi:
- dst = self.build_isapi(target, self.get_isapi_template(), arcname)
-
- for target in dist.com_server:
- if getattr(target, 'create_exe', True):
- dst = self.build_comserver(target, self.get_comexe_template(), arcname)
- self.comserver_files.append(dst)
-
- if getattr(target, 'create_dll', True):
- dst = self.build_comserver(target, self.get_comdll_template(), arcname)
- self.comserver_files.append(dst)
- continue
-
- for target in dist.ctypes_com_server:
- dst = self.build_comserver(target, self.get_ctypes_comdll_template(), arcname, boot_script = 'ctypes_com_server')
- self.comserver_files.append(dst)
-
- if dist.zipfile is None:
- os.unlink(arcname)
- elif self.bundle_files < 3 or self.compressed:
- arcbytes = open(arcname, 'rb').read()
- arcfile = open(arcname, 'wb')
- if self.bundle_files < 2:
- print 'Adding %s to %s' % (python_dll, arcname)
- arcfile.write('<pythondll>')
- bytes = open(os.path.join(self.bundle_dir, python_dll), 'rb').read()
- arcfile.write(struct.pack('i', len(bytes)))
- arcfile.write(bytes)
-
- if self.compressed:
- zlib_file = imp.find_module('zlib')[0]
- if zlib_file:
- if not is_debug_build or '_d':
- pass
- print 'Adding zlib%s.pyd to %s' % ('', arcname)
- arcfile.write('<zlib.pyd>')
- bytes = zlib_file.read()
- arcfile.write(struct.pack('i', len(bytes)))
- arcfile.write(bytes)
-
-
- arcfile.write(arcbytes)
-
-
-
- def get_console_template(self):
- if not is_debug_build or 'run_d.exe':
- pass
- return 'run.exe'
-
-
- def get_windows_template(self):
- if not is_debug_build or 'run_w_d.exe':
- pass
- return 'run_w.exe'
-
-
- def get_service_template(self):
- if not is_debug_build or 'run_d.exe':
- pass
- return 'run.exe'
-
-
- def get_isapi_template(self):
- if not is_debug_build or 'run_isapi_d.dll':
- pass
- return 'run_isapi.dll'
-
-
- def get_comexe_template(self):
- if not is_debug_build or 'run_w_d.exe':
- pass
- return 'run_w.exe'
-
-
- def get_comdll_template(self):
- if not is_debug_build or 'run_dll_d.dll':
- pass
- return 'run_dll.dll'
-
-
- def get_ctypes_comdll_template(self):
- if not is_debug_build or 'run_ctypes_dll_d.dll':
- pass
- return 'run_ctypes_dll.dll'
-
-
- def fixup_distribution(self):
- dist = self.distribution
- dist.com_server = FixupTargets(dist.com_server, 'modules')
- dist.ctypes_com_server = FixupTargets(dist.ctypes_com_server, 'modules')
- dist.service = FixupTargets(dist.service, 'modules')
- dist.windows = FixupTargets(dist.windows, 'script')
- dist.console = FixupTargets(dist.console, 'script')
- dist.isapi = FixupTargets(dist.isapi, 'script')
- paths = sets.Set()
- for target in dist.com_server + dist.service + dist.windows + dist.console + dist.isapi:
- paths.add(os.path.dirname(target.get_dest_base()))
-
- if len(paths) > 1:
- raise [], [] % [ p for p in paths ]
- len(paths) > 1
- if paths:
- exe_dir = paths.pop()
- if os.path.isabs(exe_dir):
- raise DistutilsOptionError, 'exe directory must be relative: %s' % exe_dir
- os.path.isabs(exe_dir)
- self.exe_dir = os.path.join(self.dist_dir, exe_dir)
- self.mkpath(self.exe_dir)
- else:
- self.exe_dir = self.lib_dir
-
-
- def get_boot_script(self, boot_type):
- thisfile = sys.modules['py2exe.build_exe'].__file__
- return os.path.join(os.path.dirname(thisfile), 'boot_' + boot_type + '.py')
-
-
- def build_comserver(self, target, template, arcname, boot_script = 'com_servers'):
- vars = {
- 'com_module_names': target.modules }
- boot = self.get_boot_script(boot_script)
- return self.build_executable(target, template, arcname, boot, vars)
-
-
- def get_service_names(self, module_name):
- __import__(module_name)
- mod = sys.modules[module_name]
- for name, klass in mod.__dict__.items():
- if hasattr(klass, '_svc_name_'):
- break
- continue
- else:
- raise RuntimeError, 'No services in module'
- deps = None
- if hasattr(klass, '_svc_deps_'):
- deps = klass._svc_deps_
-
- return (klass.__name__, klass._svc_name_, klass._svc_display_name_, deps)
-
-
- def build_service(self, target, template, arcname):
- cmdline_style = getattr(target, 'cmdline_style', 'py2exe')
- if cmdline_style not in ('py2exe', 'pywin32', 'custom'):
- raise RuntimeError, 'cmdline_handler invalid'
- cmdline_style not in ('py2exe', 'pywin32', 'custom')
- vars = {
- 'service_module_names': target.modules,
- 'cmdline_style': cmdline_style }
- boot = self.get_boot_script('service')
- return self.build_executable(target, template, arcname, boot, vars)
-
-
- def build_isapi(self, target, template, arcname):
- target_module = os.path.splitext(os.path.basename(target.script))[0]
- vars = {
- 'isapi_module_name': target_module }
- return self.build_executable(target, template, arcname, None, vars)
-
-
- def build_executable(self, target, template, arcname, script, vars = { }):
- add_resource = add_resource
- add_icon = add_icon
- import py2exe_util
- ext = os.path.splitext(template)[1]
- exe_base = target.get_dest_base()
- exe_path = os.path.join(self.dist_dir, exe_base + ext)
- parent_levels = len(os.path.normpath(exe_base).split(os.sep)) - 1
- lib_leaf = self.lib_dir[len(self.dist_dir) + 1:]
- relative_arcname = ('..' + os.sep) * parent_levels
- if lib_leaf:
- relative_arcname += lib_leaf + os.sep
-
- relative_arcname += os.path.basename(arcname)
- src = os.path.join(os.path.dirname(__file__), template)
- old_force = self.force
- self.force = True
- self.copy_file(src, exe_path, preserve_mode = 0)
- self.force = old_force
- os.chmod(exe_path, stat.S_IREAD | stat.S_IWRITE)
-
- try:
- f = open(exe_path, 'a+b')
- f.close()
- except IOError:
- why = None
- print 'WARNING: File %s could not be opened - %s' % (exe_path, why)
-
- boot = self.get_boot_script('common')
- boot_code = compile(file(boot, 'U').read(), os.path.abspath(boot), 'exec')
- code_objects = [
- boot_code]
- if self.bundle_files < 3:
- code_objects.append(compile('import zipextimporter; zipextimporter.install()', '<install zipextimporter>', 'exec'))
-
- for var_name, var_val in vars.items():
- code_objects.append(compile('%s=%r\n' % (var_name, var_val), var_name, 'exec'))
-
- if self.custom_boot_script:
- code_object = compile(file(self.custom_boot_script, 'U').read() + '\n', os.path.abspath(self.custom_boot_script), 'exec')
- code_objects.append(code_object)
-
- if script:
- code_object = compile(open(script, 'U').read() + '\n', os.path.basename(script), 'exec')
- code_objects.append(code_object)
-
- code_bytes = marshal.dumps(code_objects)
- if self.distribution.zipfile is None:
- relative_arcname = ''
-
- si = struct.pack('iiii', 2018915346, self.optimize, self.unbuffered, len(code_bytes)) + relative_arcname + '\x00'
- script_bytes = si + code_bytes + '\x00\x00'
- self.announce('add script resource, %d bytes' % len(script_bytes))
- if not self.dry_run:
- add_resource(ensure_unicode(exe_path), script_bytes, u'PYTHONSCRIPT', 1, True)
- if self.bundle_files < 2 and self.distribution.zipfile is None:
- dll_path = os.path.join(self.bundle_dir, python_dll)
- bytes = open(dll_path, 'rb').read()
- print 'Adding %s as resource to %s' % (python_dll, exe_path)
- add_resource(ensure_unicode(exe_path), bytes, ensure_unicode(python_dll).upper(), 1, False)
-
- if self.compressed and self.bundle_files < 3 and self.distribution.zipfile is None:
- zlib_file = imp.find_module('zlib')[0]
- if zlib_file:
- print 'Adding zlib.pyd as resource to %s' % exe_path
- zlib_bytes = zlib_file.read()
- add_resource(ensure_unicode(exe_path), zlib_bytes, u'ZLIB.PYD', 1, False)
-
-
-
- bitmap_resources = getattr(target, 'bitmap_resources', [])
- for bmp_id, bmp_filename in bitmap_resources:
- bmp_data = open(bmp_filename, 'rb').read()
- if not self.dry_run:
- add_resource(ensure_unicode(exe_path), bmp_data[14:], RT_BITMAP, bmp_id, False)
- continue
-
- icon_resources = getattr(target, 'icon_resources', [])
- for ico_id, ico_filename in icon_resources:
- if not self.dry_run:
- add_icon(ensure_unicode(exe_path), ensure_unicode(ico_filename), ico_id)
- continue
-
- for res_type, res_id, data in getattr(target, 'other_resources', []):
- if not self.dry_run:
- if isinstance(res_type, basestring):
- res_type = ensure_unicode(res_type)
-
- add_resource(ensure_unicode(exe_path), data, res_type, res_id, False)
- continue
-
- typelib = getattr(target, 'typelib', None)
- if typelib is not None:
- data = open(typelib, 'rb').read()
- add_resource(ensure_unicode(exe_path), data, u'TYPELIB', 1, False)
-
- self.add_versioninfo(target, exe_path)
- if self.distribution.zipfile is None:
- zip_data = open(arcname, 'rb').read()
- open(exe_path, 'a+b').write(zip_data)
-
- return exe_path
-
-
- def add_versioninfo(self, target, exe_path):
-
- def get(name, md = (self.distribution.metadata,)):
- return getattr(target, name, getattr(md, name, None))
-
- version = get('version')
- if version is None:
- return None
- Version = Version
- RT_VERSION = RT_VERSION
- VersionError = VersionError
- import py2exe.resources.VersionInfo
- if not get('product_version'):
- pass
- version = Version(version, file_description = get('description'), comments = get('comments'), company_name = get('company_name'), legal_copyright = get('copyright'), legal_trademarks = get('trademarks'), original_filename = os.path.basename(exe_path), product_name = get('name'), product_version = version)
-
- try:
- bytes = version.resource_bytes()
- except VersionError:
- version is None
- detail = version is None
- self.warn('Version Info will not be included:\n %s' % detail)
- return None
-
- add_resource = add_resource
- import py2exe_util
- add_resource(ensure_unicode(exe_path), bytes, RT_VERSION, 1, False)
-
-
- def patch_python_dll_winver(self, dll_name, new_winver = None):
- StringTable = StringTable
- RT_STRING = RT_STRING
- import py2exe.resources.StringTables
- add_resource = add_resource
- import py2exe_util
- if not new_winver and self.distribution.metadata.name:
- pass
- new_winver = 'py2exe'
- if self.verbose:
- print "setting sys.winver for '%s' to '%s'" % (dll_name, new_winver)
-
- if self.dry_run:
- return None
- st = os.stat(dll_name)
- os.chmod(dll_name, stat.S_IREAD | stat.S_IWRITE)
-
- try:
- f = open(dll_name, 'a+b')
- f.close()
- except IOError:
- self.dry_run
- why = self.dry_run
- print 'WARNING: File %s could not be opened - %s' % (dll_name, why)
- except:
- self.dry_run
-
- s = StringTable()
- s.add_string(1000, new_winver)
- delete = True
- for id, data in s.binary():
- add_resource(ensure_unicode(dll_name), data, RT_STRING, id, delete)
- delete = False
-
- os.utime(dll_name, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
-
-
- def find_dependend_dlls(self, dlls, pypath, dll_excludes):
- import py2exe_util
- sysdir = py2exe_util.get_sysdir()
- windir = py2exe_util.get_windir()
- exedir = os.path.dirname(sys.executable)
- syspath = os.environ['PATH']
- loadpath = ';'.join([
- exedir,
- sysdir,
- windir,
- syspath])
- loadpath = loadpath + ';' + ';'.join(pypath)
- templates = sets.Set()
- if self.distribution.console:
- templates.add(self.get_console_template())
-
- if self.distribution.windows:
- templates.add(self.get_windows_template())
-
- if self.distribution.service:
- templates.add(self.get_service_template())
-
- for target in self.distribution.com_server:
- if getattr(target, 'create_exe', True):
- templates.add(self.get_comexe_template())
-
- if getattr(target, 'create_dll', True):
- templates.add(self.get_comdll_template())
- continue
-
- templates = [ os.path.join(os.path.dirname(__file__), t) for t in templates ]
- images = dlls + templates
- self.announce('Resolving binary dependencies:')
- (alldlls, warnings, other_depends) = bin_depends(loadpath, images + [
- sys.executable], dll_excludes)
- alldlls.remove(sys.executable)
- for dll in alldlls:
- self.announce(' %s' % dll)
-
- for t in templates:
- alldlls.remove(t)
-
- return (alldlls, warnings, other_depends)
-
-
- def get_hidden_imports(self):
- return {
- 'time': [
- '_strptime'],
- 'cPickle': [
- 'copy_reg'],
- 'parser': [
- 'copy_reg'],
- 'codecs': [
- 'encodings'],
- 'cStringIO': [
- 'copy_reg'],
- '_sre': [
- 'copy',
- 'string',
- 'sre'] }
-
-
- def parse_mf_results(self, mf):
- for name, imports in self.get_hidden_imports().items():
- if name in mf.modules.keys():
- for mod in imports:
- mf.import_hook(mod)
-
-
- tcl_src_dir = None
- tcl_dst_dir = None
- if 'Tkinter' in mf.modules.keys():
- import Tkinter
- import _tkinter
- tk = _tkinter.create()
- tcl_dir = tk.call('info', 'library')
- tcl_src_dir = os.path.split(tcl_dir)[0]
- tcl_dst_dir = os.path.join(self.lib_dir, 'tcl')
- self.announce('Copying TCL files from %s...' % tcl_src_dir)
- self.copy_tree(os.path.join(tcl_src_dir, 'tcl%s' % _tkinter.TCL_VERSION), os.path.join(tcl_dst_dir, 'tcl%s' % _tkinter.TCL_VERSION))
- self.copy_tree(os.path.join(tcl_src_dir, 'tk%s' % _tkinter.TK_VERSION), os.path.join(tcl_dst_dir, 'tk%s' % _tkinter.TK_VERSION))
- del tk
- del _tkinter
- del Tkinter
-
- py_files = []
- extensions = []
- builtins = []
- for item in mf.modules.values():
- if item.__name__ == '__main__':
- continue
-
- if self.bundle_files < 3 and item.__name__ in ('pythoncom', 'pywintypes'):
- continue
-
- src = item.__file__
- if src:
- (base, ext) = os.path.splitext(src)
- suffix = ext
- if sys.platform.startswith('win') and ext in ('.dll', '.pyd') and base.endswith('_d'):
- suffix = '_d' + ext
-
- if suffix in _py_suffixes:
- py_files.append(item)
- elif suffix in _c_suffixes:
- extensions.append(item)
- if not self.bundle_files < 3:
- loader = self.create_loader(item)
- if loader:
- py_files.append(loader)
-
-
- else:
- raise RuntimeError("Don't know how to handle '%s'" % repr(src))
- suffix in _py_suffixes
- builtins.append(item.__name__)
-
- py_files.sort((lambda a, b: cmp(a.__file__, b.__file__)))
- extensions.sort((lambda a, b: cmp(a.__file__, b.__file__)))
- builtins.sort()
- return (py_files, extensions, builtins)
-
-
- def plat_finalize(self, modules, py_files, extensions, dlls):
- if sys.platform == 'win32':
- if 'pythoncom' in modules.keys():
- import pythoncom
- dlls.add(pythoncom.__file__)
-
- if 'pywintypes' in modules.keys():
- import pywintypes
- dlls.add(pywintypes.__file__)
-
- self.copy_w9xpopen(modules, dlls)
- else:
- raise DistutilsError, 'Platform %s not yet implemented' % sys.platform
- return sys.platform == 'win32'
-
-
- def copy_w9xpopen(self, modules, dlls):
- if 'os' in modules.keys() or 'popen2' in modules.keys():
- if is_debug_build:
- fname = os.path.join(os.path.dirname(sys.executable), 'w9xpopen_d.exe')
- else:
- fname = os.path.join(os.path.dirname(sys.executable), 'w9xpopen.exe')
- if os.path.exists(fname):
- dlls.add(fname)
-
-
-
-
- def create_loader(self, item):
- pathname = os.path.join(self.temp_dir, '%s.py' % item.__name__)
- if self.bundle_files > 2:
- fname = item.__name__ + os.path.splitext(item.__file__)[1]
- item.__pydfile__ = fname
- else:
- fname = os.path.basename(item.__file__)
- if self.verbose:
- print "creating python loader for extension '%s' (%s -> %s)" % (item.__name__, item.__file__, fname)
-
- source = LOADER % fname
- if not self.dry_run:
- open(pathname, 'w').write(source)
- if self.retain_times:
- st = os.stat(item.__file__)
- os.utime(pathname, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
-
- else:
- return None
- Module = Module
- import modulefinder
- return Module(item.__name__, pathname)
-
-
- def plat_prepare(self):
- self.includes.append('warnings')
- if not self.ascii:
- self.packages.append('encodings')
- self.includes.append('codecs')
-
- if self.bundle_files < 3:
- self.includes.append('zipextimporter')
- self.excludes.append('_memimporter')
-
- if self.compressed:
- self.includes.append('zlib')
-
- self.ignores.append('os.path')
- if sys.platform == 'win32':
- self.ignores += [
- 'AL',
- 'Audio_mac',
- 'Carbon.File',
- 'Carbon.Folder',
- 'Carbon.Folders',
- 'EasyDialogs',
- 'MacOS',
- 'Mailman',
- 'SOCKS',
- 'SUNAUDIODEV',
- '_dummy_threading',
- '_emx_link',
- '_xmlplus',
- '_xmlrpclib',
- 'al',
- 'bundlebuilder',
- 'ce',
- 'cl',
- 'dbm',
- 'dos',
- 'fcntl',
- 'gestalt',
- 'grp',
- 'ic',
- 'java.lang',
- 'mac',
- 'macfs',
- 'macostools',
- 'mkcwproject',
- 'org.python.core',
- 'os.path',
- 'os2',
- 'poll',
- 'posix',
- 'pwd',
- 'readline',
- 'riscos',
- 'riscosenviron',
- 'riscospath',
- 'rourl2path',
- 'sgi',
- 'sgmlop',
- 'sunaudiodev',
- 'termios',
- 'vms_lib']
- if not is_debug_build or '_d':
- pass
- if not is_debug_build or 'd':
- pass
- self.dlls_in_exedir = [
- python_dll,
- 'w9xpopen%s.exe' % '',
- 'msvcr71%s.dll' % '']
- else:
- raise DistutilsError, 'Platform %s not yet implemented' % sys.platform
- return self
-
-
- def find_needed_modules(self, mf, files, modules):
- for mod in modules:
- mf.import_hook(mod)
-
- for path in files:
- mf.run_script(path)
-
- mf.run_script(self.get_boot_script('common'))
- if self.distribution.com_server:
- mf.run_script(self.get_boot_script('com_servers'))
-
- if self.distribution.ctypes_com_server:
- mf.run_script(self.get_boot_script('ctypes_com_server'))
-
- if self.distribution.service:
- mf.run_script(self.get_boot_script('service'))
-
- if self.custom_boot_script:
- mf.run_script(self.custom_boot_script)
-
- for mod in self.includes:
- if mod[-2:] == '.*':
- mf.import_hook(mod[:-2], None, [
- '*'])
- continue
-
- try:
- mf.import_hook(mod)
- continue
- except ImportError:
- for exc in self.excludes:
- if mod.startswith(exc):
- print >>sys.stderr, 'Ignoring ImportError for %r' % mod
- break
- continue
- else:
- raise
-
-
-
- for f in self.packages:
-
- def visit(arg, dirname, names):
- if '__init__.py' in names:
- arg.append(dirname)
-
-
- mf.import_hook(f)
- if f in mf.modules:
- module = mf.modules[f]
- if module.__path__ is None:
- paths = [
- module.__file__]
- else:
- paths = module.__path__
- else:
-
- try:
- paths = [
- imp_find_module(f)[1]]
- except ImportError:
- self.warn('No package named %s' % f)
- continue
-
- packages = []
- for path in paths:
- os.path.walk(path, visit, packages)
- for p in packages:
- if p.startswith(path):
- package = f + '.' + p[len(path) + 1:].replace('\\', '.')
- mf.import_hook(package, None, [
- '*'])
- continue
-
-
-
- return mf
-
-
- def make_lib_archive(self, zip_filename, base_dir, files, verbose = 0, dry_run = 0):
- mkpath = mkpath
- import distutils.dir_util
- if not self.skip_archive:
- mkpath(os.path.dirname(zip_filename), dry_run = dry_run)
- if self.compressed:
- compression = zipfile.ZIP_DEFLATED
- else:
- compression = zipfile.ZIP_STORED
- if not dry_run:
- z = zipfile.ZipFile(zip_filename, 'w', compression = compression)
- for f in files:
- z.write(os.path.join(base_dir, f), f)
-
- z.close()
-
- return zip_filename
- copy_file = copy_file
- import distutils.file_util
- destFolder = os.path.dirname(zip_filename)
- for f in files:
- d = os.path.dirname(f)
- if d:
- mkpath(os.path.join(destFolder, d), verbose = verbose, dry_run = dry_run)
-
- copy_file(os.path.join(base_dir, f), os.path.join(destFolder, f), preserve_mode = 0, verbose = verbose, dry_run = dry_run)
-
- return '.'
-
-
-
- class FileSet:
-
- def __init__(self, iterable = None):
- self._dict = { }
- if iterable is not None:
- for arg in iterable:
- self.add(arg)
-
-
-
-
- def __repr__(self):
- return '<FileSet %s at %x>' % (self._dict.values(), id(self))
-
-
- def add(self, fname):
- self._dict[fname.upper()] = fname
-
-
- def remove(self, fname):
- del self._dict[fname.upper()]
-
-
- def __contains__(self, fname):
- return fname.upper() in self._dict.keys()
-
-
- def __getitem__(self, index):
- key = self._dict.keys()[index]
- return self._dict[key]
-
-
- def __len__(self):
- return len(self._dict)
-
-
- def copy(self):
- res = FileSet()
- res._dict.update(self._dict)
- return res
-
-
-
- def bin_depends(path, images, excluded_dlls):
- import py2exe_util
- warnings = FileSet()
- images = FileSet(images)
- dependents = FileSet()
- others = FileSet()
- while images:
- for image in images.copy():
- images.remove(image)
- if image not in dependents:
- dependents.add(image)
- abs_image = os.path.abspath(image)
- loadpath = os.path.dirname(abs_image) + ';' + path
- for result in py2exe_util.depends(image, loadpath).items():
-
- try:
- (dll, uses_import_module) = result
- if os.path.basename(dll).lower() not in excluded_dlls:
- if isSystemDLL(dll):
- others.add(dll)
- continue
-
- if dll not in images and dll not in dependents:
- images.add(dll)
- if uses_import_module:
- warnings.add(dll)
-
-
- continue
- except Exception:
- print >>sys.stderr, 'Error finding dependency for %s' % image
- raise
- continue
-
-
-
- None<EXCEPTION MATCH>Exception
-
- return (dependents, warnings, others)
-
- EXCLUDED_DLLS = ('advapi32.dll', 'comctl32.dll', 'comdlg32.dll', 'crtdll.dll', 'gdi32.dll', 'glu32.dll', 'opengl32.dll', 'imm32.dll', 'kernel32.dll', 'mfc42.dll', 'msvcirt.dll', 'msvcrt.dll', 'msvcrtd.dll', 'ntdll.dll', 'odbc32.dll', 'ole32.dll', 'oleaut32.dll', 'rpcrt4.dll', 'shell32.dll', 'shlwapi.dll', 'user32.dll', 'version.dll', 'winmm.dll', 'winspool.drv', 'ws2_32.dll', 'ws2help.dll', 'wsock32.dll', 'netapi32.dll', 'gdiplus.dll', 'msvcr90.dll', 'msvcp90.dll')
-
- def isSystemDLL(pathname):
- if os.path.basename(pathname).lower() in ('msvcr71.dll', 'msvcr71d.dll'):
- return 0
- if os.path.basename(pathname).lower() in EXCLUDED_DLLS:
- return 1
- import struct
- file = open(pathname, 'rb')
- if file.read(2) != 'MZ':
- raise Exception, 'Seems not to be an exe-file'
- file.read(2) != 'MZ'
- file.seek(60)
- pe_ofs = struct.unpack('i', file.read(4))[0]
- file.seek(pe_ofs)
- if file.read(4) != 'PE\x00\x00':
- raise Exception, ('Seems not to be an exe-file', pathname)
- file.read(4) != 'PE\x00\x00'
- file.read(48)
- imagebase = struct.unpack('I', file.read(4))[0]
- return not (imagebase < 1879048192)
-
-
- def byte_compile(py_files, optimize = 0, force = 0, target_dir = None, verbose = 1, dry_run = 0, direct = None):
- if direct is None:
- if __debug__:
- pass
- direct = optimize == 0
-
- if not direct:
- mktemp = mktemp
- import tempfile
- execute = execute
- import distutils.util
- script_name = mktemp('.py')
- if verbose:
- print "writing byte-compilation script '%s'" % script_name
-
- if not dry_run:
- script = open(script_name, 'w')
- script.write('from py2exe.build_exe import byte_compile\nfrom modulefinder import Module\nfiles = [\n')
- for f in py_files:
- script.write('Module(%s, %s, %s),\n' % (`f.__name__`, `f.__file__`, `f.__path__`))
-
- script.write(']\n')
- script.write('\nbyte_compile(files, optimize=%s, force=%s,\n target_dir=%s,\n verbose=%s, dry_run=0,\n direct=1)\n' % (`optimize`, `force`, `target_dir`, `verbose`))
- script.close()
-
- cmd = [
- sys.executable,
- script_name]
- if optimize == 1:
- cmd.insert(1, '-O')
- elif optimize == 2:
- cmd.insert(1, '-OO')
-
- spawn(cmd, verbose = verbose, dry_run = dry_run)
- execute(os.remove, (script_name,), 'removing %s' % script_name, verbose = verbose, dry_run = dry_run)
- else:
- compile = compile
- import py_compile
- mkpath = mkpath
- import distutils.dir_util
- newer = newer
- import distutils.dep_util
- copy_file = copy_file
- import distutils.file_util
- for file in py_files:
- cfile = file.__name__.replace('.', '\\')
- if file.__path__:
- if not __debug__ or 'c':
- pass
- dfile = cfile + '\\__init__.py' + 'o'
- elif not __debug__ or 'c':
- pass
- dfile = cfile + '.py' + 'o'
- if target_dir:
- cfile = os.path.join(target_dir, dfile)
-
- if force or newer(file.__file__, cfile):
- if verbose:
- print 'byte-compiling %s to %s' % (file.__file__, dfile)
-
- if not dry_run:
- mkpath(os.path.dirname(cfile))
- suffix = os.path.splitext(file.__file__)[1]
- if suffix in ('.py', '.pyw'):
- compile(file.__file__, cfile, dfile)
- elif suffix in _py_suffixes:
- copy_file(file.__file__, cfile, preserve_mode = 0)
- else:
- raise RuntimeError("Don't know how to handle %r" % file.__file__)
- suffix in ('.py', '.pyw')
- continue
- if verbose:
- print 'skipping byte-compilation of %s to %s' % (file.__file__, dfile)
- continue
-
- compiled_files = []
- for file in py_files:
- cfile = file.__name__.replace('.', '\\')
- if file.__path__:
- if not optimize or 'o':
- pass
- dfile = cfile + '\\__init__.py' + 'c'
- elif not optimize or 'o':
- pass
- dfile = cfile + '.py' + 'c'
- compiled_files.append(dfile)
-
- return compiled_files
-
-
- def collect_win32com_genpy(path, typelibs, verbose = 0, dry_run = 0):
- import win32com
- gencache = gencache
- makepy = makepy
- import win32com.client
- copy_file = copy_file
- import distutils.file_util
- old_gen_path = win32com.__gen_path__
- num = 0
-
- try:
- win32com.__gen_path__ = path
- win32com.gen_py.__path__ = [
- path]
- gencache.__init__()
- for info in typelibs:
- (guid, lcid, major, minor) = info[:4]
- fname_in = None
- if len(info) > 4:
- fname_in = info[4]
-
- if fname_in is not None:
- base = gencache.GetGeneratedFileName(guid, lcid, major, minor)
- fname_out = os.path.join(path, base) + '.py'
- copy_file(fname_in, fname_out, verbose = verbose, dry_run = dry_run)
- num += 1
- continue
-
- tlb_info = (guid, lcid, major, minor)
- makepy.GenerateFromTypeLibSpec(tlb_info, bForDemand = False)
- mod = gencache.GetModuleForTypelib(*tlb_info)
- for clsid, name in mod.CLSIDToPackageMap.items():
-
- try:
- gencache.GetModuleForCLSID(clsid)
- num += 1
- continue
- except ImportError:
- continue
-
-
-
-
- return num
- finally:
- win32com.__gen_path__ = old_gen_path
- win32com.gen_py.__path__ = [
- old_gen_path]
- gencache.__init__()
-
-
-
- def _chmod(file):
- os.chmod(file, 511)
-
-
- def _build_cmdtuple(path, cmdtuples):
- for f in os.listdir(path):
- real_f = os.path.join(path, f)
- if os.path.isdir(real_f) and not os.path.islink(real_f):
- _build_cmdtuple(real_f, cmdtuples)
- continue
- cmdtuples.append((_chmod, real_f))
- cmdtuples.append((os.remove, real_f))
-
- cmdtuples.append((os.rmdir, path))
-
-
- def force_remove_tree(directory, verbose = 0, dry_run = 0):
- import distutils
- grok_environment_error = grok_environment_error
- import distutils.util
- _path_created = distutils.dir_util._path_created
- if verbose:
- print "removing '%s' (and everything under it)" % directory
-
- if dry_run:
- return None
- cmdtuples = []
- _build_cmdtuple(directory, cmdtuples)
- for cmd in cmdtuples:
-
- try:
- cmd[0](cmd[1])
- abspath = os.path.abspath(cmd[1])
- if _path_created.has_key(abspath):
- del _path_created[abspath]
- continue
- except (IOError, OSError):
- dry_run
- exc = dry_run
- if verbose:
- print grok_environment_error(exc, 'error removing %s: ' % directory)
-
- verbose
-
-
-
-
-