def importModule(name): "needed because of a bug in python when dynamically loading a python module" if (len(name) == 0): return None if not name[0].isalpha(): return None # Fast path: see if the module has already been imported. if sys.modules.has_key(name): return sys.modules[name] # If any of the following calls raises an exception, # there's a problem we can't handle # See if it's a built-in module. m = imp.init_builtin(name) if m: return m # See if it's a frozen module. m = imp.init_frozen(name) if m: return m try: # Search the default path (i.e. sys.path). fp, pathname, stuff = imp.find_module(name) except ImportError, param: Log.logDebug("Helper.importModule(): ImportError: " + str(param), 2) Log.logDebug("Helper.importModule(): failed to find module " + str(name), 1) return None
def importModule(name): "needed because of a bug in python when dynamically loading a python module" if (len(name) == 0): return None if not name[0].isalpha(): return None # Fast path: see if the module has already been imported. if sys.modules.has_key(name): return sys.modules[name] # If any of the following calls raises an exception, # there's a problem we can't handle # See if it's a built-in module. m = imp.init_builtin(name) if m: return m # See if it's a frozen module. m = imp.init_frozen(name) if m: return m try: # Search the default path (i.e. sys.path). fp, pathname, stuff = imp.find_module(name) except ImportError, param: Log.logDebug("Helper.importModule(): ImportError: " + str(param), 2) Log.logDebug( "Helper.importModule(): failed to find module " + str(name), 1) return None
def load_module(self,fullname): try: return sys.modules[fullname] except KeyError: pass if imp.is_builtin(fullname): mod = imp.init_builtin(fullname) elif imp.is_frozen(fullname): mod = imp.init_frozen(fullname) else: raise ImportError(fullname + " is not builtin or frozen") sys.modules[fullname] = mod return mod
def test_obscure_functions(self): import imp mod = imp.new_module('hi') assert mod.__name__ == 'hi' mod = imp.init_builtin( 'hello.world.this.is.never.a.builtin.module.name') assert mod is None mod = imp.init_frozen('hello.world.this.is.never.a.frozen.module.name') assert mod is None assert imp.is_builtin('sys') assert not imp.is_builtin( 'hello.world.this.is.never.a.builtin.module.name') assert not imp.is_frozen( 'hello.world.this.is.never.a.frozen.module.name')
def load_module(self, name, stuff): file, filename, (suff, mode, type) = stuff if type == BUILTIN_MODULE: return imp.init_builtin(name) if type == FROZEN_MODULE: return imp.init_frozen(name) if type == C_EXTENSION: return imp.load_dynamic(name, filename, file) if type == PY_SOURCE: return imp.load_source(name, filename, file) if type == PY_COMPILED: return imp.load_compiled(name, filename, file) raise ImportError, "Unrecognized module type (%s) for %s" % \ (`type`, name)
def test_init_frozen(): for name in temp_name: f = imp.init_frozen(name) if f != None : Fail("return object should be None!")
def test_init_frozen(self): for name in self.temp_name: f = imp.init_frozen(name) self.assertIsNone(f)
def init_frozen(self, name): return imp.init_frozen(name) def get_frozen_object(self, name): return imp.get_frozen_object(name)
def init_frozen(self, name): return imp.init_frozen(name)
def update_event(self, inp=-1): self.set_output_val(0, imp.init_frozen(self.input(0)))
def import_module(name, envLocals=None, envGlobals=None, froms=None, inPkg=None): """Primary service routine implementing 'import' with package nesting.""" # The job is divided into a few distinct steps: # # - Look for either an already loaded module or a file to be loaded. # * if neither loaded module nor prospect file is found, raise an error. # - If we have a file, not an already loaded module: # - Load the file into a module. # - Register the new module and intermediate package stubs. # (We have a module at this point...) # - Bind requested syms (module or specified 'from' defs) in calling env. # - Return the appropriate component. note("import_module: seeking '%s'%s" % (name, ((inPkg and ' (in package %s)' % inPkg.__name__) or ''))) # We need callers environment dict for local path and resulting module # binding. if not (envLocals or envGlobals): envLocals, envGlobals = exterior() modList = theMod = absNm = container = None # Get module obj if one already established, or else module file if not: if inPkg: # We've been invoked with a specific containing package: pkg, pkgPath, pkgNm = inPkg, inPkg.__dict__[PKG_PATH], inPkg.__name__ relNm = name absNm = pkgNm + '.' + name elif name[:PKG_SHORT_NM_LEN+1] != PKG_SHORT_NM + '.': # name is NOT '__.something' - setup to seek according to specified # absolute name. pkg = __python__ pkgPath = sys.path absNm = name relNm = absNm else: # name IS '__.' + something - setup to seek according to relative name, # in current package. relNm = name[len(PKG_SHORT_NM)+1:] # Relative portion of name. try: pkg = envGlobals[PKG_NM] # The immediately containing package. pkgPath = pkg.__dict__[PKG_PATH] if pkg == __python__: # At outermost package. absNm = relNm else: absNm = (pkg.__name__ + '.' + relNm) except KeyError: # Missing package, path, or name. note("Can't identify parent package, package name, or pkgpath") pass # ==v # Try to find existing module: if sys.modules.has_key(absNm): note('found ' + absNm + ' already imported') theMod = sys.modules[absNm] else: # Try for builtin or frozen first: theMod = imp.init_builtin(absNm) if theMod: note('found builtin ' + absNm) else: theMod = imp.init_frozen(absNm) if theMod: note('found frozen ' + absNm) if not theMod: if type(pkgPath) == types.StringType: pkgPath = [pkgPath] modList = find_module(relNm, pkgPath, absNm) if not modList: raise ImportError, "module '%s' not found" % absNm # ===X # We have a list of successively nested files leading to the # module, register them as stubs: container = register_module_nesting(modList, pkg) # Load from file if necessary and possible: modNm, modf, path, ty = modList[-1] note('found type ' + modes[ty[2]] + ' - ' + absNm) # Do the load: theMod = load_module(absNm, ty[2], modf, inPkg) # Loaded successfully - promote module to full module status: register_module(theMod, theMod.__name__, pkgPath, pkg) # Have a loaded module, impose designated components, and return # appropriate thing - according to guido: # "Note that for "from spam.ham import bacon" your function should # return the object denoted by 'spam.ham', while for "import # spam.ham" it should return the object denoted by 'spam' -- the # STORE instructions following the import statement expect it this # way." if not froms: # Establish the module defs in the importing name space: (envLocals or envGlobals)[name] = theMod return (container or theMod) else: # Implement 'from': Populate immediate env with module defs: if froms == '*': froms = theMod.__dict__.keys() # resolve '*' for item in froms: (envLocals or envGlobals)[item] = theMod.__dict__[item] return theMod
def secimport(name, globals=None, locals=None, fromlist=None): # Fast path: let's see if it's already in sys.modules. # Two speed optimizations are worth mentioning: # - We use 'modules' instead of 'sys.modules'; this saves a # dictionary look-up per call. # - It's also faster to use a try-except statement than # to use modules.has_key(name) to check if it's there. try: return modules[name] except KeyError: pass # See if it's a built-in module m = imp.init_builtin(name) if m: return m # See if it's a frozen module m = imp.init_frozen(name) if m: return m # Search the default path (i.e. sys.path). # If this raises an exception, the module is not found -- # let the caller handle the exception. fp, pathname, (suffix, mode, type) = imp.find_module(name) # See what we got... # Note that fp will be closed automatically when we return. # Extensions are written in C, and can just be loaded. if type == imp.C_EXTENSION: return imp.load_dynamic(name, pathname) # How do you handle files only present in source form? I've # arbitrarily chosen to forbid secure importing of source code; # you will probably wish to change this in a real application. if type == imp.PY_SOURCE: print name, pathname raise ImportError, 'Importing of source files is forbidden by secure import' # For a compiled file, we'll check if there is a *.pys file # present in the same directory. if type == imp.PY_COMPILED: testfile = pathname[:-4]+'.pys' try: print testfile secfile=open(testfile, 'rb') except IOError, tuple: if (tuple[0]==2): pass # Ignore 'file not found' error else: raise IOError, tuple else: # Check the signature import marshal, RSA, md5 fp.close() # Close the original *.pyc file from testkey import * # Get the key for verification signature=marshal.load(secfile) # Read signature position=secfile.tell() data=secfile.read() # Read code object hash=md5.new(data).digest() # Compute its hash value print 'sigcheck:', key.validate(hash, signature) if (not key.validate(hash, signature)): raise ImportError, 'Signature check failed' secfile.seek(position) # Rewind pointer to the # beginning of the code object fp=secfile del secfile # Now we can happily import the compiled code object. return imp.load_compiled(name, pathname, fp)
def secimport(name, globals=None, locals=None, fromlist=None): # Fast path: let's see if it's already in sys.modules. # Two speed optimizations are worth mentioning: # - We use 'modules' instead of 'sys.modules'; this saves a # dictionary look-up per call. # - It's also faster to use a try-except statement than # to use modules.has_key(name) to check if it's there. try: return modules[name] except KeyError: pass # See if it's a built-in module m = imp.init_builtin(name) if m: return m # See if it's a frozen module m = imp.init_frozen(name) if m: return m # Search the default path (i.e. sys.path). # If this raises an exception, the module is not found -- # let the caller handle the exception. fp, pathname, (suffix, mode, type) = imp.find_module(name) # See what we got... # Note that fp will be closed automatically when we return. # Extensions are written in C, and can just be loaded. if type == imp.C_EXTENSION: return imp.load_dynamic(name, pathname) # For a compiled or source file, we'll check if there is a *.pys file # present in the same directory. if type == imp.PY_COMPILED or type == imp.PY_SOURCE: root, ext = os.path.splitext(pathname) testfile = root + '.pys' try: print testfile secfile=open(testfile, 'rb') except IOError, tuple: if (tuple[0]==2): pass # Ignore 'file not found' error else: raise IOError, tuple else: # Check the signature (a signed hash of the code object). # We could sign the whole code object, but that would # require a huge key and would double the size of the # *.pys file. import marshal from Crypto.Hash import MD5 fp.close() # Close the original *.pyc file from testkey import * # Get the key for verification signature=marshal.load(secfile) # Read signature position=secfile.tell() # Save position data=secfile.read() # Read code object hash=MD5.new(data).digest() # Compute its hash value ##print 'sigcheck:', key.verify(hash, signature) if (not key.verify(hash, signature)): raise ImportError, 'Signature check of '+ testfile + ' failed' secfile.seek(position) # Rewind pointer to the # beginning of the code object fp=secfile del secfile # Now we can happily import the compiled code object. return imp.load_compiled(name, pathname, fp)
"""Import hook support.