Пример #1
0
    def test_is_builtin(self):

        self.assertEqual(imp.is_builtin("xxx"),0)
        self.assertEqual(imp.is_builtin("12324"),0)
        self.assertEqual(imp.is_builtin("&*^^"),0)

        self.assertEqual(imp.is_builtin("dir"),0)
        self.assertEqual(imp.is_builtin("__doc__"),0)
        self.assertEqual(imp.is_builtin("__name__"),0)

        self.assertEqual(imp.is_builtin("_locle"),0)

        if is_cli:
            self.assertEqual(imp.is_builtin("_pickle"),0)
        else:
            self.assertEqual(imp.is_builtin("_pickle"),1)
        self.assertEqual(imp.is_builtin("_random"),1)

        # nt module disabled in Silverlight
        if is_posix:
            self.assertEqual(imp.is_builtin("posix"),1)
        else:
            self.assertEqual(imp.is_builtin("nt"),1)

        self.assertEqual(imp.is_builtin("_thread"),1)

        # used to be a builtin but no longer is
        self.assertEqual(imp.is_builtin("copyreg"),0)

        # supposedly you can't re-init these
        self.assertEqual(imp.is_builtin("sys"), -1)
        self.assertEqual(imp.is_builtin("builtins"), -1)

        imp.init_builtin("sys")
        imp.init_builtin("builtins")
Пример #2
0
 def test_init_builtin(self):
     r  = imp.init_builtin("c_Pickle")
     self.assertEqual(r,None)
     
     r  = imp.init_builtin("2345")
     self.assertEqual(r,None)
     r  = imp.init_builtin("xxxx")
     self.assertEqual(r,None)
     r  = imp.init_builtin("^$%$#@")
     self.assertEqual(r,None)
     
     r  = imp.init_builtin("_locale")
     self.assertTrue(r!=None)
Пример #3
0
def test_init_builtin():
    r  = imp.init_builtin("c_Pickle")
    AreEqual(r,None)
    
    r  = imp.init_builtin("2345")
    AreEqual(r,None)
    r  = imp.init_builtin("xxxx")
    AreEqual(r,None)
    r  = imp.init_builtin("^$%$#@")
    AreEqual(r,None)
    
    r  = imp.init_builtin("_locale")
    Assert(r!=None)
Пример #4
0
def test_init_builtin():
    r  = imp.init_builtin("c_Pickle")
    AreEqual(r,None)
    
    r  = imp.init_builtin("2345")
    AreEqual(r,None)
    r  = imp.init_builtin("xxxx")
    AreEqual(r,None)
    r  = imp.init_builtin("^$%$#@")
    AreEqual(r,None)
    
    r  = imp.init_builtin("_locale")
    Assert(r!=None)
Пример #5
0
 def test_init_builtin(self):
     r  = imp.init_builtin("c_Pickle")
     self.assertEqual(r,None)
     
     r  = imp.init_builtin("2345")
     self.assertEqual(r,None)
     r  = imp.init_builtin("xxxx")
     self.assertEqual(r,None)
     r  = imp.init_builtin("^$%$#@")
     self.assertEqual(r,None)
     
     r  = imp.init_builtin("_locale")
     self.assertTrue(r!=None)
 def load_module(self, mod, stuff):
     """Internal -- load a module given the imp.find_module() stuff."""
     rexec = self.get_rexec()
     rexec.reset_urlpath()
     rexec.set_urlpath(self.codeurl)
     # XXX Duplicate stuff from rexec.RModuleLoader.load_module()
     # and even from ihooks.FancyModuleLoader.load_module().
     # This is needed to pass a copy of the source to linecace.
     file, filename, info = stuff
     (suff, mode, type) = info
     import imp
     from pythonlib import ihooks
     if type == imp.PKG_DIRECTORY:
         loader = self.get_rexec().loader
         return ihooks.FancyModuleLoader.load_module(loader, mod, stuff)
     if type == imp.PY_SOURCE:
         import linecache
         lines = file.readlines()
         data = str.join(lines, '')
         linecache.cache[filename] = (len(data), 0, lines, filename)
         code = compile(data, filename, 'exec')
         m = rexec.hooks.add_module(mod)
         m.__file__ = filename
         m.__filename__ = filename
         exec(code in m.__dict__)
     elif type == imp.C_BUILTIN:
         m = imp.init_builtin(mod)
     elif type == ihooks.C_EXTENSION:
         m = rexec.load_dynamic(mod, filename, file)
     else:
         raise ImportError("Unsupported module type: %s" % repr(filename))
     return m
Пример #7
0
 def load_module(self, mod, stuff):
     """Internal -- load a module given the imp.find_module() stuff."""
     rexec = self.get_rexec()
     rexec.reset_urlpath()
     rexec.set_urlpath(self.codeurl)
     # XXX Duplicate stuff from rexec.RModuleLoader.load_module()
     # and even from ihooks.FancyModuleLoader.load_module().
     # This is needed to pass a copy of the source to linecace.
     file, filename, info = stuff
     (suff, mode, type) = info
     import imp
     import ihooks
     if type == imp.PKG_DIRECTORY:
         loader = self.get_rexec().loader
         return ihooks.FancyModuleLoader.load_module(loader, mod, stuff)
     if type == imp.PY_SOURCE:
         import linecache
         lines = file.readlines()
         data = string.joinfields(lines, '')
         linecache.cache[filename] = (len(data), 0, lines, filename)
         code = compile(data, filename, 'exec')
         m = rexec.hooks.add_module(mod)
         m.__file__ = filename
         m.__filename__ = filename
         exec code in m.__dict__
     elif type == imp.C_BUILTIN:
         m = imp.init_builtin(mod)
     elif type == ihooks.C_EXTENSION:
         m = rexec.load_dynamic(mod, filename, file)
     else:
         raise ImportError, "Unsupported module type: %s" % `filename`
     return m
Пример #8
0
 def test_is_builtin(self):
     import sys, imp
     for name in sys.builtin_module_names:
         assert imp.is_builtin(name)
         mod = imp.init_builtin(name)
         assert mod
         assert mod.__spec__
Пример #9
0
def stdlib_import(name):
    "Work around undesired behavior of Python's relative import feature."
    try:
        return sys.modules[name]
    except KeyError:
        pass
    import imp

    if imp.is_builtin(name):
        try:
            return imp.init_builtin(name)
        except Exception:
            pass
    sys_path = sys.path[:]
    sys_path.reverse()
    for path in sys_path:
        try:
            fp, pathname, description = imp.find_module(name, [path])
        except ImportError:
            pass
        else:
            try:
                return imp.load_module(name, fp, pathname, description)
            finally:
                if fp is not None:
                    fp.close()
    raise RuntimeError("Cannot import %s module." % name)
Пример #10
0
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
Пример #11
0
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
Пример #12
0
def test_is_builtin():

    AreEqual(imp.is_builtin("xxx"), 0)
    AreEqual(imp.is_builtin("12324"), 0)
    AreEqual(imp.is_builtin("&*^^"), 0)

    AreEqual(imp.is_builtin("dir"), 0)
    AreEqual(imp.is_builtin("__doc__"), 0)
    AreEqual(imp.is_builtin("__name__"), 0)

    AreEqual(imp.is_builtin("_locle"), 0)

    AreEqual(imp.is_builtin("cPickle"), 1)
    AreEqual(imp.is_builtin("_random"), 1)

    # nt module disabled in Silverlight
    if not is_silverlight:
        AreEqual(imp.is_builtin("nt"), 1)

    AreEqual(imp.is_builtin("thread"), 1)

    # there are a several differences between ironpython and cpython
    if is_cli or is_silverlight:
        AreEqual(imp.is_builtin("copy_reg"), 1)
    else:
        AreEqual(imp.is_builtin("copy_reg"), 0)

    # supposedly you can't re-init these
    AreEqual(imp.is_builtin("sys"), -1)
    AreEqual(imp.is_builtin("__builtin__"), -1)
    AreEqual(imp.is_builtin("exceptions"), -1)

    imp.init_builtin("sys")
    imp.init_builtin("__builtin__")
    imp.init_builtin("exceptions")
Пример #13
0
 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
Пример #14
0
def fixupBuiltinModules(needs_init=0):
    for moduleName in sys.builtin_module_names :
        if needs_init:
            _ = Module(moduleName, 0)
        module = _allModules.get(moduleName, None)
        if module is not None :
            try :
                m = imp.init_builtin(moduleName)
            except ImportError :
                pass
            else :
                extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, [])
                module.attributes = [ '__dict__' ] + dir(m) + extra_attrs
Пример #15
0
def pypy58_57_compat():
    import imp, os

    # first load and move the builtin cppyy module
    if not 'cppyy' in sys.modules:
        try:
            olddir = os.getcwd()
            from cppyy_backend import loader
            c = loader.load_cpp_backend()
            # move to the location of the backend, just in case '.' is
            # in the dynloader's path
            os.chdir(os.path.dirname(c._name))
            imp.init_builtin('cppyy')
        except ImportError:
            raise EnvironmentError('"%s" missing in LD_LIBRARY_PATH' %\
                                   os.path.dirname(c._name))
        finally:
            os.chdir(olddir)

    sys.modules['_cppyy'] = sys.modules['cppyy']
    del sys.modules['cppyy']

    # now locate and load the pip cppyy module
    decdir = os.path.join(os.path.dirname(__file__), os.path.pardir)
    for path in sys.path:  # walk over sys.path skips builtins
        try:
            fp, pathname, description = imp.find_module('cppyy', [path])
            sys.modules['cppyy'] = imp.load_module('cppyy_', fp, pathname,
                                                   description)
            break
        except ImportError:
            pass

# copy over the _cppyy functions into cppyy
    old = sys.modules['_cppyy']
    new = sys.modules['cppyy']
    for name in dir(old):
        if not hasattr(new, name):
            setattr(new, name, getattr(old, name))
Пример #16
0
def fixupBuiltinModules(needs_init=0):
    for moduleName in sys.builtin_module_names:
        if needs_init:
            _ = Module(moduleName, 0)
        module = _allModules.get(moduleName, None)
        if module is not None:
            try:
                m = imp.init_builtin(moduleName)
            except ImportError:
                pass
            else:
                extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, [])
                module.attributes = ['__dict__'] + dir(m) + extra_attrs
Пример #17
0
    def test_is_builtin(self):

        self.assertEqual(imp.is_builtin("xxx"), 0)
        self.assertEqual(imp.is_builtin("12324"), 0)
        self.assertEqual(imp.is_builtin("&*^^"), 0)

        self.assertEqual(imp.is_builtin("dir"), 0)
        self.assertEqual(imp.is_builtin("__doc__"), 0)
        self.assertEqual(imp.is_builtin("__name__"), 0)

        self.assertEqual(imp.is_builtin("_locle"), 0)

        if is_cli:
            self.assertEqual(imp.is_builtin("_pickle"), 0)
        else:
            self.assertEqual(imp.is_builtin("_pickle"), 1)
        self.assertEqual(imp.is_builtin("_random"), 1)

        # nt module disabled in Silverlight
        if is_posix:
            self.assertEqual(imp.is_builtin("posix"), 1)
        else:
            self.assertEqual(imp.is_builtin("nt"), 1)

        self.assertEqual(imp.is_builtin("_thread"), 1)

        # there are a several differences between ironpython and cpython
        if is_cli:
            self.assertEqual(imp.is_builtin("copyreg"), 1)
        else:
            self.assertEqual(imp.is_builtin("copyreg"), 0)

        # supposedly you can't re-init these
        self.assertEqual(imp.is_builtin("sys"), -1)
        self.assertEqual(imp.is_builtin("builtins"), -1)

        imp.init_builtin("sys")
        imp.init_builtin("builtins")
Пример #18
0
def pypy58_57_compat():
    import imp, os

  # first load and move the builtin cppyy module
    if not 'cppyy' in sys.modules:
        try:
            olddir = os.getcwd()
            from cppyy_backend import loader
            c = loader.load_cpp_backend()
          # move to the location of the backend, just in case '.' is
          # in the dynloader's path
            os.chdir(os.path.dirname(c._name))
            imp.init_builtin('cppyy')
        except ImportError:
            raise EnvironmentError('"%s" missing in LD_LIBRARY_PATH' %\
                                   os.path.dirname(c._name))
        finally:
            os.chdir(olddir)

    sys.modules['_cppyy'] = sys.modules['cppyy']
    del sys.modules['cppyy']

  # now locate and load the pip cppyy module
    decdir = os.path.join(os.path.dirname(__file__), os.path.pardir)
    for path in sys.path:     # walk over sys.path skips builtins
        try:
            fp, pathname, description = imp.find_module('cppyy', [path])
            sys.modules['cppyy'] = imp.load_module('cppyy_', fp, pathname, description)
            break
        except ImportError:
            pass

  # copy over the _cppyy functions into cppyy
    old = sys.modules['_cppyy']
    new = sys.modules['cppyy']
    for name in dir(old):
        if not hasattr(new, name):
            setattr(new, name, getattr(old, name))
Пример #19
0
    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)
Пример #20
0
 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')
Пример #21
0
    def load_module(self, fullname, path=None):
        imp_lock()
        try:
            try:
                module = sys.modules.get(fullname)
                if module is None:
                    module = imp.init_builtin(fullname)
            except Exception:
                if fullname in sys.modules:
                    sys.modules.pop(fullname)
                raise

        finally:
            imp_unlock()

        return module
Пример #22
0
def load_module(fqname):
    """Return an imported module without filling sys.modules."""
    name, path = get_dotted_path(fqname)

    try:
        (module_file, p, description) = imp.find_module(name, [path])
    except ImportError:
        (module_file, p, description) = imp.find_module(name)

    if module_file is None:
        if description[2] == imp.C_BUILTIN:
            return imp.init_builtin(fqname)
        # Module was a package, we need to get __init__.py for that package
        (module_file, p, description) = imp.find_module('__init__', [p])

    module = imp.new_module(fqname)
    module.__file__ = module_file.name
    exec module_file in module.__dict__

    return module
Пример #23
0
    def load_module(self, fullname, path=None):
        imp.acquire_lock()

        try:
            # PEP302 If there is an existing module object named 'fullname'
            # in sys.modules, the loader must use that existing module.
            module = sys.modules.get(fullname)
            if module is None:
                module = imp.init_builtin(fullname)

        except Exception:
            # Remove 'fullname' from sys.modules if it was appended there.
            if fullname in sys.modules:
                sys.modules.pop(fullname)
            raise  # Raise the same exception again.
        finally:
            # Release the interpreter's import lock.
            imp.release_lock()

        return module
Пример #24
0
def load_module(fqname):
    """Return an imported module without filling sys.modules."""
    name, path = get_dotted_path(fqname)

    try:
        (module_file, p, description) = imp.find_module(name, [path])
    except ImportError:
        (module_file, p, description) = imp.find_module(name)

    if module_file is None:
        if description[2] == imp.C_BUILTIN:
            return imp.init_builtin(fqname)
        # Module was a package, we need to get __init__.py for that package
        (module_file, p, description) = imp.find_module('__init__', [p])

    module = imp.new_module(fqname)
    module.__file__ = module_file.name
    exec module_file in module.__dict__

    return module
Пример #25
0
    def load_module(self, fullname, path=None):
        imp.acquire_lock()

        try:
            # PEP302 If there is an existing module object named 'fullname'
            # in sys.modules, the loader must use that existing module.
            module = sys.modules.get(fullname)
            if module is None:
                module = imp.init_builtin(fullname)

        except Exception:
            # Remove 'fullname' from sys.modules if it was appended there.
            if fullname in sys.modules:
                sys.modules.pop(fullname)
            raise  # Raise the same exception again.
        finally:
            # Release the interpreter's import lock.
            imp.release_lock()

        return module
Пример #26
0
def fixupBuiltinModules(needs_init=0):
    for moduleName in sys.builtin_module_names:
        # Skip sys since it will reset sys.stdout in IDLE and cause
        # stdout to go to the real console rather than the IDLE console.
        # FIXME: this breaks test42
        # if moduleName == 'sys':
        #     continue

        if needs_init:
            _ = PyCheckerModule(moduleName, 0)
        # builtin modules don't have a moduleDir
        module = pcmodules.getPCModule(moduleName)
        if module is not None:
            try:
                m = imp.init_builtin(moduleName)
            except ImportError:
                pass
            else:
                extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, [])
                module.attributes = ['__dict__'] + dir(m) + extra_attrs
Пример #27
0
def fixupBuiltinModules(needs_init=0):
    for moduleName in sys.builtin_module_names :
        # Skip sys since it will reset sys.stdout in IDLE and cause
        # stdout to go to the real console rather than the IDLE console.
        # FIXME: this breaks test42
        # if moduleName == 'sys':
        #     continue

        if needs_init:
            _ = PyCheckerModule(moduleName, 0)
        # builtin modules don't have a moduleDir
        module = pcmodules.getPCModule(moduleName)
        if module is not None :
            try :
                m = imp.init_builtin(moduleName)
            except ImportError :
                pass
            else :
                extra_attrs = _BUILTIN_MODULE_ATTRS.get(moduleName, [])
                module.attributes = [ '__dict__' ] + dir(m) + extra_attrs
Пример #28
0
def stdlib_import(name):
  "Work around undesired behavior of Python's relative import feature."
  try:
    return sys.modules[name]
  except KeyError:
    pass
  import imp
  if (imp.is_builtin(name)):
    try: return imp.init_builtin(name)
    except Exception: pass
  sys_path = sys.path[:]
  sys_path.reverse()
  for path in sys_path:
    try:
      fp, pathname, description = imp.find_module(name, [path])
    except ImportError:
      pass
    else:
      try:
        return imp.load_module(name, fp, pathname, description)
      finally:
        if (fp is not None): fp.close()
  raise RuntimeError("Cannot import %s module." % name)
Пример #29
0
    def load_module(self, fullname):
        try:
            return sys.modules[fullname]
        except KeyError:
            pass

        if imp.is_builtin(fullname):
            import freeze_external_modules
            try:
                imp.acquire_lock()
                py_package_context = freeze_external_modules.get_py_package_context()
                freeze_external_modules.set_py_package_context(fullname)
                return imp.init_builtin(fullname)
            finally:
                freeze_external_modules.set_py_package_context(py_package_context)
                imp.release_lock()
        else:
            if imp.is_frozen('freezer_package.' + fullname):
                co = imp.get_frozen_object('freezer_package.' + fullname)
                is_package = True
            else:
                co = imp.get_frozen_object("freezer." + fullname)  # This may throw ImportError if not found.
                is_package = False
            try:
                imp.acquire_lock()
                mod = imp.new_module(fullname)
                if '__builtins__' not in mod.__dict__:
                    mod.__dict__['__builtins__'] = __builtins__
                mod.__file__ = "frozen/" + "/".join(fullname.split('.'))
                if is_package:
                    mod.__path__ = [fullname]
                    mod.__file__ = mod.__file__ + "/__init__"
                sys.modules[fullname] = mod
                eval(co, mod.__dict__, mod.__dict__)
                return mod
            finally:
                imp.release_lock()
Пример #30
0
 def test_is_builtin(self):
 
     self.assertEqual(imp.is_builtin("xxx"),0)
     self.assertEqual(imp.is_builtin("12324"),0)
     self.assertEqual(imp.is_builtin("&*^^"),0)
     
     self.assertEqual(imp.is_builtin("dir"),0)
     self.assertEqual(imp.is_builtin("__doc__"),0)
     self.assertEqual(imp.is_builtin("__name__"),0)
     
     self.assertEqual(imp.is_builtin("_locle"),0)
     
     self.assertEqual(imp.is_builtin("cPickle"),1)
     self.assertEqual(imp.is_builtin("_random"),1)
         
     if is_posix:
         self.assertEqual(imp.is_builtin("posix"),1)
     else:
         self.assertEqual(imp.is_builtin("nt"),1)
         
     self.assertEqual(imp.is_builtin("thread"),1)
     
     
     # there are a several differences between ironpython and cpython
     if is_cli:
         self.assertEqual(imp.is_builtin("copy_reg"),1)
     else:
         self.assertEqual(imp.is_builtin("copy_reg"),0)
     
     # supposedly you can't re-init these
     self.assertEqual(imp.is_builtin("sys"), -1)
     self.assertEqual(imp.is_builtin("__builtin__"), -1)
     self.assertEqual(imp.is_builtin("exceptions"), -1)
     
     imp.init_builtin("sys")
     imp.init_builtin("__builtin__")
     imp.init_builtin("exceptions")
Пример #31
0
def test_is_builtin():
   
    AreEqual(imp.is_builtin("xxx"),0)
    AreEqual(imp.is_builtin("12324"),0)
    AreEqual(imp.is_builtin("&*^^"),0)
    
    AreEqual(imp.is_builtin("dir"),0)
    AreEqual(imp.is_builtin("__doc__"),0)
    AreEqual(imp.is_builtin("__name__"),0)
    
    AreEqual(imp.is_builtin("_locle"),0)
    
    AreEqual(imp.is_builtin("cPickle"),1)
    AreEqual(imp.is_builtin("_random"),1)
        
    # nt module disabled in Silverlight
    if not is_silverlight:
        AreEqual(imp.is_builtin("nt"),1)
        
    AreEqual(imp.is_builtin("thread"),1)
    
    
    # there are a several differences between ironpython and cpython
    if is_cli or is_silverlight:
        AreEqual(imp.is_builtin("copy_reg"),1)
    else:
        AreEqual(imp.is_builtin("copy_reg"),0)
    
    # supposedly you can't re-init these
    AreEqual(imp.is_builtin("sys"), -1)
    AreEqual(imp.is_builtin("__builtin__"), -1)
    AreEqual(imp.is_builtin("exceptions"), -1)
    
    imp.init_builtin("sys")
    imp.init_builtin("__builtin__")
    imp.init_builtin("exceptions")
Пример #32
0
 def init_builtin(self, name): return imp.init_builtin(name)
 def is_frozen(self, name): return imp.is_frozen(name)
Пример #33
0
 def update_event(self, inp=-1):
     self.set_output_val(0, imp.init_builtin(self.input(0)))
Пример #34
0
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)
Пример #35
0
 def init_builtin(self, name):
     return imp.init_builtin(name)
Пример #36
0
 def init_builtin(self, name): return imp.init_builtin(name)
 def is_frozen(self, name): return imp.is_frozen(name)
Пример #37
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
Пример #38
0
 def init_builtin(self, name):
     return imp.init_builtin(name)
Пример #39
0
"""Import hook support.
Пример #40
0
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)
Пример #41
0
 def getmod(self, nm, isbuiltin=imp.is_builtin):
     # Return initialized built-in module object or None
     # if there is no built-in module with that name.
     return imp.init_builtin(nm)
Пример #42
0
import warnings

#  When using PySiLK as a plug-in from a SiLK application, the C parts
#  of the SiLK package (which are in the pysilk module) are compiled
#  into the application itself.  We need to use the 'imp' module to
#  make the "silk.pysilk_pin" code availabe.
if "silk.pysilk_pin" in sys.builtin_module_names:
    try:
        # Do not initialize the package again if we already have it
        mod = sys.modules["silk.pysilk_pin"]
    except KeyError:
        # initialize the built-in package, then make it available as
        # silk.pysilk_pin.  The following is a mystery, but it seems
        # to work.  NOTE: The imp module is deprecated in Python 3.4.
        import imp
        mod = imp.init_builtin("silk.pysilk_pin")
        import silk.pysilk_pin
        silk.pysilk_pin = mod
        import silk.pysilk_pin as pysilk
else:
    # use version that is linked against libsilk.
    import silk.pysilk as pysilk

import silk.site
from silk.fglob import FGlob

# Differences between versions of Python
if sys.hexversion < 0x02060000:
    # Python 2.[45]
    Integral = (int, long)
    def next(it):
Пример #43
0
import warnings

#  When using PySiLK as a plug-in from a SiLK application, the C parts
#  of the SiLK package (which are in the pysilk module) are compiled
#  into the application itself.  We need to use the 'imp' module to
#  make the "silk.pysilk_pin" code availabe.
if "silk.pysilk_pin" in sys.builtin_module_names:
    try:
        # Do not initialize the package again if we already have it
        mod = sys.modules["silk.pysilk_pin"]
    except KeyError:
        # initialize the built-in package, then make it available as
        # silk.pysilk_pin.  The following is a mystery, but it seems
        # to work.  NOTE: The imp module is deprecated in Python 3.4.
        import imp
        mod = imp.init_builtin("silk.pysilk_pin")
        import silk.pysilk_pin
        silk.pysilk_pin = mod
        import silk.pysilk_pin as pysilk
else:
    # use version that is linked against libsilk.
    import silk.pysilk as pysilk

import silk.site
from silk.fglob import FGlob

# Differences between versions of Python
if sys.hexversion < 0x02060000:
    # Python 2.[45]
    Integral = (int, long)
    def next(it):
Пример #44
0
"""Import hook support.
Пример #45
0
 def getmod(self, nm, isbuiltin=imp.is_builtin):
     # Return initialized built-in module object or None
     # if there is no built-in module with that name.
     return imp.init_builtin(nm)