home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 October / maximum-cd-2011-10.iso / DiscContents / digsby_setup.exe / lib / py2exe / build_exe.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-06-22  |  44.2 KB  |  1,445 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.6)
  3.  
  4. from distutils.core import Command
  5. from distutils.spawn import spawn
  6. from distutils.errors import *
  7. import sys
  8. import os
  9. import imp
  10. import types
  11. import stat
  12. import marshal
  13. import zipfile
  14. import sets
  15. import tempfile
  16. import struct
  17. is_win64 = struct.calcsize('P') == 8
  18.  
  19. def _is_debug_build():
  20.     for ext, _, _ in imp.get_suffixes():
  21.         if ext == '_d.pyd':
  22.             return True
  23.     
  24.     return False
  25.  
  26. is_debug_build = _is_debug_build()
  27. if is_debug_build:
  28.     python_dll = 'python%d%d_d.dll' % sys.version_info[:2]
  29. else:
  30.     python_dll = 'python%d%d.dll' % sys.version_info[:2]
  31. RT_BITMAP = 2
  32. _py_suffixes = [
  33.     '.py',
  34.     '.pyo',
  35.     '.pyc',
  36.     '.pyw']
  37. _c_suffixes = [] if _triple[2] == imp.C_EXTENSION else _[1]
  38.  
  39. def imp_find_module(name):
  40.     names = name.split('.')
  41.     path = None
  42.     for name in names:
  43.         result = imp.find_module(name, path)
  44.         path = [
  45.             result[1]]
  46.     
  47.     return result
  48.  
  49.  
  50. def fancy_split(str, sep = ','):
  51.     if str is None:
  52.         return []
  53.     if hasattr(str, 'split'):
  54.         return [ item.strip() for item in str.split(sep) ]
  55.     return str
  56.  
  57.  
  58. def ensure_unicode(text):
  59.     if isinstance(text, unicode):
  60.         return text
  61.     return text.decode('mbcs')
  62.  
  63. 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'
  64.  
  65. class Target:
  66.     
  67.     def __init__(self, **kw):
  68.         self.__dict__.update(kw)
  69.         m = self.__dict__.get('modules')
  70.         if m and type(m) in types.StringTypes:
  71.             self.modules = [
  72.                 m]
  73.         
  74.  
  75.     
  76.     def get_dest_base(self):
  77.         dest_base = getattr(self, 'dest_base', None)
  78.         if dest_base:
  79.             return dest_base
  80.         script = getattr(self, 'script', None)
  81.         if script:
  82.             return os.path.basename(os.path.splitext(script)[0])
  83.         modules = getattr(self, 'modules', None)
  84.         return modules[0].split('.')[-1]
  85.  
  86.     
  87.     def validate(self):
  88.         resources = getattr(self, 'bitmap_resources', []) + getattr(self, 'icon_resources', [])
  89.         for r_id, r_filename in resources:
  90.             if type(r_id) != type(0):
  91.                 raise DistutilsOptionError, 'Resource ID must be an integer'
  92.             type(r_id) != type(0)
  93.             if not os.path.isfile(r_filename):
  94.                 raise DistutilsOptionError, "Resource filename '%s' does not exist" % r_filename
  95.             os.path.isfile(r_filename)
  96.         
  97.  
  98.  
  99.  
  100. def FixupTargets(targets, default_attribute):
  101.     if not targets:
  102.         return targets
  103.     ret = []
  104.     for target_def in targets:
  105.         if type(target_def) in types.StringTypes:
  106.             target = Target(**{
  107.                 default_attribute: target_def })
  108.         else:
  109.             d = getattr(target_def, '__dict__', target_def)
  110.             if not d.has_key(default_attribute):
  111.                 raise DistutilsOptionError, "This target class requires an attribute '%s'" % default_attribute
  112.             d.has_key(default_attribute)
  113.             target = Target(**d)
  114.         target.validate()
  115.         ret.append(target)
  116.     
  117.     return ret
  118.  
  119.  
  120. class py2exe(Command):
  121.     description = ''
  122.     user_options = [
  123.         ('optimize=', 'O', 'optimization level: -O1 for "python -O", -O2 for "python -OO", and -O0 to disable [default: -O0]'),
  124.         ('dist-dir=', 'd', 'directory to put final built distributions in (default is dist)'),
  125.         ('excludes=', 'e', 'comma-separated list of modules to exclude'),
  126.         ('dll-excludes=', None, 'comma-separated list of DLLs to exclude'),
  127.         ('ignores=', None, 'comma-separated list of modules to ignore if they are not found'),
  128.         ('includes=', 'i', 'comma-separated list of modules to include'),
  129.         ('packages=', 'p', 'comma-separated list of packages to include'),
  130.         ('compressed', 'c', 'create a compressed zipfile'),
  131.         ('xref', 'x', 'create and show a module cross reference'),
  132.         ('bundle-files=', 'b', 'bundle dlls in the zipfile or the exe. Valid levels are 1, 2, or 3 (default)'),
  133.         ('skip-archive', None, 'do not place Python bytecode files in an archive, put them directly in the file system'),
  134.         ('ascii', 'a', 'do not automatically include encodings and codecs'),
  135.         ('custom-boot-script=', None, 'Python file that will be run when setting up the runtime environment')]
  136.     boolean_options = [
  137.         'compressed',
  138.         'xref',
  139.         'ascii',
  140.         'skip-archive',
  141.         'retain_times']
  142.     
  143.     def initialize_options(self):
  144.         self.xref = 0
  145.         self.compressed = 0
  146.         self.unbuffered = 0
  147.         self.optimize = 0
  148.         self.includes = None
  149.         self.excludes = None
  150.         self.ignores = None
  151.         self.packages = None
  152.         self.dist_dir = None
  153.         self.dll_excludes = 'msvcr90.dll msvcp90.dll'
  154.         self.typelibs = None
  155.         self.bundle_files = 3
  156.         self.skip_archive = 0
  157.         self.ascii = 0
  158.         self.custom_boot_script = None
  159.         self.retain_times = 0
  160.  
  161.     
  162.     def finalize_options(self):
  163.         self.optimize = int(self.optimize)
  164.         self.excludes = fancy_split(self.excludes)
  165.         self.includes = fancy_split(self.includes)
  166.         self.ignores = fancy_split(self.ignores)
  167.         self.bundle_files = int(self.bundle_files)
  168.         if self.bundle_files < 1 or self.bundle_files > 3:
  169.             raise DistutilsOptionError, 'bundle-files must be 1, 2, or 3, not %s' % self.bundle_files
  170.         self.bundle_files > 3
  171.         if is_win64 and self.bundle_files < 3:
  172.             raise DistutilsOptionError, 'bundle-files %d not yet supported on win64' % self.bundle_files
  173.         self.bundle_files < 3
  174.         if self.skip_archive:
  175.             if self.compressed:
  176.                 raise DistutilsOptionError, "can't compress when skipping archive"
  177.             self.compressed
  178.             if self.distribution.zipfile is None:
  179.                 raise DistutilsOptionError, 'zipfile cannot be None when skipping archive'
  180.             self.distribution.zipfile is None
  181.         
  182.         for m in self.includes:
  183.             if m in self.excludes:
  184.                 self.excludes.remove(m)
  185.                 continue
  186.         
  187.         self.packages = fancy_split(self.packages)
  188.         self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
  189.         self.dll_excludes = [ x.lower() for x in fancy_split(self.dll_excludes) ]
  190.  
  191.     
  192.     def run(self):
  193.         build = self.reinitialize_command('build')
  194.         build.run()
  195.         sys_old_path = sys.path[:]
  196.         if build.build_platlib is not None:
  197.             sys.path.insert(0, build.build_platlib)
  198.         
  199.         if build.build_lib is not None:
  200.             sys.path.insert(0, build.build_lib)
  201.         
  202.         
  203.         try:
  204.             self._run()
  205.         finally:
  206.             sys.path = sys_old_path
  207.  
  208.  
  209.     
  210.     def _run(self):
  211.         self.create_directories()
  212.         self.plat_prepare()
  213.         self.fixup_distribution()
  214.         dist = self.distribution
  215.         required_modules = []
  216.         for target in dist.com_server + dist.service + dist.ctypes_com_server:
  217.             required_modules.extend(target.modules)
  218.         
  219.         required_files = [ target.script for target in dist.windows + dist.console ]
  220.         mf = self.create_modulefinder()
  221.         for f in dist.isapi:
  222.             mf.load_file(f.script)
  223.         
  224.         orig_compile = compile
  225.         import __builtin__
  226.         
  227.         def my_compile(source, filename, *args):
  228.             
  229.             try:
  230.                 result = orig_compile(source, filename, *args)
  231.             except Exception:
  232.                 details = None
  233.                 raise DistutilsError, "compiling '%s' failed\n    %s: %s" % (filename, details.__class__.__name__, details)
  234.  
  235.             return result
  236.  
  237.         __builtin__.compile = my_compile
  238.         print '*** searching for required modules ***'
  239.         self.find_needed_modules(mf, required_files, required_modules)
  240.         print '*** parsing results ***'
  241.         (py_files, extensions, builtins) = self.parse_mf_results(mf)
  242.         if self.xref:
  243.             mf.create_xref()
  244.         
  245.         print '*** finding dlls needed ***'
  246.         dlls = self.find_dlls(extensions)
  247.         self.plat_finalize(mf.modules, py_files, extensions, dlls)
  248.         dlls = _[2]
  249.         print '*** create binaries ***'
  250.         self.create_binaries(py_files, extensions, dlls)
  251.         self.fix_badmodules(mf)
  252.         if self.other_depends:
  253.             print 
  254.             print '*** binary dependencies ***'
  255.             print 'Your executable(s) also depend on these dlls which are not included,'
  256.             print 'you may or may not need to distribute them.'
  257.             print 
  258.             print 'Make sure you have the license if you distribute any of them, and'
  259.             print "make sure you don't distribute files belonging to the operating system."
  260.             print 
  261.             for fnm in self.other_depends:
  262.                 print '  ', os.path.basename(fnm), '-', fnm.strip()
  263.             
  264.         
  265.  
  266.     
  267.     def create_modulefinder(self):
  268.         ReplacePackage = ReplacePackage
  269.         import modulefinder
  270.         ModuleFinder = ModuleFinder
  271.         import py2exe.mf
  272.         ReplacePackage('_xmlplus', 'xml')
  273.         return ModuleFinder(excludes = self.excludes)
  274.  
  275.     
  276.     def fix_badmodules(self, mf):
  277.         builtins = {
  278.             'clip_dndc': 'wxPython.clip_dnd',
  279.             'cmndlgsc': 'wxPython.cmndlgs',
  280.             'controls2c': 'wxPython.controls2',
  281.             'controlsc': 'wxPython.controls',
  282.             'eventsc': 'wxPython.events',
  283.             'filesysc': 'wxPython.filesys',
  284.             'fontsc': 'wxPython.fonts',
  285.             'framesc': 'wxPython.frames',
  286.             'gdic': 'wxPython.gdi',
  287.             'imagec': 'wxPython.image',
  288.             'mdic': 'wxPython.mdi',
  289.             'misc2c': 'wxPython.misc2',
  290.             'miscc': 'wxPython.misc',
  291.             'printfwc': 'wxPython.printfw',
  292.             'sizersc': 'wxPython.sizers',
  293.             'stattoolc': 'wxPython.stattool',
  294.             'streamsc': 'wxPython.streams',
  295.             'utilsc': 'wxPython.utils',
  296.             'windows2c': 'wxPython.windows2',
  297.             'windows3c': 'wxPython.windows3',
  298.             'windowsc': 'wxPython.windows' }
  299.         bad = mf.badmodules
  300.         for name in mf.any_missing():
  301.             if name in self.ignores:
  302.                 del bad[name]
  303.                 continue
  304.             
  305.             mod = builtins.get(name, None)
  306.             if mod is not None:
  307.                 if mod in bad[name] and bad[name] == {
  308.                     mod: 1 }:
  309.                     del bad[name]
  310.                 
  311.             bad[name] == {
  312.                 mod: 1 }
  313.         
  314.  
  315.     
  316.     def find_dlls(self, extensions):
  317.         dlls = [ item.__file__ for item in extensions ]
  318.         extra_path = []
  319.         (dlls, unfriendly_dlls, other_depends) = self.find_dependend_dlls(dlls, extra_path + sys.path, self.dll_excludes)
  320.         self.other_depends = other_depends
  321.         for item in extensions:
  322.             if item.__file__ in dlls:
  323.                 dlls.remove(item.__file__)
  324.                 continue
  325.             []
  326.         
  327.         return dlls
  328.  
  329.     
  330.     def create_directories(self):
  331.         bdist_base = self.get_finalized_command('bdist').bdist_base
  332.         self.bdist_dir = os.path.join(bdist_base, 'winexe')
  333.         collect_name = 'collect-%d.%d' % sys.version_info[:2]
  334.         self.collect_dir = os.path.abspath(os.path.join(self.bdist_dir, collect_name))
  335.         self.mkpath(self.collect_dir)
  336.         bundle_name = 'bundle-%d.%d' % sys.version_info[:2]
  337.         self.bundle_dir = os.path.abspath(os.path.join(self.bdist_dir, bundle_name))
  338.         self.mkpath(self.bundle_dir)
  339.         self.temp_dir = os.path.abspath(os.path.join(self.bdist_dir, 'temp'))
  340.         self.mkpath(self.temp_dir)
  341.         self.dist_dir = os.path.abspath(self.dist_dir)
  342.         self.mkpath(self.dist_dir)
  343.         if self.distribution.zipfile is None:
  344.             self.lib_dir = self.dist_dir
  345.         else:
  346.             self.lib_dir = os.path.join(self.dist_dir, os.path.dirname(self.distribution.zipfile))
  347.         self.mkpath(self.lib_dir)
  348.  
  349.     
  350.     def copy_extensions(self, extensions):
  351.         print '*** copy extensions ***'
  352.         for item in extensions:
  353.             src = item.__file__
  354.             if self.bundle_files > 2:
  355.                 dst = os.path.join(self.lib_dir, item.__pydfile__)
  356.                 self.copy_file(src, dst, preserve_mode = 0)
  357.                 self.lib_files.append(dst)
  358.                 continue
  359.             package = '\\'.join(item.__name__.split('.')[:-1])
  360.             if package:
  361.                 dst = os.path.join(package, os.path.basename(src))
  362.             else:
  363.                 dst = os.path.basename(src)
  364.             self.copy_file(src, os.path.join(self.collect_dir, dst), preserve_mode = 0)
  365.             self.compiled_files.append(dst)
  366.         
  367.  
  368.     
  369.     def copy_dlls(self, dlls):
  370.         print '*** copy dlls ***'
  371.         if self.bundle_files < 3:
  372.             self.copy_dlls_bundle_files(dlls)
  373.             return None
  374.         for dll in dlls:
  375.             base = os.path.basename(dll)
  376.             if base.lower() in self.dlls_in_exedir:
  377.                 dst = os.path.join(self.exe_dir, base)
  378.             else:
  379.                 dst = os.path.join(self.lib_dir, base)
  380.             (_, copied) = self.copy_file(dll, dst, preserve_mode = 0)
  381.             if not (self.dry_run) and copied and base.lower() == python_dll.lower():
  382.                 self.patch_python_dll_winver(dst)
  383.             
  384.             self.lib_files.append(dst)
  385.         
  386.  
  387.     
  388.     def copy_dlls_bundle_files(self, dlls):
  389.         for dll in dlls:
  390.             base = os.path.basename(dll)
  391.             if base.lower() in self.dlls_in_exedir:
  392.                 if base.lower() == python_dll.lower() and self.bundle_files < 2:
  393.                     dst = os.path.join(self.bundle_dir, base)
  394.                 else:
  395.                     dst = os.path.join(self.exe_dir, base)
  396.                 (_, copied) = self.copy_file(dll, dst, preserve_mode = 0)
  397.                 if not (self.dry_run) and copied and base.lower() == python_dll.lower():
  398.                     self.patch_python_dll_winver(dst)
  399.                 
  400.                 self.lib_files.append(dst)
  401.                 continue
  402.             
  403.             dst = os.path.join(self.collect_dir, os.path.basename(dll))
  404.             self.copy_file(dll, dst, preserve_mode = 0)
  405.             self.compiled_files.append(os.path.basename(dst))
  406.         
  407.  
  408.     
  409.     def create_binaries(self, py_files, extensions, dlls):
  410.         dist = self.distribution
  411.         print '*** byte compile python files ***'
  412.         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)
  413.         self.lib_files = []
  414.         self.console_exe_files = []
  415.         self.windows_exe_files = []
  416.         self.service_exe_files = []
  417.         self.comserver_files = []
  418.         self.copy_extensions(extensions)
  419.         self.copy_dlls(dlls)
  420.         if dist.zipfile is None:
  421.             (fd, archive_name) = tempfile.mkstemp()
  422.             os.close(fd)
  423.         else:
  424.             archive_name = os.path.join(self.lib_dir, os.path.basename(dist.zipfile))
  425.         arcname = self.make_lib_archive(archive_name, base_dir = self.collect_dir, files = self.compiled_files, verbose = self.verbose, dry_run = self.dry_run)
  426.         if dist.zipfile is not None:
  427.             self.lib_files.append(arcname)
  428.         
  429.         for target in self.distribution.isapi:
  430.             print '*** copy isapi support DLL ***'
  431.             import isapi
  432.             if not is_debug_build or 'PyISAPI_loader_d.dll':
  433.                 pass
  434.             src_name = 'PyISAPI_loader.dll'
  435.             src = os.path.join(isapi.__path__[0], src_name)
  436.             script_base = os.path.splitext(os.path.basename(target.script))[0]
  437.             dst = os.path.join(self.exe_dir, '_' + script_base + '.dll')
  438.             self.copy_file(src, dst, preserve_mode = 0)
  439.         
  440.         if self.distribution.has_data_files():
  441.             print '*** copy data files ***'
  442.             install_data = self.reinitialize_command('install_data')
  443.             install_data.install_dir = self.dist_dir
  444.             install_data.ensure_finalized()
  445.             install_data.run()
  446.             self.lib_files.extend(install_data.get_outputs())
  447.         
  448.         for target in dist.console:
  449.             dst = self.build_executable(target, self.get_console_template(), arcname, target.script)
  450.             self.console_exe_files.append(dst)
  451.         
  452.         for target in dist.windows:
  453.             dst = self.build_executable(target, self.get_windows_template(), arcname, target.script)
  454.             self.windows_exe_files.append(dst)
  455.         
  456.         for target in dist.service:
  457.             dst = self.build_service(target, self.get_service_template(), arcname)
  458.             self.service_exe_files.append(dst)
  459.         
  460.         for target in dist.isapi:
  461.             dst = self.build_isapi(target, self.get_isapi_template(), arcname)
  462.         
  463.         for target in dist.com_server:
  464.             if getattr(target, 'create_exe', True):
  465.                 dst = self.build_comserver(target, self.get_comexe_template(), arcname)
  466.                 self.comserver_files.append(dst)
  467.             
  468.             if getattr(target, 'create_dll', True):
  469.                 dst = self.build_comserver(target, self.get_comdll_template(), arcname)
  470.                 self.comserver_files.append(dst)
  471.                 continue
  472.         
  473.         for target in dist.ctypes_com_server:
  474.             dst = self.build_comserver(target, self.get_ctypes_comdll_template(), arcname, boot_script = 'ctypes_com_server')
  475.             self.comserver_files.append(dst)
  476.         
  477.         if dist.zipfile is None:
  478.             os.unlink(arcname)
  479.         elif self.bundle_files < 3 or self.compressed:
  480.             arcbytes = open(arcname, 'rb').read()
  481.             arcfile = open(arcname, 'wb')
  482.             if self.bundle_files < 2:
  483.                 print 'Adding %s to %s' % (python_dll, arcname)
  484.                 arcfile.write('<pythondll>')
  485.                 bytes = open(os.path.join(self.bundle_dir, python_dll), 'rb').read()
  486.                 arcfile.write(struct.pack('i', len(bytes)))
  487.                 arcfile.write(bytes)
  488.             
  489.             if self.compressed:
  490.                 zlib_file = imp.find_module('zlib')[0]
  491.                 if zlib_file:
  492.                     if not is_debug_build or '_d':
  493.                         pass
  494.                     print 'Adding zlib%s.pyd to %s' % ('', arcname)
  495.                     arcfile.write('<zlib.pyd>')
  496.                     bytes = zlib_file.read()
  497.                     arcfile.write(struct.pack('i', len(bytes)))
  498.                     arcfile.write(bytes)
  499.                 
  500.             
  501.             arcfile.write(arcbytes)
  502.         
  503.  
  504.     
  505.     def get_console_template(self):
  506.         if not is_debug_build or 'run_d.exe':
  507.             pass
  508.         return 'run.exe'
  509.  
  510.     
  511.     def get_windows_template(self):
  512.         if not is_debug_build or 'run_w_d.exe':
  513.             pass
  514.         return 'run_w.exe'
  515.  
  516.     
  517.     def get_service_template(self):
  518.         if not is_debug_build or 'run_d.exe':
  519.             pass
  520.         return 'run.exe'
  521.  
  522.     
  523.     def get_isapi_template(self):
  524.         if not is_debug_build or 'run_isapi_d.dll':
  525.             pass
  526.         return 'run_isapi.dll'
  527.  
  528.     
  529.     def get_comexe_template(self):
  530.         if not is_debug_build or 'run_w_d.exe':
  531.             pass
  532.         return 'run_w.exe'
  533.  
  534.     
  535.     def get_comdll_template(self):
  536.         if not is_debug_build or 'run_dll_d.dll':
  537.             pass
  538.         return 'run_dll.dll'
  539.  
  540.     
  541.     def get_ctypes_comdll_template(self):
  542.         if not is_debug_build or 'run_ctypes_dll_d.dll':
  543.             pass
  544.         return 'run_ctypes_dll.dll'
  545.  
  546.     
  547.     def fixup_distribution(self):
  548.         dist = self.distribution
  549.         dist.com_server = FixupTargets(dist.com_server, 'modules')
  550.         dist.ctypes_com_server = FixupTargets(dist.ctypes_com_server, 'modules')
  551.         dist.service = FixupTargets(dist.service, 'modules')
  552.         dist.windows = FixupTargets(dist.windows, 'script')
  553.         dist.console = FixupTargets(dist.console, 'script')
  554.         dist.isapi = FixupTargets(dist.isapi, 'script')
  555.         paths = sets.Set()
  556.         for target in dist.com_server + dist.service + dist.windows + dist.console + dist.isapi:
  557.             paths.add(os.path.dirname(target.get_dest_base()))
  558.         
  559.         if len(paths) > 1:
  560.             raise [], [] % [ p for p in paths ]
  561.         len(paths) > 1
  562.         if paths:
  563.             exe_dir = paths.pop()
  564.             if os.path.isabs(exe_dir):
  565.                 raise DistutilsOptionError, 'exe directory must be relative: %s' % exe_dir
  566.             os.path.isabs(exe_dir)
  567.             self.exe_dir = os.path.join(self.dist_dir, exe_dir)
  568.             self.mkpath(self.exe_dir)
  569.         else:
  570.             self.exe_dir = self.lib_dir
  571.  
  572.     
  573.     def get_boot_script(self, boot_type):
  574.         thisfile = sys.modules['py2exe.build_exe'].__file__
  575.         return os.path.join(os.path.dirname(thisfile), 'boot_' + boot_type + '.py')
  576.  
  577.     
  578.     def build_comserver(self, target, template, arcname, boot_script = 'com_servers'):
  579.         vars = {
  580.             'com_module_names': target.modules }
  581.         boot = self.get_boot_script(boot_script)
  582.         return self.build_executable(target, template, arcname, boot, vars)
  583.  
  584.     
  585.     def get_service_names(self, module_name):
  586.         __import__(module_name)
  587.         mod = sys.modules[module_name]
  588.         for name, klass in mod.__dict__.items():
  589.             if hasattr(klass, '_svc_name_'):
  590.                 break
  591.                 continue
  592.         else:
  593.             raise RuntimeError, 'No services in module'
  594.         deps = None
  595.         if hasattr(klass, '_svc_deps_'):
  596.             deps = klass._svc_deps_
  597.         
  598.         return (klass.__name__, klass._svc_name_, klass._svc_display_name_, deps)
  599.  
  600.     
  601.     def build_service(self, target, template, arcname):
  602.         cmdline_style = getattr(target, 'cmdline_style', 'py2exe')
  603.         if cmdline_style not in ('py2exe', 'pywin32', 'custom'):
  604.             raise RuntimeError, 'cmdline_handler invalid'
  605.         cmdline_style not in ('py2exe', 'pywin32', 'custom')
  606.         vars = {
  607.             'service_module_names': target.modules,
  608.             'cmdline_style': cmdline_style }
  609.         boot = self.get_boot_script('service')
  610.         return self.build_executable(target, template, arcname, boot, vars)
  611.  
  612.     
  613.     def build_isapi(self, target, template, arcname):
  614.         target_module = os.path.splitext(os.path.basename(target.script))[0]
  615.         vars = {
  616.             'isapi_module_name': target_module }
  617.         return self.build_executable(target, template, arcname, None, vars)
  618.  
  619.     
  620.     def build_executable(self, target, template, arcname, script, vars = { }):
  621.         add_resource = add_resource
  622.         add_icon = add_icon
  623.         import py2exe_util
  624.         ext = os.path.splitext(template)[1]
  625.         exe_base = target.get_dest_base()
  626.         exe_path = os.path.join(self.dist_dir, exe_base + ext)
  627.         parent_levels = len(os.path.normpath(exe_base).split(os.sep)) - 1
  628.         lib_leaf = self.lib_dir[len(self.dist_dir) + 1:]
  629.         relative_arcname = ('..' + os.sep) * parent_levels
  630.         if lib_leaf:
  631.             relative_arcname += lib_leaf + os.sep
  632.         
  633.         relative_arcname += os.path.basename(arcname)
  634.         src = os.path.join(os.path.dirname(__file__), template)
  635.         old_force = self.force
  636.         self.force = True
  637.         self.copy_file(src, exe_path, preserve_mode = 0)
  638.         self.force = old_force
  639.         os.chmod(exe_path, stat.S_IREAD | stat.S_IWRITE)
  640.         
  641.         try:
  642.             f = open(exe_path, 'a+b')
  643.             f.close()
  644.         except IOError:
  645.             why = None
  646.             print 'WARNING: File %s could not be opened - %s' % (exe_path, why)
  647.  
  648.         boot = self.get_boot_script('common')
  649.         boot_code = compile(file(boot, 'U').read(), os.path.abspath(boot), 'exec')
  650.         code_objects = [
  651.             boot_code]
  652.         if self.bundle_files < 3:
  653.             code_objects.append(compile('import zipextimporter; zipextimporter.install()', '<install zipextimporter>', 'exec'))
  654.         
  655.         for var_name, var_val in vars.items():
  656.             code_objects.append(compile('%s=%r\n' % (var_name, var_val), var_name, 'exec'))
  657.         
  658.         if self.custom_boot_script:
  659.             code_object = compile(file(self.custom_boot_script, 'U').read() + '\n', os.path.abspath(self.custom_boot_script), 'exec')
  660.             code_objects.append(code_object)
  661.         
  662.         if script:
  663.             code_object = compile(open(script, 'U').read() + '\n', os.path.basename(script), 'exec')
  664.             code_objects.append(code_object)
  665.         
  666.         code_bytes = marshal.dumps(code_objects)
  667.         if self.distribution.zipfile is None:
  668.             relative_arcname = ''
  669.         
  670.         si = struct.pack('iiii', 2018915346, self.optimize, self.unbuffered, len(code_bytes)) + relative_arcname + '\x00'
  671.         script_bytes = si + code_bytes + '\x00\x00'
  672.         self.announce('add script resource, %d bytes' % len(script_bytes))
  673.         if not self.dry_run:
  674.             add_resource(ensure_unicode(exe_path), script_bytes, u'PYTHONSCRIPT', 1, True)
  675.             if self.bundle_files < 2 and self.distribution.zipfile is None:
  676.                 dll_path = os.path.join(self.bundle_dir, python_dll)
  677.                 bytes = open(dll_path, 'rb').read()
  678.                 print 'Adding %s as resource to %s' % (python_dll, exe_path)
  679.                 add_resource(ensure_unicode(exe_path), bytes, ensure_unicode(python_dll).upper(), 1, False)
  680.             
  681.             if self.compressed and self.bundle_files < 3 and self.distribution.zipfile is None:
  682.                 zlib_file = imp.find_module('zlib')[0]
  683.                 if zlib_file:
  684.                     print 'Adding zlib.pyd as resource to %s' % exe_path
  685.                     zlib_bytes = zlib_file.read()
  686.                     add_resource(ensure_unicode(exe_path), zlib_bytes, u'ZLIB.PYD', 1, False)
  687.                 
  688.             
  689.         
  690.         bitmap_resources = getattr(target, 'bitmap_resources', [])
  691.         for bmp_id, bmp_filename in bitmap_resources:
  692.             bmp_data = open(bmp_filename, 'rb').read()
  693.             if not self.dry_run:
  694.                 add_resource(ensure_unicode(exe_path), bmp_data[14:], RT_BITMAP, bmp_id, False)
  695.                 continue
  696.         
  697.         icon_resources = getattr(target, 'icon_resources', [])
  698.         for ico_id, ico_filename in icon_resources:
  699.             if not self.dry_run:
  700.                 add_icon(ensure_unicode(exe_path), ensure_unicode(ico_filename), ico_id)
  701.                 continue
  702.         
  703.         for res_type, res_id, data in getattr(target, 'other_resources', []):
  704.             if not self.dry_run:
  705.                 if isinstance(res_type, basestring):
  706.                     res_type = ensure_unicode(res_type)
  707.                 
  708.                 add_resource(ensure_unicode(exe_path), data, res_type, res_id, False)
  709.                 continue
  710.         
  711.         typelib = getattr(target, 'typelib', None)
  712.         if typelib is not None:
  713.             data = open(typelib, 'rb').read()
  714.             add_resource(ensure_unicode(exe_path), data, u'TYPELIB', 1, False)
  715.         
  716.         self.add_versioninfo(target, exe_path)
  717.         if self.distribution.zipfile is None:
  718.             zip_data = open(arcname, 'rb').read()
  719.             open(exe_path, 'a+b').write(zip_data)
  720.         
  721.         return exe_path
  722.  
  723.     
  724.     def add_versioninfo(self, target, exe_path):
  725.         
  726.         def get(name, md = (self.distribution.metadata,)):
  727.             return getattr(target, name, getattr(md, name, None))
  728.  
  729.         version = get('version')
  730.         if version is None:
  731.             return None
  732.         Version = Version
  733.         RT_VERSION = RT_VERSION
  734.         VersionError = VersionError
  735.         import py2exe.resources.VersionInfo
  736.         if not get('product_version'):
  737.             pass
  738.         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)
  739.         
  740.         try:
  741.             bytes = version.resource_bytes()
  742.         except VersionError:
  743.             version is None
  744.             detail = version is None
  745.             self.warn('Version Info will not be included:\n  %s' % detail)
  746.             return None
  747.  
  748.         add_resource = add_resource
  749.         import py2exe_util
  750.         add_resource(ensure_unicode(exe_path), bytes, RT_VERSION, 1, False)
  751.  
  752.     
  753.     def patch_python_dll_winver(self, dll_name, new_winver = None):
  754.         StringTable = StringTable
  755.         RT_STRING = RT_STRING
  756.         import py2exe.resources.StringTables
  757.         add_resource = add_resource
  758.         import py2exe_util
  759.         if not new_winver and self.distribution.metadata.name:
  760.             pass
  761.         new_winver = 'py2exe'
  762.         if self.verbose:
  763.             print "setting sys.winver for '%s' to '%s'" % (dll_name, new_winver)
  764.         
  765.         if self.dry_run:
  766.             return None
  767.         st = os.stat(dll_name)
  768.         os.chmod(dll_name, stat.S_IREAD | stat.S_IWRITE)
  769.         
  770.         try:
  771.             f = open(dll_name, 'a+b')
  772.             f.close()
  773.         except IOError:
  774.             self.dry_run
  775.             why = self.dry_run
  776.             print 'WARNING: File %s could not be opened - %s' % (dll_name, why)
  777.         except:
  778.             self.dry_run
  779.  
  780.         s = StringTable()
  781.         s.add_string(1000, new_winver)
  782.         delete = True
  783.         for id, data in s.binary():
  784.             add_resource(ensure_unicode(dll_name), data, RT_STRING, id, delete)
  785.             delete = False
  786.         
  787.         os.utime(dll_name, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
  788.  
  789.     
  790.     def find_dependend_dlls(self, dlls, pypath, dll_excludes):
  791.         import py2exe_util
  792.         sysdir = py2exe_util.get_sysdir()
  793.         windir = py2exe_util.get_windir()
  794.         exedir = os.path.dirname(sys.executable)
  795.         syspath = os.environ['PATH']
  796.         loadpath = ';'.join([
  797.             exedir,
  798.             sysdir,
  799.             windir,
  800.             syspath])
  801.         loadpath = loadpath + ';' + ';'.join(pypath)
  802.         templates = sets.Set()
  803.         if self.distribution.console:
  804.             templates.add(self.get_console_template())
  805.         
  806.         if self.distribution.windows:
  807.             templates.add(self.get_windows_template())
  808.         
  809.         if self.distribution.service:
  810.             templates.add(self.get_service_template())
  811.         
  812.         for target in self.distribution.com_server:
  813.             if getattr(target, 'create_exe', True):
  814.                 templates.add(self.get_comexe_template())
  815.             
  816.             if getattr(target, 'create_dll', True):
  817.                 templates.add(self.get_comdll_template())
  818.                 continue
  819.         
  820.         templates = [ os.path.join(os.path.dirname(__file__), t) for t in templates ]
  821.         images = dlls + templates
  822.         self.announce('Resolving binary dependencies:')
  823.         (alldlls, warnings, other_depends) = bin_depends(loadpath, images + [
  824.             sys.executable], dll_excludes)
  825.         alldlls.remove(sys.executable)
  826.         for dll in alldlls:
  827.             self.announce('  %s' % dll)
  828.         
  829.         for t in templates:
  830.             alldlls.remove(t)
  831.         
  832.         return (alldlls, warnings, other_depends)
  833.  
  834.     
  835.     def get_hidden_imports(self):
  836.         return {
  837.             'time': [
  838.                 '_strptime'],
  839.             'cPickle': [
  840.                 'copy_reg'],
  841.             'parser': [
  842.                 'copy_reg'],
  843.             'codecs': [
  844.                 'encodings'],
  845.             'cStringIO': [
  846.                 'copy_reg'],
  847.             '_sre': [
  848.                 'copy',
  849.                 'string',
  850.                 'sre'] }
  851.  
  852.     
  853.     def parse_mf_results(self, mf):
  854.         for name, imports in self.get_hidden_imports().items():
  855.             if name in mf.modules.keys():
  856.                 for mod in imports:
  857.                     mf.import_hook(mod)
  858.                 
  859.         
  860.         tcl_src_dir = None
  861.         tcl_dst_dir = None
  862.         if 'Tkinter' in mf.modules.keys():
  863.             import Tkinter
  864.             import _tkinter
  865.             tk = _tkinter.create()
  866.             tcl_dir = tk.call('info', 'library')
  867.             tcl_src_dir = os.path.split(tcl_dir)[0]
  868.             tcl_dst_dir = os.path.join(self.lib_dir, 'tcl')
  869.             self.announce('Copying TCL files from %s...' % tcl_src_dir)
  870.             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))
  871.             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))
  872.             del tk
  873.             del _tkinter
  874.             del Tkinter
  875.         
  876.         py_files = []
  877.         extensions = []
  878.         builtins = []
  879.         for item in mf.modules.values():
  880.             if item.__name__ == '__main__':
  881.                 continue
  882.             
  883.             if self.bundle_files < 3 and item.__name__ in ('pythoncom', 'pywintypes'):
  884.                 continue
  885.             
  886.             src = item.__file__
  887.             if src:
  888.                 (base, ext) = os.path.splitext(src)
  889.                 suffix = ext
  890.                 if sys.platform.startswith('win') and ext in ('.dll', '.pyd') and base.endswith('_d'):
  891.                     suffix = '_d' + ext
  892.                 
  893.                 if suffix in _py_suffixes:
  894.                     py_files.append(item)
  895.                 elif suffix in _c_suffixes:
  896.                     extensions.append(item)
  897.                     if not self.bundle_files < 3:
  898.                         loader = self.create_loader(item)
  899.                         if loader:
  900.                             py_files.append(loader)
  901.                         
  902.                     
  903.                 else:
  904.                     raise RuntimeError("Don't know how to handle '%s'" % repr(src))
  905.             suffix in _py_suffixes
  906.             builtins.append(item.__name__)
  907.         
  908.         py_files.sort((lambda a, b: cmp(a.__file__, b.__file__)))
  909.         extensions.sort((lambda a, b: cmp(a.__file__, b.__file__)))
  910.         builtins.sort()
  911.         return (py_files, extensions, builtins)
  912.  
  913.     
  914.     def plat_finalize(self, modules, py_files, extensions, dlls):
  915.         if sys.platform == 'win32':
  916.             if 'pythoncom' in modules.keys():
  917.                 import pythoncom
  918.                 dlls.add(pythoncom.__file__)
  919.             
  920.             if 'pywintypes' in modules.keys():
  921.                 import pywintypes
  922.                 dlls.add(pywintypes.__file__)
  923.             
  924.             self.copy_w9xpopen(modules, dlls)
  925.         else:
  926.             raise DistutilsError, 'Platform %s not yet implemented' % sys.platform
  927.         return sys.platform == 'win32'
  928.  
  929.     
  930.     def copy_w9xpopen(self, modules, dlls):
  931.         if 'os' in modules.keys() or 'popen2' in modules.keys():
  932.             if is_debug_build:
  933.                 fname = os.path.join(os.path.dirname(sys.executable), 'w9xpopen_d.exe')
  934.             else:
  935.                 fname = os.path.join(os.path.dirname(sys.executable), 'w9xpopen.exe')
  936.             if os.path.exists(fname):
  937.                 dlls.add(fname)
  938.             
  939.         
  940.  
  941.     
  942.     def create_loader(self, item):
  943.         pathname = os.path.join(self.temp_dir, '%s.py' % item.__name__)
  944.         if self.bundle_files > 2:
  945.             fname = item.__name__ + os.path.splitext(item.__file__)[1]
  946.             item.__pydfile__ = fname
  947.         else:
  948.             fname = os.path.basename(item.__file__)
  949.         if self.verbose:
  950.             print "creating python loader for extension '%s' (%s -> %s)" % (item.__name__, item.__file__, fname)
  951.         
  952.         source = LOADER % fname
  953.         if not self.dry_run:
  954.             open(pathname, 'w').write(source)
  955.             if self.retain_times:
  956.                 st = os.stat(item.__file__)
  957.                 os.utime(pathname, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
  958.             
  959.         else:
  960.             return None
  961.         Module = Module
  962.         import modulefinder
  963.         return Module(item.__name__, pathname)
  964.  
  965.     
  966.     def plat_prepare(self):
  967.         self.includes.append('warnings')
  968.         if not self.ascii:
  969.             self.packages.append('encodings')
  970.             self.includes.append('codecs')
  971.         
  972.         if self.bundle_files < 3:
  973.             self.includes.append('zipextimporter')
  974.             self.excludes.append('_memimporter')
  975.         
  976.         if self.compressed:
  977.             self.includes.append('zlib')
  978.         
  979.         self.ignores.append('os.path')
  980.         if sys.platform == 'win32':
  981.             self.ignores += [
  982.                 'AL',
  983.                 'Audio_mac',
  984.                 'Carbon.File',
  985.                 'Carbon.Folder',
  986.                 'Carbon.Folders',
  987.                 'EasyDialogs',
  988.                 'MacOS',
  989.                 'Mailman',
  990.                 'SOCKS',
  991.                 'SUNAUDIODEV',
  992.                 '_dummy_threading',
  993.                 '_emx_link',
  994.                 '_xmlplus',
  995.                 '_xmlrpclib',
  996.                 'al',
  997.                 'bundlebuilder',
  998.                 'ce',
  999.                 'cl',
  1000.                 'dbm',
  1001.                 'dos',
  1002.                 'fcntl',
  1003.                 'gestalt',
  1004.                 'grp',
  1005.                 'ic',
  1006.                 'java.lang',
  1007.                 'mac',
  1008.                 'macfs',
  1009.                 'macostools',
  1010.                 'mkcwproject',
  1011.                 'org.python.core',
  1012.                 'os.path',
  1013.                 'os2',
  1014.                 'poll',
  1015.                 'posix',
  1016.                 'pwd',
  1017.                 'readline',
  1018.                 'riscos',
  1019.                 'riscosenviron',
  1020.                 'riscospath',
  1021.                 'rourl2path',
  1022.                 'sgi',
  1023.                 'sgmlop',
  1024.                 'sunaudiodev',
  1025.                 'termios',
  1026.                 'vms_lib']
  1027.             if not is_debug_build or '_d':
  1028.                 pass
  1029.             if not is_debug_build or 'd':
  1030.                 pass
  1031.             self.dlls_in_exedir = [
  1032.                 python_dll,
  1033.                 'w9xpopen%s.exe' % '',
  1034.                 'msvcr71%s.dll' % '']
  1035.         else:
  1036.             raise DistutilsError, 'Platform %s not yet implemented' % sys.platform
  1037.         return self
  1038.  
  1039.     
  1040.     def find_needed_modules(self, mf, files, modules):
  1041.         for mod in modules:
  1042.             mf.import_hook(mod)
  1043.         
  1044.         for path in files:
  1045.             mf.run_script(path)
  1046.         
  1047.         mf.run_script(self.get_boot_script('common'))
  1048.         if self.distribution.com_server:
  1049.             mf.run_script(self.get_boot_script('com_servers'))
  1050.         
  1051.         if self.distribution.ctypes_com_server:
  1052.             mf.run_script(self.get_boot_script('ctypes_com_server'))
  1053.         
  1054.         if self.distribution.service:
  1055.             mf.run_script(self.get_boot_script('service'))
  1056.         
  1057.         if self.custom_boot_script:
  1058.             mf.run_script(self.custom_boot_script)
  1059.         
  1060.         for mod in self.includes:
  1061.             if mod[-2:] == '.*':
  1062.                 mf.import_hook(mod[:-2], None, [
  1063.                     '*'])
  1064.                 continue
  1065.             
  1066.             try:
  1067.                 mf.import_hook(mod)
  1068.             continue
  1069.             except ImportError:
  1070.                 for exc in self.excludes:
  1071.                     if mod.startswith(exc):
  1072.                         print >>sys.stderr, 'Ignoring ImportError for %r' % mod
  1073.                         break
  1074.                         continue
  1075.                 else:
  1076.                     raise 
  1077.             
  1078.  
  1079.         
  1080.         for f in self.packages:
  1081.             
  1082.             def visit(arg, dirname, names):
  1083.                 if '__init__.py' in names:
  1084.                     arg.append(dirname)
  1085.                 
  1086.  
  1087.             mf.import_hook(f)
  1088.             if f in mf.modules:
  1089.                 module = mf.modules[f]
  1090.                 if module.__path__ is None:
  1091.                     paths = [
  1092.                         module.__file__]
  1093.                 else:
  1094.                     paths = module.__path__
  1095.             else:
  1096.                 
  1097.                 try:
  1098.                     paths = [
  1099.                         imp_find_module(f)[1]]
  1100.                 except ImportError:
  1101.                     self.warn('No package named %s' % f)
  1102.                     continue
  1103.  
  1104.             packages = []
  1105.             for path in paths:
  1106.                 os.path.walk(path, visit, packages)
  1107.                 for p in packages:
  1108.                     if p.startswith(path):
  1109.                         package = f + '.' + p[len(path) + 1:].replace('\\', '.')
  1110.                         mf.import_hook(package, None, [
  1111.                             '*'])
  1112.                         continue
  1113.                 
  1114.             
  1115.         
  1116.         return mf
  1117.  
  1118.     
  1119.     def make_lib_archive(self, zip_filename, base_dir, files, verbose = 0, dry_run = 0):
  1120.         mkpath = mkpath
  1121.         import distutils.dir_util
  1122.         if not self.skip_archive:
  1123.             mkpath(os.path.dirname(zip_filename), dry_run = dry_run)
  1124.             if self.compressed:
  1125.                 compression = zipfile.ZIP_DEFLATED
  1126.             else:
  1127.                 compression = zipfile.ZIP_STORED
  1128.             if not dry_run:
  1129.                 z = zipfile.ZipFile(zip_filename, 'w', compression = compression)
  1130.                 for f in files:
  1131.                     z.write(os.path.join(base_dir, f), f)
  1132.                 
  1133.                 z.close()
  1134.             
  1135.             return zip_filename
  1136.         copy_file = copy_file
  1137.         import distutils.file_util
  1138.         destFolder = os.path.dirname(zip_filename)
  1139.         for f in files:
  1140.             d = os.path.dirname(f)
  1141.             if d:
  1142.                 mkpath(os.path.join(destFolder, d), verbose = verbose, dry_run = dry_run)
  1143.             
  1144.             copy_file(os.path.join(base_dir, f), os.path.join(destFolder, f), preserve_mode = 0, verbose = verbose, dry_run = dry_run)
  1145.         
  1146.         return '.'
  1147.  
  1148.  
  1149.  
  1150. class FileSet:
  1151.     
  1152.     def __init__(self, iterable = None):
  1153.         self._dict = { }
  1154.         if iterable is not None:
  1155.             for arg in iterable:
  1156.                 self.add(arg)
  1157.             
  1158.         
  1159.  
  1160.     
  1161.     def __repr__(self):
  1162.         return '<FileSet %s at %x>' % (self._dict.values(), id(self))
  1163.  
  1164.     
  1165.     def add(self, fname):
  1166.         self._dict[fname.upper()] = fname
  1167.  
  1168.     
  1169.     def remove(self, fname):
  1170.         del self._dict[fname.upper()]
  1171.  
  1172.     
  1173.     def __contains__(self, fname):
  1174.         return fname.upper() in self._dict.keys()
  1175.  
  1176.     
  1177.     def __getitem__(self, index):
  1178.         key = self._dict.keys()[index]
  1179.         return self._dict[key]
  1180.  
  1181.     
  1182.     def __len__(self):
  1183.         return len(self._dict)
  1184.  
  1185.     
  1186.     def copy(self):
  1187.         res = FileSet()
  1188.         res._dict.update(self._dict)
  1189.         return res
  1190.  
  1191.  
  1192.  
  1193. def bin_depends(path, images, excluded_dlls):
  1194.     import py2exe_util
  1195.     warnings = FileSet()
  1196.     images = FileSet(images)
  1197.     dependents = FileSet()
  1198.     others = FileSet()
  1199.     while images:
  1200.         for image in images.copy():
  1201.             images.remove(image)
  1202.             if image not in dependents:
  1203.                 dependents.add(image)
  1204.                 abs_image = os.path.abspath(image)
  1205.                 loadpath = os.path.dirname(abs_image) + ';' + path
  1206.                 for result in py2exe_util.depends(image, loadpath).items():
  1207.                     
  1208.                     try:
  1209.                         (dll, uses_import_module) = result
  1210.                         if os.path.basename(dll).lower() not in excluded_dlls:
  1211.                             if isSystemDLL(dll):
  1212.                                 others.add(dll)
  1213.                                 continue
  1214.                             
  1215.                             if dll not in images and dll not in dependents:
  1216.                                 images.add(dll)
  1217.                                 if uses_import_module:
  1218.                                     warnings.add(dll)
  1219.                                 
  1220.                             
  1221.                     continue
  1222.                     except Exception:
  1223.                         print >>sys.stderr, 'Error finding dependency for %s' % image
  1224.                         raise 
  1225.                         continue
  1226.                     
  1227.  
  1228.                 
  1229.             None<EXCEPTION MATCH>Exception
  1230.         
  1231.     return (dependents, warnings, others)
  1232.  
  1233. 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')
  1234.  
  1235. def isSystemDLL(pathname):
  1236.     if os.path.basename(pathname).lower() in ('msvcr71.dll', 'msvcr71d.dll'):
  1237.         return 0
  1238.     if os.path.basename(pathname).lower() in EXCLUDED_DLLS:
  1239.         return 1
  1240.     import struct
  1241.     file = open(pathname, 'rb')
  1242.     if file.read(2) != 'MZ':
  1243.         raise Exception, 'Seems not to be an exe-file'
  1244.     file.read(2) != 'MZ'
  1245.     file.seek(60)
  1246.     pe_ofs = struct.unpack('i', file.read(4))[0]
  1247.     file.seek(pe_ofs)
  1248.     if file.read(4) != 'PE\x00\x00':
  1249.         raise Exception, ('Seems not to be an exe-file', pathname)
  1250.     file.read(4) != 'PE\x00\x00'
  1251.     file.read(48)
  1252.     imagebase = struct.unpack('I', file.read(4))[0]
  1253.     return not (imagebase < 1879048192)
  1254.  
  1255.  
  1256. def byte_compile(py_files, optimize = 0, force = 0, target_dir = None, verbose = 1, dry_run = 0, direct = None):
  1257.     if direct is None:
  1258.         if __debug__:
  1259.             pass
  1260.         direct = optimize == 0
  1261.     
  1262.     if not direct:
  1263.         mktemp = mktemp
  1264.         import tempfile
  1265.         execute = execute
  1266.         import distutils.util
  1267.         script_name = mktemp('.py')
  1268.         if verbose:
  1269.             print "writing byte-compilation script '%s'" % script_name
  1270.         
  1271.         if not dry_run:
  1272.             script = open(script_name, 'w')
  1273.             script.write('from py2exe.build_exe import byte_compile\nfrom modulefinder import Module\nfiles = [\n')
  1274.             for f in py_files:
  1275.                 script.write('Module(%s, %s, %s),\n' % (`f.__name__`, `f.__file__`, `f.__path__`))
  1276.             
  1277.             script.write(']\n')
  1278.             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`))
  1279.             script.close()
  1280.         
  1281.         cmd = [
  1282.             sys.executable,
  1283.             script_name]
  1284.         if optimize == 1:
  1285.             cmd.insert(1, '-O')
  1286.         elif optimize == 2:
  1287.             cmd.insert(1, '-OO')
  1288.         
  1289.         spawn(cmd, verbose = verbose, dry_run = dry_run)
  1290.         execute(os.remove, (script_name,), 'removing %s' % script_name, verbose = verbose, dry_run = dry_run)
  1291.     else:
  1292.         compile = compile
  1293.         import py_compile
  1294.         mkpath = mkpath
  1295.         import distutils.dir_util
  1296.         newer = newer
  1297.         import distutils.dep_util
  1298.         copy_file = copy_file
  1299.         import distutils.file_util
  1300.         for file in py_files:
  1301.             cfile = file.__name__.replace('.', '\\')
  1302.             if file.__path__:
  1303.                 if not __debug__ or 'c':
  1304.                     pass
  1305.                 dfile = cfile + '\\__init__.py' + 'o'
  1306.             elif not __debug__ or 'c':
  1307.                 pass
  1308.             dfile = cfile + '.py' + 'o'
  1309.             if target_dir:
  1310.                 cfile = os.path.join(target_dir, dfile)
  1311.             
  1312.             if force or newer(file.__file__, cfile):
  1313.                 if verbose:
  1314.                     print 'byte-compiling %s to %s' % (file.__file__, dfile)
  1315.                 
  1316.                 if not dry_run:
  1317.                     mkpath(os.path.dirname(cfile))
  1318.                     suffix = os.path.splitext(file.__file__)[1]
  1319.                     if suffix in ('.py', '.pyw'):
  1320.                         compile(file.__file__, cfile, dfile)
  1321.                     elif suffix in _py_suffixes:
  1322.                         copy_file(file.__file__, cfile, preserve_mode = 0)
  1323.                     else:
  1324.                         raise RuntimeError("Don't know how to handle %r" % file.__file__)
  1325.                 suffix in ('.py', '.pyw')
  1326.                 continue
  1327.             if verbose:
  1328.                 print 'skipping byte-compilation of %s to %s' % (file.__file__, dfile)
  1329.                 continue
  1330.         
  1331.     compiled_files = []
  1332.     for file in py_files:
  1333.         cfile = file.__name__.replace('.', '\\')
  1334.         if file.__path__:
  1335.             if not optimize or 'o':
  1336.                 pass
  1337.             dfile = cfile + '\\__init__.py' + 'c'
  1338.         elif not optimize or 'o':
  1339.             pass
  1340.         dfile = cfile + '.py' + 'c'
  1341.         compiled_files.append(dfile)
  1342.     
  1343.     return compiled_files
  1344.  
  1345.  
  1346. def collect_win32com_genpy(path, typelibs, verbose = 0, dry_run = 0):
  1347.     import win32com
  1348.     gencache = gencache
  1349.     makepy = makepy
  1350.     import win32com.client
  1351.     copy_file = copy_file
  1352.     import distutils.file_util
  1353.     old_gen_path = win32com.__gen_path__
  1354.     num = 0
  1355.     
  1356.     try:
  1357.         win32com.__gen_path__ = path
  1358.         win32com.gen_py.__path__ = [
  1359.             path]
  1360.         gencache.__init__()
  1361.         for info in typelibs:
  1362.             (guid, lcid, major, minor) = info[:4]
  1363.             fname_in = None
  1364.             if len(info) > 4:
  1365.                 fname_in = info[4]
  1366.             
  1367.             if fname_in is not None:
  1368.                 base = gencache.GetGeneratedFileName(guid, lcid, major, minor)
  1369.                 fname_out = os.path.join(path, base) + '.py'
  1370.                 copy_file(fname_in, fname_out, verbose = verbose, dry_run = dry_run)
  1371.                 num += 1
  1372.                 continue
  1373.             
  1374.             tlb_info = (guid, lcid, major, minor)
  1375.             makepy.GenerateFromTypeLibSpec(tlb_info, bForDemand = False)
  1376.             mod = gencache.GetModuleForTypelib(*tlb_info)
  1377.             for clsid, name in mod.CLSIDToPackageMap.items():
  1378.                 
  1379.                 try:
  1380.                     gencache.GetModuleForCLSID(clsid)
  1381.                     num += 1
  1382.                 continue
  1383.                 except ImportError:
  1384.                     continue
  1385.                 
  1386.  
  1387.             
  1388.         
  1389.         return num
  1390.     finally:
  1391.         win32com.__gen_path__ = old_gen_path
  1392.         win32com.gen_py.__path__ = [
  1393.             old_gen_path]
  1394.         gencache.__init__()
  1395.  
  1396.  
  1397.  
  1398. def _chmod(file):
  1399.     os.chmod(file, 511)
  1400.  
  1401.  
  1402. def _build_cmdtuple(path, cmdtuples):
  1403.     for f in os.listdir(path):
  1404.         real_f = os.path.join(path, f)
  1405.         if os.path.isdir(real_f) and not os.path.islink(real_f):
  1406.             _build_cmdtuple(real_f, cmdtuples)
  1407.             continue
  1408.         cmdtuples.append((_chmod, real_f))
  1409.         cmdtuples.append((os.remove, real_f))
  1410.     
  1411.     cmdtuples.append((os.rmdir, path))
  1412.  
  1413.  
  1414. def force_remove_tree(directory, verbose = 0, dry_run = 0):
  1415.     import distutils
  1416.     grok_environment_error = grok_environment_error
  1417.     import distutils.util
  1418.     _path_created = distutils.dir_util._path_created
  1419.     if verbose:
  1420.         print "removing '%s' (and everything under it)" % directory
  1421.     
  1422.     if dry_run:
  1423.         return None
  1424.     cmdtuples = []
  1425.     _build_cmdtuple(directory, cmdtuples)
  1426.     for cmd in cmdtuples:
  1427.         
  1428.         try:
  1429.             cmd[0](cmd[1])
  1430.             abspath = os.path.abspath(cmd[1])
  1431.             if _path_created.has_key(abspath):
  1432.                 del _path_created[abspath]
  1433.         continue
  1434.         except (IOError, OSError):
  1435.             dry_run
  1436.             exc = dry_run
  1437.             if verbose:
  1438.                 print grok_environment_error(exc, 'error removing %s: ' % directory)
  1439.             
  1440.             verbose
  1441.         
  1442.  
  1443.     
  1444.  
  1445.