home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / ihooks.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  26.0 KB  |  652 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''Import hook support.
  5.  
  6. Consistent use of this module will make it possible to change the
  7. different mechanisms involved in loading modules independently.
  8.  
  9. While the built-in module imp exports interfaces to the built-in
  10. module searching and loading algorithm, and it is possible to replace
  11. the built-in function __import__ in order to change the semantics of
  12. the import statement, until now it has been difficult to combine the
  13. effect of different __import__ hacks, like loading modules from URLs
  14. by rimport.py, or restricted execution by rexec.py.
  15.  
  16. This module defines three new concepts:
  17.  
  18. 1) A "file system hooks" class provides an interface to a filesystem.
  19.  
  20. One hooks class is defined (Hooks), which uses the interface provided
  21. by standard modules os and os.path.  It should be used as the base
  22. class for other hooks classes.
  23.  
  24. 2) A "module loader" class provides an interface to to search for a
  25. module in a search path and to load it.  It defines a method which
  26. searches for a module in a single directory; by overriding this method
  27. one can redefine the details of the search.  If the directory is None,
  28. built-in and frozen modules are searched instead.
  29.  
  30. Two module loader class are defined, both implementing the search
  31. strategy used by the built-in __import__ function: ModuleLoader uses
  32. the imp module\'s find_module interface, while HookableModuleLoader
  33. uses a file system hooks class to interact with the file system.  Both
  34. use the imp module\'s load_* interfaces to actually load the module.
  35.  
  36. 3) A "module importer" class provides an interface to import a
  37. module, as well as interfaces to reload and unload a module.  It also
  38. provides interfaces to install and uninstall itself instead of the
  39. default __import__ and reload (and unload) functions.
  40.  
  41. One module importer class is defined (ModuleImporter), which uses a
  42. module loader instance passed in (by default HookableModuleLoader is
  43. instantiated).
  44.  
  45. The classes defined here should be used as base classes for extended
  46. functionality along those lines.
  47.  
  48. If a module importer class supports dotted names, its import_module()
  49. must return a different value depending on whether it is called on
  50. behalf of a "from ... import ..." statement or not.  (This is caused
  51. by the way the __import__ hook is used by the Python interpreter.)  It
  52. would also do wise to install a different version of reload().
  53.  
  54. '''
  55. import __builtin__
  56. import imp
  57. import os
  58. import sys
  59. __all__ = [
  60.     'BasicModuleLoader',
  61.     'Hooks',
  62.     'ModuleLoader',
  63.     'FancyModuleLoader',
  64.     'BasicModuleImporter',
  65.     'ModuleImporter',
  66.     'install',
  67.     'uninstall']
  68. VERBOSE = 0
  69. from imp import C_EXTENSION, PY_SOURCE, PY_COMPILED
  70. from imp import C_BUILTIN, PY_FROZEN, PKG_DIRECTORY
  71. BUILTIN_MODULE = C_BUILTIN
  72. FROZEN_MODULE = PY_FROZEN
  73.  
  74. class _Verbose:
  75.     
  76.     def __init__(self, verbose = VERBOSE):
  77.         self.verbose = verbose
  78.  
  79.     
  80.     def get_verbose(self):
  81.         return self.verbose
  82.  
  83.     
  84.     def set_verbose(self, verbose):
  85.         self.verbose = verbose
  86.  
  87.     
  88.     def note(self, *args):
  89.         if self.verbose:
  90.             apply(self.message, args)
  91.         
  92.  
  93.     
  94.     def message(self, format, *args):
  95.         if args:
  96.             print format % args
  97.         else:
  98.             print format
  99.  
  100.  
  101.  
  102. class BasicModuleLoader(_Verbose):
  103.     """Basic module loader.
  104.  
  105.     This provides the same functionality as built-in import.  It
  106.     doesn't deal with checking sys.modules -- all it provides is
  107.     find_module() and a load_module(), as well as find_module_in_dir()
  108.     which searches just one directory, and can be overridden by a
  109.     derived class to change the module search algorithm when the basic
  110.     dependency on sys.path is unchanged.
  111.  
  112.     The interface is a little more convenient than imp's:
  113.     find_module(name, [path]) returns None or 'stuff', and
  114.     load_module(name, stuff) loads the module.
  115.  
  116.     """
  117.     
  118.     def find_module(self, name, path = None):
  119.         if path is None:
  120.             path = [
  121.                 None] + self.default_path()
  122.         
  123.         for dir in path:
  124.             stuff = self.find_module_in_dir(name, dir)
  125.             if stuff:
  126.                 return stuff
  127.             
  128.         
  129.         return None
  130.  
  131.     
  132.     def default_path(self):
  133.         return sys.path
  134.  
  135.     
  136.     def find_module_in_dir(self, name, dir):
  137.         if dir is None:
  138.             return self.find_builtin_module(name)
  139.         else:
  140.             
  141.             try:
  142.                 return imp.find_module(name, [
  143.                     dir])
  144.             except ImportError:
  145.                 return None
  146.  
  147.  
  148.     
  149.     def find_builtin_module(self, name):
  150.         if imp.is_builtin(name):
  151.             return (None, '', ('', '', BUILTIN_MODULE))
  152.         
  153.         if imp.is_frozen(name):
  154.             return (None, '', ('', '', FROZEN_MODULE))
  155.         
  156.         return None
  157.  
  158.     
  159.     def load_module(self, name, stuff):
  160.         (file, filename, info) = stuff
  161.         
  162.         try:
  163.             return imp.load_module(name, file, filename, info)
  164.         finally:
  165.             if file:
  166.                 file.close()
  167.             
  168.  
  169.  
  170.  
  171.  
  172. class Hooks(_Verbose):
  173.     '''Hooks into the filesystem and interpreter.
  174.  
  175.     By deriving a subclass you can redefine your filesystem interface,
  176.     e.g. to merge it with the URL space.
  177.  
  178.     This base class behaves just like the native filesystem.
  179.  
  180.     '''
  181.     
  182.     def get_suffixes(self):
  183.         return imp.get_suffixes()
  184.  
  185.     
  186.     def new_module(self, name):
  187.         return imp.new_module(name)
  188.  
  189.     
  190.     def is_builtin(self, name):
  191.         return imp.is_builtin(name)
  192.  
  193.     
  194.     def init_builtin(self, name):
  195.         return imp.init_builtin(name)
  196.  
  197.     
  198.     def is_frozen(self, name):
  199.         return imp.is_frozen(name)
  200.  
  201.     
  202.     def init_frozen(self, name):
  203.         return imp.init_frozen(name)
  204.  
  205.     
  206.     def get_frozen_object(self, name):
  207.         return imp.get_frozen_object(name)
  208.  
  209.     
  210.     def load_source(self, name, filename, file = None):
  211.         return imp.load_source(name, filename, file)
  212.  
  213.     
  214.     def load_compiled(self, name, filename, file = None):
  215.         return imp.load_compiled(name, filename, file)
  216.  
  217.     
  218.     def load_dynamic(self, name, filename, file = None):
  219.         return imp.load_dynamic(name, filename, file)
  220.  
  221.     
  222.     def load_package(self, name, filename, file = None):
  223.         return imp.load_module(name, file, filename, ('', '', PKG_DIRECTORY))
  224.  
  225.     
  226.     def add_module(self, name):
  227.         d = self.modules_dict()
  228.         if d.has_key(name):
  229.             return d[name]
  230.         
  231.         d[name] = m = self.new_module(name)
  232.         return m
  233.  
  234.     
  235.     def modules_dict(self):
  236.         return sys.modules
  237.  
  238.     
  239.     def default_path(self):
  240.         return sys.path
  241.  
  242.     
  243.     def path_split(self, x):
  244.         return os.path.split(x)
  245.  
  246.     
  247.     def path_join(self, x, y):
  248.         return os.path.join(x, y)
  249.  
  250.     
  251.     def path_isabs(self, x):
  252.         return os.path.isabs(x)
  253.  
  254.     
  255.     def path_exists(self, x):
  256.         return os.path.exists(x)
  257.  
  258.     
  259.     def path_isdir(self, x):
  260.         return os.path.isdir(x)
  261.  
  262.     
  263.     def path_isfile(self, x):
  264.         return os.path.isfile(x)
  265.  
  266.     
  267.     def path_islink(self, x):
  268.         return os.path.islink(x)
  269.  
  270.     
  271.     def openfile(self, *x):
  272.         return apply(open, x)
  273.  
  274.     openfile_error = IOError
  275.     
  276.     def listdir(self, x):
  277.         return os.listdir(x)
  278.  
  279.     listdir_error = os.error
  280.  
  281.  
  282. class ModuleLoader(BasicModuleLoader):
  283.     """Default module loader; uses file system hooks.
  284.  
  285.     By defining suitable hooks, you might be able to load modules from
  286.     other sources than the file system, e.g. from compressed or
  287.     encrypted files, tar files or (if you're brave!) URLs.
  288.  
  289.     """
  290.     
  291.     def __init__(self, hooks = None, verbose = VERBOSE):
  292.         BasicModuleLoader.__init__(self, verbose)
  293.         if not hooks:
  294.             pass
  295.         self.hooks = Hooks(verbose)
  296.  
  297.     
  298.     def default_path(self):
  299.         return self.hooks.default_path()
  300.  
  301.     
  302.     def modules_dict(self):
  303.         return self.hooks.modules_dict()
  304.  
  305.     
  306.     def get_hooks(self):
  307.         return self.hooks
  308.  
  309.     
  310.     def set_hooks(self, hooks):
  311.         self.hooks = hooks
  312.  
  313.     
  314.     def find_builtin_module(self, name):
  315.         if self.hooks.is_builtin(name):
  316.             return (None, '', ('', '', BUILTIN_MODULE))
  317.         
  318.         if self.hooks.is_frozen(name):
  319.             return (None, '', ('', '', FROZEN_MODULE))
  320.         
  321.         return None
  322.  
  323.     
  324.     def find_module_in_dir(self, name, dir, allow_packages = 1):
  325.         if dir is None:
  326.             return self.find_builtin_module(name)
  327.         
  328.         if allow_packages:
  329.             fullname = self.hooks.path_join(dir, name)
  330.             if self.hooks.path_isdir(fullname):
  331.                 stuff = self.find_module_in_dir('__init__', fullname, 0)
  332.                 if stuff:
  333.                     file = stuff[0]
  334.                     if file:
  335.                         file.close()
  336.                     
  337.                     return (None, fullname, ('', '', PKG_DIRECTORY))
  338.                 
  339.             
  340.         
  341.         for info in self.hooks.get_suffixes():
  342.             (suff, mode, type) = info
  343.             fullname = self.hooks.path_join(dir, name + suff)
  344.             
  345.             try:
  346.                 fp = self.hooks.openfile(fullname, mode)
  347.                 return (fp, fullname, info)
  348.             except self.hooks.openfile_error:
  349.                 pass
  350.  
  351.         
  352.         return None
  353.  
  354.     
  355.     def load_module(self, name, stuff):
  356.         (file, filename, info) = stuff
  357.         (suff, mode, type) = info
  358.         
  359.         try:
  360.             if type == BUILTIN_MODULE:
  361.                 return self.hooks.init_builtin(name)
  362.             
  363.             if type == FROZEN_MODULE:
  364.                 return self.hooks.init_frozen(name)
  365.             
  366.             if type == C_EXTENSION:
  367.                 m = self.hooks.load_dynamic(name, filename, file)
  368.             elif type == PY_SOURCE:
  369.                 m = self.hooks.load_source(name, filename, file)
  370.             elif type == PY_COMPILED:
  371.                 m = self.hooks.load_compiled(name, filename, file)
  372.             elif type == PKG_DIRECTORY:
  373.                 m = self.hooks.load_package(name, filename, file)
  374.             else:
  375.                 raise ImportError, 'Unrecognized module type (%s) for %s' % (`type`, name)
  376.         finally:
  377.             if file:
  378.                 file.close()
  379.             
  380.  
  381.         m.__file__ = filename
  382.         return m
  383.  
  384.  
  385.  
  386. class FancyModuleLoader(ModuleLoader):
  387.     '''Fancy module loader -- parses and execs the code itself.'''
  388.     
  389.     def load_module(self, name, stuff):
  390.         (suff, mode, type) = (file, filename)
  391.         realfilename = filename
  392.         path = None
  393.         if type == FROZEN_MODULE:
  394.             code = self.hooks.get_frozen_object(name)
  395.         elif type == PY_COMPILED:
  396.             import marshal
  397.             file.seek(8)
  398.             code = marshal.load(file)
  399.         elif type == PY_SOURCE:
  400.             data = file.read()
  401.             code = compile(data, realfilename, 'exec')
  402.         else:
  403.             return ModuleLoader.load_module(self, name, stuff)
  404.         m = self.hooks.add_module(name)
  405.         if path:
  406.             m.__path__ = path
  407.         
  408.         m.__file__ = filename
  409.         exec code in m.__dict__
  410.         return m
  411.  
  412.  
  413.  
  414. class BasicModuleImporter(_Verbose):
  415.     '''Basic module importer; uses module loader.
  416.  
  417.     This provides basic import facilities but no package imports.
  418.  
  419.     '''
  420.     
  421.     def __init__(self, loader = None, verbose = VERBOSE):
  422.         _Verbose.__init__(self, verbose)
  423.         if not loader:
  424.             pass
  425.         self.loader = ModuleLoader(None, verbose)
  426.         self.modules = self.loader.modules_dict()
  427.  
  428.     
  429.     def get_loader(self):
  430.         return self.loader
  431.  
  432.     
  433.     def set_loader(self, loader):
  434.         self.loader = loader
  435.  
  436.     
  437.     def get_hooks(self):
  438.         return self.loader.get_hooks()
  439.  
  440.     
  441.     def set_hooks(self, hooks):
  442.         return self.loader.set_hooks(hooks)
  443.  
  444.     
  445.     def import_module(self, name, globals = { }, locals = { }, fromlist = []):
  446.         if self.modules.has_key(name):
  447.             return self.modules[name]
  448.         
  449.         stuff = self.loader.find_module(name)
  450.         if not stuff:
  451.             raise ImportError, 'No module named %s' % name
  452.         
  453.         return self.loader.load_module(name, stuff)
  454.  
  455.     
  456.     def reload(self, module, path = None):
  457.         name = module.__name__
  458.         stuff = self.loader.find_module(name, path)
  459.         if not stuff:
  460.             raise ImportError, 'Module %s not found for reload' % name
  461.         
  462.         return self.loader.load_module(name, stuff)
  463.  
  464.     
  465.     def unload(self, module):
  466.         del self.modules[module.__name__]
  467.  
  468.     
  469.     def install(self):
  470.         self.save_import_module = __builtin__.__import__
  471.         self.save_reload = __builtin__.reload
  472.         if not hasattr(__builtin__, 'unload'):
  473.             __builtin__.unload = None
  474.         
  475.         self.save_unload = __builtin__.unload
  476.         __builtin__.__import__ = self.import_module
  477.         __builtin__.reload = self.reload
  478.         __builtin__.unload = self.unload
  479.  
  480.     
  481.     def uninstall(self):
  482.         __builtin__.__import__ = self.save_import_module
  483.         __builtin__.reload = self.save_reload
  484.         __builtin__.unload = self.save_unload
  485.         if not (__builtin__.unload):
  486.             del __builtin__.unload
  487.         
  488.  
  489.  
  490.  
  491. class ModuleImporter(BasicModuleImporter):
  492.     '''A module importer that supports packages.'''
  493.     
  494.     def import_module(self, name, globals = None, locals = None, fromlist = None):
  495.         parent = self.determine_parent(globals)
  496.         (q, tail) = self.find_head_package(parent, name)
  497.         m = self.load_tail(q, tail)
  498.         if not fromlist:
  499.             return q
  500.         
  501.         if hasattr(m, '__path__'):
  502.             self.ensure_fromlist(m, fromlist)
  503.         
  504.         return m
  505.  
  506.     
  507.     def determine_parent(self, globals):
  508.         if not globals or not globals.has_key('__name__'):
  509.             return None
  510.         
  511.         pname = globals['__name__']
  512.         if globals.has_key('__path__'):
  513.             parent = self.modules[pname]
  514.             if not __debug__ and globals is parent.__dict__:
  515.                 raise AssertionError
  516.             return parent
  517.         
  518.         if '.' in pname:
  519.             i = pname.rfind('.')
  520.             pname = pname[:i]
  521.             parent = self.modules[pname]
  522.             if not __debug__ and parent.__name__ == pname:
  523.                 raise AssertionError
  524.             return parent
  525.         
  526.         return None
  527.  
  528.     
  529.     def find_head_package(self, parent, name):
  530.         if '.' in name:
  531.             i = name.find('.')
  532.             head = name[:i]
  533.             tail = name[i + 1:]
  534.         else:
  535.             head = name
  536.             tail = ''
  537.         if parent:
  538.             qname = '%s.%s' % (parent.__name__, head)
  539.         else:
  540.             qname = head
  541.         q = self.import_it(head, qname, parent)
  542.         if q:
  543.             return (q, tail)
  544.         
  545.         if parent:
  546.             qname = head
  547.             parent = None
  548.             q = self.import_it(head, qname, parent)
  549.             if q:
  550.                 return (q, tail)
  551.             
  552.         
  553.         raise ImportError, 'No module named ' + qname
  554.  
  555.     
  556.     def load_tail(self, q, tail):
  557.         m = q
  558.         while tail:
  559.             i = tail.find('.')
  560.             if i < 0:
  561.                 i = len(tail)
  562.             
  563.             (head, tail) = (tail[:i], tail[i + 1:])
  564.             mname = '%s.%s' % (m.__name__, head)
  565.             m = self.import_it(head, mname, m)
  566.             if not m:
  567.                 raise ImportError, 'No module named ' + mname
  568.             
  569.         return m
  570.  
  571.     
  572.     def ensure_fromlist(self, m, fromlist, recursive = 0):
  573.         for sub in fromlist:
  574.             if sub == '*':
  575.                 if not recursive:
  576.                     
  577.                     try:
  578.                         all = m.__all__
  579.                     except AttributeError:
  580.                         pass
  581.  
  582.                     self.ensure_fromlist(m, all, 1)
  583.                 
  584.                 continue
  585.             
  586.             if sub != '*' and not hasattr(m, sub):
  587.                 subname = '%s.%s' % (m.__name__, sub)
  588.                 submod = self.import_it(sub, subname, m)
  589.                 if not submod:
  590.                     raise ImportError, 'No module named ' + subname
  591.                 
  592.             
  593.         
  594.  
  595.     
  596.     def import_it(self, partname, fqname, parent, force_load = 0):
  597.         if not partname:
  598.             raise ValueError, 'Empty module name'
  599.         
  600.         if not force_load:
  601.             
  602.             try:
  603.                 return self.modules[fqname]
  604.             except KeyError:
  605.                 pass
  606.  
  607.         
  608.         
  609.         try:
  610.             if parent:
  611.                 pass
  612.             path = parent.__path__
  613.         except AttributeError:
  614.             return None
  615.  
  616.         stuff = self.loader.find_module(partname, path)
  617.         if not stuff:
  618.             return None
  619.         
  620.         m = self.loader.load_module(fqname, stuff)
  621.         if parent:
  622.             setattr(parent, partname, m)
  623.         
  624.         return m
  625.  
  626.     
  627.     def reload(self, module):
  628.         name = module.__name__
  629.         if '.' not in name:
  630.             return self.import_it(name, name, None, force_load = 1)
  631.         
  632.         i = name.rfind('.')
  633.         pname = name[:i]
  634.         parent = self.modules[pname]
  635.         return self.import_it(name[i + 1:], name, parent, force_load = 1)
  636.  
  637.  
  638. default_importer = None
  639. current_importer = None
  640.  
  641. def install(importer = None):
  642.     global current_importer
  643.     if not importer and default_importer:
  644.         pass
  645.     current_importer = ModuleImporter()
  646.     current_importer.install()
  647.  
  648.  
  649. def uninstall():
  650.     current_importer.uninstall()
  651.  
  652.