⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 palm_imputil.py

📁 minimal python variant for small footprint apps like embedded apps
💻 PY
📖 第 1 页 / 共 2 页
字号:
## imputil.py: import utilities## Modified by J. Collins for the PalmOS#### docco needed here and in Docs/ ...# note: avoid importing non-builtin modulesimport imp                      ### not available in JPython?import sysimport __builtin__# for the DirectoryImporterimport marshal__all__ = ["ImportManager","Importer","BuiltinImporter"]_StringType = type('')_ModuleType = type(sys)         ### doesn't work in JPython...class ImportManager:    "Manage the import process."    def install(self, namespace=vars(__builtin__)):        "Install this ImportManager into the specified namespace."        if isinstance(namespace, _ModuleType):            namespace = vars(namespace)        # Note: we have no notion of "chaining"        # Record the previous import hook, then install our own.        self.previous_importer = namespace['__import__']        self.namespace = namespace        namespace['__import__'] = self._import_hook        ### fix this        # namespace['reload'] = self._reload_hook    def uninstall(self):        "Restore the previous import mechanism."        self.namespace['__import__'] = self.previous_importer    ######################################################################    #    # PRIVATE METHODS    #    def __init__(self, fs_imp=None):        # Initialize the set of suffixes that we recognize and import.        # The default will import dynamic-load modules first, followed by        # .py files (or a .py file's cached bytecode)        pass    def _import_hook(self, fqname, globals=None, locals=None, fromlist=None):        """Python calls this hook to locate and import a module."""        parts = fqname.split('.')        # determine the context of this import        parent = self._determine_import_context(globals)        # if there is a parent, then its importer should manage this import        if parent:            module = parent.__importer__._do_import(parent, parts, fromlist)            if module:                return module        # has the top module already been imported?        try:            top_module = sys.modules[parts[0]]        except KeyError:            # look for the topmost module            top_module = self._import_top_module(parts[0])            if not top_module:                # the topmost module wasn't found at all.                raise ImportError, 'No module named ' + fqname        # fast-path simple imports        if len(parts) == 1:            if not fromlist:                return top_module            if not top_module.__dict__.get('__ispkg__'):                # __ispkg__ isn't defined (the module was not imported by us),                # or it is zero.                #                # In the former case, there is no way that we could import                # sub-modules that occur in the fromlist (but we can't raise an                # error because it may just be names) because we don't know how                # to deal with packages that were imported by other systems.                #                # In the latter case (__ispkg__ == 0), there can't be any sub-                # modules present, so we can just return.                #                # In both cases, since len(parts) == 1, the top_module is also                # the "bottom" which is the defined return when a fromlist                # exists.                return top_module        importer = top_module.__dict__.get('__importer__')        if importer:            return importer._finish_import(top_module, parts[1:], fromlist)        # If the importer does not exist, then we have to bail. A missing        # importer means that something else imported the module, and we have        # no knowledge of how to get sub-modules out of the thing.        raise ImportError, 'No module named ' + fqname    def _determine_import_context(self, globals):        """Returns the context in which a module should be imported.        The context could be a loaded (package) module and the imported module        will be looked for within that package. The context could also be None,        meaning there is no context -- the module should be looked for as a        "top-level" module.        """        if not globals or not globals.get('__importer__'):            # globals does not refer to one of our modules or packages. That            # implies there is no relative import context (as far as we are            # concerned), and it should just pick it off the standard path.            return None        # The globals refer to a module or package of ours. It will define        # the context of the new import. Get the module/package fqname.        parent_fqname = globals['__name__']        # if a package is performing the import, then return itself (imports        # refer to pkg contents)        if globals['__ispkg__']:            parent = sys.modules[parent_fqname]            assert globals is parent.__dict__            return parent        i = parent_fqname.rfind('.')        # a module outside of a package has no particular import context        if i == -1:            return None        # if a module in a package is performing the import, then return the        # package (imports refer to siblings)        parent_fqname = parent_fqname[:i]        parent = sys.modules[parent_fqname]        assert parent.__name__ == parent_fqname        return parent    def _import_top_module(self, name):        # scan sys.path looking for a location in the filesystem that contains        # the module, or an Importer object that can import the module.        for item in sys.path:            module = item.import_top(name)            if module:                return module        return None    def _reload_hook(self, module):        "Python calls this hook to reload a module."        # reloading of a module may or may not be possible (depending on the        # importer), but at least we can validate that it's ours to reload        importer = module.__dict__.get('__importer__')        if not importer:            # Must have imported through some other mechanism - use builtin            pass        # okay. it is using the imputil system, and we must delegate it, but        # we don't know what to do (yet)        ### we should blast the module dict and do another get_code(). need to        ### flesh this out and add proper docco...        raise SystemError, "reload not yet implemented"class Importer:    "Base class for replacing standard import functions."    def import_top(self, name):        "Import a top-level module."        return self._import_one(None, name, name)    ######################################################################    #    # PRIVATE METHODS    #    def _finish_import(self, top, parts, fromlist):        # if "a.b.c" was provided, then load the ".b.c" portion down from        # below the top-level module.        bottom = self._load_tail(top, parts)        # if the form is "import a.b.c", then return "a"        if not fromlist:            # no fromlist: return the top of the import tree            return top        # the top module was imported by self.        #        # this means that the bottom module was also imported by self (just        # now, or in the past and we fetched it from sys.modules).        #        # since we imported/handled the bottom module, this means that we can        # also handle its fromlist (and reliably use __ispkg__).        # if the bottom node is a package, then (potentially) import some        # modules.        #        # note: if it is not a package, then "fromlist" refers to names in        #       the bottom module rather than modules.        # note: for a mix of names and modules in the fromlist, we will        #       import all modules and insert those into the namespace of        #       the package module. Python will pick up all fromlist names        #       from the bottom (package) module; some will be modules that        #       we imported and stored in the namespace, others are expected        #       to be present already.        if bottom.__ispkg__:            self._import_fromlist(bottom, fromlist)        # if the form is "from a.b import c, d" then return "b"        return bottom    def _import_one(self, parent, modname, fqname):        "Import a single module."        # has the module already been imported?        try:            return sys.modules[fqname]        except KeyError:            pass        # load the module's code, or fetch the module itself        result = self.get_code(parent, modname, fqname)        if result is None:            return None        module = self._process_result(result, fqname)        # insert the module into its parent        if parent:            setattr(parent, modname, module)        return module    def _process_result(self, (ispkg, code, values), fqname):        # did get_code() return an actual module? (rather than a code object)        is_module = isinstance(code, _ModuleType)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -