home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 May / maximum-cd-2010-05.iso / DiscContents / boxee-0.9.20.10711.exe / system / python / Lib / imputil.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-07-20  |  14.8 KB  |  534 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. '''
  5. Import utilities
  6.  
  7. Exported classes:
  8.     ImportManager   Manage the import process
  9.  
  10.     Importer        Base class for replacing standard import functions
  11.     BuiltinImporter Emulate the import mechanism for builtin and frozen modules
  12.  
  13.     DynLoadSuffixImporter
  14. '''
  15. import imp
  16. import sys
  17. import __builtin__
  18. import struct
  19. import marshal
  20. __all__ = [
  21.     'ImportManager',
  22.     'Importer',
  23.     'BuiltinImporter']
  24. _StringType = type('')
  25. _ModuleType = type(sys)
  26.  
  27. class ImportManager:
  28.     '''Manage the import process.'''
  29.     
  30.     def install(self, namespace = vars(__builtin__)):
  31.         '''Install this ImportManager into the specified namespace.'''
  32.         if isinstance(namespace, _ModuleType):
  33.             namespace = vars(namespace)
  34.         
  35.         self.previous_importer = namespace['__import__']
  36.         self.namespace = namespace
  37.         namespace['__import__'] = self._import_hook
  38.  
  39.     
  40.     def uninstall(self):
  41.         '''Restore the previous import mechanism.'''
  42.         self.namespace['__import__'] = self.previous_importer
  43.  
  44.     
  45.     def add_suffix(self, suffix, importFunc):
  46.         self.fs_imp.add_suffix(suffix, importFunc)
  47.  
  48.     clsFilesystemImporter = None
  49.     
  50.     def __init__(self, fs_imp = None):
  51.         if not _os_stat:
  52.             _os_bootstrap()
  53.         
  54.         if fs_imp is None:
  55.             if not self.clsFilesystemImporter:
  56.                 pass
  57.             cls = _FilesystemImporter
  58.             fs_imp = cls()
  59.         
  60.         self.fs_imp = fs_imp
  61.         for desc in imp.get_suffixes():
  62.             if desc[2] == imp.C_EXTENSION:
  63.                 self.add_suffix(desc[0], DynLoadSuffixImporter(desc).import_file)
  64.                 continue
  65.         
  66.         self.add_suffix('.py', py_suffix_importer)
  67.  
  68.     
  69.     def _import_hook(self, fqname, globals = None, locals = None, fromlist = None):
  70.         '''Python calls this hook to locate and import a module.'''
  71.         parts = fqname.split('.')
  72.         parent = self._determine_import_context(globals)
  73.         if parent:
  74.             module = parent.__importer__._do_import(parent, parts, fromlist)
  75.             if module:
  76.                 return module
  77.             
  78.         
  79.         
  80.         try:
  81.             top_module = sys.modules[parts[0]]
  82.         except KeyError:
  83.             top_module = self._import_top_module(parts[0])
  84.             if not top_module:
  85.                 raise ImportError, 'No module named ' + fqname
  86.             
  87.         except:
  88.             top_module
  89.  
  90.         if len(parts) == 1:
  91.             if not fromlist:
  92.                 return top_module
  93.             
  94.             if not top_module.__dict__.get('__ispkg__'):
  95.                 return top_module
  96.             
  97.         
  98.         importer = top_module.__dict__.get('__importer__')
  99.         if importer:
  100.             return importer._finish_import(top_module, parts[1:], fromlist)
  101.         
  102.         if len(parts) == 2 and hasattr(top_module, parts[1]):
  103.             if fromlist:
  104.                 return getattr(top_module, parts[1])
  105.             else:
  106.                 return top_module
  107.         
  108.         raise ImportError, 'No module named ' + fqname
  109.  
  110.     
  111.     def _determine_import_context(self, globals):
  112.         '''Returns the context in which a module should be imported.
  113.  
  114.         The context could be a loaded (package) module and the imported module
  115.         will be looked for within that package. The context could also be None,
  116.         meaning there is no context -- the module should be looked for as a
  117.         "top-level" module.
  118.         '''
  119.         if not globals or not globals.get('__importer__'):
  120.             return None
  121.         
  122.         parent_fqname = globals['__name__']
  123.         if globals['__ispkg__']:
  124.             parent = sys.modules[parent_fqname]
  125.             return parent
  126.         
  127.         i = parent_fqname.rfind('.')
  128.         if i == -1:
  129.             return None
  130.         
  131.         parent_fqname = parent_fqname[:i]
  132.         parent = sys.modules[parent_fqname]
  133.         return parent
  134.  
  135.     
  136.     def _import_top_module(self, name):
  137.         for item in sys.path:
  138.             if isinstance(item, _StringType):
  139.                 module = self.fs_imp.import_from_dir(item, name)
  140.             else:
  141.                 module = item.import_top(name)
  142.             if module:
  143.                 return module
  144.                 continue
  145.         
  146.  
  147.     
  148.     def _reload_hook(self, module):
  149.         '''Python calls this hook to reload a module.'''
  150.         importer = module.__dict__.get('__importer__')
  151.         if not importer:
  152.             pass
  153.         
  154.         raise SystemError, 'reload not yet implemented'
  155.  
  156.  
  157.  
  158. class Importer:
  159.     '''Base class for replacing standard import functions.'''
  160.     
  161.     def import_top(self, name):
  162.         '''Import a top-level module.'''
  163.         return self._import_one(None, name, name)
  164.  
  165.     
  166.     def _finish_import(self, top, parts, fromlist):
  167.         bottom = self._load_tail(top, parts)
  168.         if not fromlist:
  169.             return top
  170.         
  171.         if bottom.__ispkg__:
  172.             self._import_fromlist(bottom, fromlist)
  173.         
  174.         return bottom
  175.  
  176.     
  177.     def _import_one(self, parent, modname, fqname):
  178.         '''Import a single module.'''
  179.         
  180.         try:
  181.             return sys.modules[fqname]
  182.         except KeyError:
  183.             pass
  184.  
  185.         result = self.get_code(parent, modname, fqname)
  186.         if result is None:
  187.             return None
  188.         
  189.         module = self._process_result(result, fqname)
  190.         if parent:
  191.             setattr(parent, modname, module)
  192.         
  193.         return module
  194.  
  195.     
  196.     def _process_result(self, .2, fqname):
  197.         (ispkg, code, values) = .2
  198.         is_module = isinstance(code, _ModuleType)
  199.         if is_module:
  200.             module = code
  201.         else:
  202.             module = imp.new_module(fqname)
  203.         module.__importer__ = self
  204.         module.__ispkg__ = ispkg
  205.         module.__dict__.update(values)
  206.         sys.modules[fqname] = module
  207.         if not is_module:
  208.             
  209.             try:
  210.                 exec code in module.__dict__
  211.             if fqname in sys.modules:
  212.                 del sys.modules[fqname]
  213.             
  214.  
  215.             raise 
  216.         
  217.         is_module
  218.         module = sys.modules[fqname]
  219.         module.__name__ = fqname
  220.         return module
  221.  
  222.     
  223.     def _load_tail(self, m, parts):
  224.         '''Import the rest of the modules, down from the top-level module.
  225.  
  226.         Returns the last module in the dotted list of modules.
  227.         '''
  228.         for part in parts:
  229.             fqname = '%s.%s' % (m.__name__, part)
  230.             m = self._import_one(m, part, fqname)
  231.             if not m:
  232.                 raise ImportError, 'No module named ' + fqname
  233.                 continue
  234.         
  235.         return m
  236.  
  237.     
  238.     def _import_fromlist(self, package, fromlist):
  239.         '''Import any sub-modules in the "from" list.'''
  240.         if '*' in fromlist:
  241.             fromlist = list(fromlist) + list(package.__dict__.get('__all__', []))
  242.         
  243.         for sub in fromlist:
  244.             if sub != '*' and not hasattr(package, sub):
  245.                 subname = '%s.%s' % (package.__name__, sub)
  246.                 submod = self._import_one(package, sub, subname)
  247.                 if not submod:
  248.                     raise ImportError, 'cannot import name ' + subname
  249.                 
  250.             submod
  251.         
  252.  
  253.     
  254.     def _do_import(self, parent, parts, fromlist):
  255.         '''Attempt to import the module relative to parent.
  256.  
  257.         This method is used when the import context specifies that <self>
  258.         imported the parent module.
  259.         '''
  260.         top_name = parts[0]
  261.         top_fqname = parent.__name__ + '.' + top_name
  262.         top_module = self._import_one(parent, top_name, top_fqname)
  263.         if not top_module:
  264.             return None
  265.         
  266.         return self._finish_import(top_module, parts[1:], fromlist)
  267.  
  268.     
  269.     def get_code(self, parent, modname, fqname):
  270.         '''Find and retrieve the code for the given module.
  271.  
  272.         parent specifies a parent module to define a context for importing. It
  273.         may be None, indicating no particular context for the search.
  274.  
  275.         modname specifies a single module (not dotted) within the parent.
  276.  
  277.         fqname specifies the fully-qualified module name. This is a
  278.         (potentially) dotted name from the "root" of the module namespace
  279.         down to the modname.
  280.         If there is no parent, then modname==fqname.
  281.  
  282.         This method should return None, or a 3-tuple.
  283.  
  284.         * If the module was not found, then None should be returned.
  285.  
  286.         * The first item of the 2- or 3-tuple should be the integer 0 or 1,
  287.             specifying whether the module that was found is a package or not.
  288.  
  289.         * The second item is the code object for the module (it will be
  290.             executed within the new module\'s namespace). This item can also
  291.             be a fully-loaded module object (e.g. loaded from a shared lib).
  292.  
  293.         * The third item is a dictionary of name/value pairs that will be
  294.             inserted into new module before the code object is executed. This
  295.             is provided in case the module\'s code expects certain values (such
  296.             as where the module was found). When the second item is a module
  297.             object, then these names/values will be inserted *after* the module
  298.             has been loaded/initialized.
  299.         '''
  300.         raise RuntimeError, 'get_code not implemented'
  301.  
  302.  
  303. if not __debug__ or 'c':
  304.     pass
  305. _suffix_char = 'o'
  306. _suffix = '.py' + _suffix_char
  307.  
  308. def _compile(pathname, timestamp):
  309.     """Compile (and cache) a Python source file.
  310.  
  311.     The file specified by <pathname> is compiled to a code object and
  312.     returned.
  313.  
  314.     Presuming the appropriate privileges exist, the bytecodes will be
  315.     saved back to the filesystem for future imports. The source file's
  316.     modification timestamp must be provided as a Long value.
  317.     """
  318.     codestring = open(pathname, 'rU').read()
  319.     if codestring and codestring[-1] != '\n':
  320.         codestring = codestring + '\n'
  321.     
  322.     code = __builtin__.compile(codestring, pathname, 'exec')
  323.     
  324.     try:
  325.         f = open(pathname + _suffix_char, 'wb')
  326.     except IOError:
  327.         pass
  328.  
  329.     f.write('\x00\x00\x00\x00')
  330.     f.write(struct.pack('<I', timestamp))
  331.     marshal.dump(code, f)
  332.     f.flush()
  333.     f.seek(0, 0)
  334.     f.write(imp.get_magic())
  335.     f.close()
  336.     return code
  337.  
  338. _os_stat = None
  339. _os_path_join = None
  340.  
  341. def _os_bootstrap():
  342.     """Set up 'os' module replacement functions for use during import bootstrap."""
  343.     global _os_stat, _os_path_join
  344.     names = sys.builtin_module_names
  345.     join = None
  346.     if 'posix' in names:
  347.         sep = '/'
  348.         stat = stat
  349.         import posix
  350.     elif 'nt' in names:
  351.         sep = '\\'
  352.         stat = stat
  353.         import nt
  354.     elif 'dos' in names:
  355.         sep = '\\'
  356.         stat = stat
  357.         import dos
  358.     elif 'os2' in names:
  359.         sep = '\\'
  360.         stat = stat
  361.         import os2
  362.     elif 'mac' in names:
  363.         stat = stat
  364.         import mac
  365.         
  366.         def join(a, b):
  367.             if a == '':
  368.                 return b
  369.             
  370.             if ':' not in a:
  371.                 a = ':' + a
  372.             
  373.             if a[-1:] != ':':
  374.                 a = a + ':'
  375.             
  376.             return a + b
  377.  
  378.     else:
  379.         raise ImportError, 'no os specific module found'
  380.     if join is None:
  381.         
  382.         def join(a, b, sep = sep):
  383.             if a == '':
  384.                 return b
  385.             
  386.             lastchar = a[-1:]
  387.             if lastchar == '/' or lastchar == sep:
  388.                 return a + b
  389.             
  390.             return a + sep + b
  391.  
  392.     
  393.     _os_stat = stat
  394.     _os_path_join = join
  395.  
  396.  
  397. def _os_path_isdir(pathname):
  398.     '''Local replacement for os.path.isdir().'''
  399.     
  400.     try:
  401.         s = _os_stat(pathname)
  402.     except OSError:
  403.         return None
  404.  
  405.     return s.st_mode & 61440 == 16384
  406.  
  407.  
  408. def _timestamp(pathname):
  409.     '''Return the file modification time as a Long.'''
  410.     
  411.     try:
  412.         s = _os_stat(pathname)
  413.     except OSError:
  414.         return None
  415.  
  416.     return long(s.st_mtime)
  417.  
  418.  
  419. class BuiltinImporter(Importer):
  420.     
  421.     def get_code(self, parent, modname, fqname):
  422.         if parent:
  423.             return None
  424.         
  425.         if imp.is_builtin(modname):
  426.             type = imp.C_BUILTIN
  427.         elif imp.is_frozen(modname):
  428.             type = imp.PY_FROZEN
  429.         else:
  430.             return None
  431.         module = imp.load_module(modname, None, modname, ('', '', type))
  432.         return (0, module, { })
  433.  
  434.  
  435.  
  436. class _FilesystemImporter(Importer):
  437.     
  438.     def __init__(self):
  439.         self.suffixes = []
  440.  
  441.     
  442.     def add_suffix(self, suffix, importFunc):
  443.         self.suffixes.append((suffix, importFunc))
  444.  
  445.     
  446.     def import_from_dir(self, dir, fqname):
  447.         result = self._import_pathname(_os_path_join(dir, fqname), fqname)
  448.         if result:
  449.             return self._process_result(result, fqname)
  450.         
  451.  
  452.     
  453.     def get_code(self, parent, modname, fqname):
  454.         return self._import_pathname(_os_path_join(parent.__pkgdir__, modname), fqname)
  455.  
  456.     
  457.     def _import_pathname(self, pathname, fqname):
  458.         if _os_path_isdir(pathname):
  459.             result = self._import_pathname(_os_path_join(pathname, '__init__'), fqname)
  460.             if result:
  461.                 values = result[2]
  462.                 values['__pkgdir__'] = pathname
  463.                 values['__path__'] = [
  464.                     pathname]
  465.                 return (1, result[1], values)
  466.             
  467.             return None
  468.         
  469.         for suffix, importFunc in self.suffixes:
  470.             filename = pathname + suffix
  471.             
  472.             try:
  473.                 finfo = _os_stat(filename)
  474.             except OSError:
  475.                 continue
  476.  
  477.             return importFunc(filename, finfo, fqname)
  478.         
  479.  
  480.  
  481.  
  482. def py_suffix_importer(filename, finfo, fqname):
  483.     file = filename[:-3] + _suffix
  484.     t_py = long(finfo[8])
  485.     t_pyc = _timestamp(file)
  486.     code = None
  487.     if t_pyc is not None and t_pyc >= t_py:
  488.         f = open(file, 'rb')
  489.         if f.read(4) == imp.get_magic():
  490.             t = struct.unpack('<I', f.read(4))[0]
  491.             if t == t_py:
  492.                 code = marshal.load(f)
  493.             
  494.         
  495.         f.close()
  496.     
  497.     if code is None:
  498.         file = filename
  499.         code = _compile(file, t_py)
  500.     
  501.     return (0, code, {
  502.         '__file__': file })
  503.  
  504.  
  505. class DynLoadSuffixImporter:
  506.     
  507.     def __init__(self, desc):
  508.         self.desc = desc
  509.  
  510.     
  511.     def import_file(self, filename, finfo, fqname):
  512.         fp = open(filename, self.desc[1])
  513.         module = imp.load_module(fqname, fp, filename, self.desc)
  514.         module.__file__ = filename
  515.         return (0, module, { })
  516.  
  517.  
  518.  
  519. def _print_importers():
  520.     items = sys.modules.items()
  521.     items.sort()
  522.     for name, module in items:
  523.         if module:
  524.             print name, module.__dict__.get('__importer__', '-- no importer')
  525.             continue
  526.         print name, '-- non-existent module'
  527.     
  528.  
  529.  
  530. def _test_revamp():
  531.     ImportManager().install()
  532.     sys.path.insert(0, BuiltinImporter())
  533.  
  534.