Python __builtin__.__import__() Examples

The following are 30 code examples of __builtin__.__import__(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module __builtin__ , or try the search function .
Example #1
Source File: splitbrain.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def disable_splitbrain():
    """Disables (deactivates) the Splitbrain machinery"""
    global _enabled
    if not _enabled:
        return
    _enabled = False
    for funcname, origfunc in _prev_builtins.items():
        setattr(builtins, funcname, origfunc)
    for modname, mod in sys.modules.items():
        if isinstance(mod, RoutedModule):
            sys.modules[modname] = mod.__realmod__
            for ref in gc.get_referrers(mod):
                if isinstance(ref, dict) and "__name__" in ref and ref.get("__file__") is not None:
                    for k, v in ref.items():
                        if v is mod:
                            ref[k] = mod.__realmod__
    sys.modules["sys"] = sys
    builtins.__import__ = _orig_import 
Example #2
Source File: ihooks.py    From BinderFilter with MIT License 6 votes vote down vote up
def import_it(self, partname, fqname, parent, force_load=0):
        if not partname:
            # completely empty module name should only happen in
            # 'from . import' or __import__("")
            return parent
        if not force_load:
            try:
                return self.modules[fqname]
            except KeyError:
                pass
        try:
            path = parent and parent.__path__
        except AttributeError:
            return None
        partname = str(partname)
        stuff = self.loader.find_module(partname, path)
        if not stuff:
            return None
        fqname = str(fqname)
        m = self.loader.load_module(fqname, stuff)
        if parent:
            setattr(parent, partname, m)
        return m 
Example #3
Source File: ihooks.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def import_it(self, partname, fqname, parent, force_load=0):
        if not partname:
            # completely empty module name should only happen in
            # 'from . import' or __import__("")
            return parent
        if not force_load:
            try:
                return self.modules[fqname]
            except KeyError:
                pass
        try:
            path = parent and parent.__path__
        except AttributeError:
            return None
        partname = str(partname)
        stuff = self.loader.find_module(partname, path)
        if not stuff:
            return None
        fqname = str(fqname)
        m = self.loader.load_module(fqname, stuff)
        if parent:
            setattr(parent, partname, m)
        return m 
Example #4
Source File: deepreload.py    From Computable with MIT License 6 votes vote down vote up
def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
    """Replacement for __import__()"""
    parent, buf = get_parent(globals, level)

    head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)

    tail = head
    while name:
        tail, name, buf = load_next(tail, tail, name, buf)

    # If tail is None, both get_parent and load_next found
    # an empty module name: someone called __import__("") or
    # doctored faulty bytecode
    if tail is None:
        raise ValueError('Empty module name')

    if not fromlist:
        return head

    ensure_fromlist(tail, fromlist, buf, 0)
    return tail 
Example #5
Source File: pluginbase.py    From ZEROScan with MIT License 6 votes vote down vote up
def _setup_base_package(module_name):
    try:
        mod = __import__(module_name, None, None, ['__name__'])
    except ImportError:
        mod = None
        if '.' in module_name:
            parent_mod = __import__(module_name.rsplit('.', 1)[0],
                                    None, None, ['__name__'])
        else:
            parent_mod = None

    if mod is None:
        mod = _IntentionallyEmptyModule(module_name)
        if parent_mod is not None:
            setattr(parent_mod, module_name.rsplit('.', 1)[-1], mod)
        sys.modules[module_name] = mod 
Example #6
Source File: ihooks.py    From oss-ftp with MIT License 6 votes vote down vote up
def import_it(self, partname, fqname, parent, force_load=0):
        if not partname:
            # completely empty module name should only happen in
            # 'from . import' or __import__("")
            return parent
        if not force_load:
            try:
                return self.modules[fqname]
            except KeyError:
                pass
        try:
            path = parent and parent.__path__
        except AttributeError:
            return None
        partname = str(partname)
        stuff = self.loader.find_module(partname, path)
        if not stuff:
            return None
        fqname = str(fqname)
        m = self.loader.load_module(fqname, stuff)
        if parent:
            setattr(parent, partname, m)
        return m 
Example #7
Source File: pluginbase.py    From PFramer with GNU General Public License v3.0 6 votes vote down vote up
def _setup_base_package(module_name):
    try:
        mod = __import__(module_name, None, None, ['__name__'])
    except ImportError:
        mod = None
        if '.' in module_name:
            parent_mod = __import__(module_name.rsplit('.', 1)[0],
                                    None, None, ['__name__'])
        else:
            parent_mod = None

    if mod is None:
        mod = _IntentionallyEmptyModule(module_name)
        if parent_mod is not None:
            setattr(parent_mod, module_name.rsplit('.', 1)[-1], mod)
        sys.modules[module_name] = mod 
Example #8
Source File: test_cpickle_jy.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def testWithUserDefinedImport(self):
        """test cPickle calling a user defined import function."""
        # This tests the fix for http://bugs.jython.org/issue1665
        # setup
        original_import = __builtin__.__import__
        def import_hook(name, _globals=None, locals=None, fromlist=None, level= -1):
            return original_import(name, _globals, locals, fromlist, level)
    
        # test
        __builtin__.__import__ = import_hook
        try:
            if "no_such_module" in sys.modules:
                del sys.modules["no_such_module"]  # force cPickle to call __import__
            self.assertRaises(ImportError, cPickle.loads, pickle.GLOBAL + "no_such_module\n" + "no_such_class\n")
        finally:
            __builtin__.__import__ = original_import 
Example #9
Source File: pydev_import_hook.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def do_import(self, name, *args, **kwargs):
        module = self._system_import(name, *args, **kwargs)
        try:
            activate_func = self._modules_to_patch.pop(name, None)
            if activate_func:
                activate_func()  # call activate function
        except:
            if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 2:
                traceback.print_exc()

        # Restore normal system importer to reduce performance impact
        # of calling this method every time an import statement is invoked
        if not self._modules_to_patch:
            builtins.__import__ = self._system_import

        return module 
Example #10
Source File: test_import_jy.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_renamed_bytecode(self):
        source = safe_mktemp(dir=self.dir, suffix='.py')
        fp = open(source, 'w')
        fp.write("test = 'imported'")
        fp.close()

        module = os.path.basename(source)[:-3]
        compiled = module + COMPILED_SUFFIX
        # Compile to bytecode
        module_obj = __import__(module)
        self.assertEquals(module_obj.test, 'imported')
        self.assert_(os.path.exists(compiled))

        # Rename the bytecode
        compiled_moved = safe_mktemp(dir=self.dir, suffix=COMPILED_SUFFIX)
        os.rename(compiled, compiled_moved)

        # Ensure we can still import the renamed bytecode
        moved_module = os.path.basename(compiled_moved)[:-len(COMPILED_SUFFIX)]
        module_obj = __import__(moved_module)
        self.assertEquals(module_obj.__file__, os.path.basename(compiled_moved))
        self.assertEquals(module_obj.test, 'imported') 
Example #11
Source File: test_imp.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_import_from_custom(self):
        import __builtin__
        try:
            class foo(object):
                b = 'abc'
            def __import__(name, globals, locals, fromlist):
                global received
                received = name, fromlist
                return foo()
        
            saved = __builtin__.__import__
            __builtin__.__import__ = __import__
        
            from a import b
            self.assertEqual(received, ('a', ('b', )))
        finally:
            __builtin__.__import__ = saved 
Example #12
Source File: ihooks.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def import_it(self, partname, fqname, parent, force_load=0):
        if not partname:
            # completely empty module name should only happen in
            # 'from . import' or __import__("")
            return parent
        if not force_load:
            try:
                return self.modules[fqname]
            except KeyError:
                pass
        try:
            path = parent and parent.__path__
        except AttributeError:
            return None
        partname = str(partname)
        stuff = self.loader.find_module(partname, path)
        if not stuff:
            return None
        fqname = str(fqname)
        m = self.loader.load_module(fqname, stuff)
        if parent:
            setattr(parent, partname, m)
        return m 
Example #13
Source File: splitbrain.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def disable_splitbrain():
    """Disables (deactivates) the Splitbrain machinery"""
    global _enabled
    if not _enabled:
        return
    _enabled = False
    for funcname, origfunc in _prev_builtins.items():
        setattr(builtins, funcname, origfunc)
    for modname, mod in sys.modules.items():
        if isinstance(mod, RoutedModule):
            sys.modules[modname] = mod.__realmod__
            for ref in gc.get_referrers(mod):
                if isinstance(ref, dict) and "__name__" in ref and ref.get("__file__") is not None:
                    for k, v in ref.items():
                        if v is mod:
                            ref[k] = mod.__realmod__
    sys.modules["sys"] = sys
    builtins.__import__ = _orig_import 
Example #14
Source File: ihooks.py    From meddle with MIT License 6 votes vote down vote up
def import_it(self, partname, fqname, parent, force_load=0):
        if not partname:
            # completely empty module name should only happen in
            # 'from . import' or __import__("")
            return parent
        if not force_load:
            try:
                return self.modules[fqname]
            except KeyError:
                pass
        try:
            path = parent and parent.__path__
        except AttributeError:
            return None
        partname = str(partname)
        stuff = self.loader.find_module(partname, path)
        if not stuff:
            return None
        fqname = str(fqname)
        m = self.loader.load_module(fqname, stuff)
        if parent:
            setattr(parent, partname, m)
        return m 
Example #15
Source File: test_import_jy.py    From medicare-demo with Apache License 2.0 6 votes vote down vote up
def test_symlinks(self):
            # Ensure imports work over symlinks.  Did not work in Jython from
            # 2.1 to 2.5.0, fixed in 2.5.1  See
            # http://bugs.jython.org/issue645615.
            sym = test_support.TESTFN+"1"
            try:
                os.mkdir(test_support.TESTFN)
                init = os.path.join(test_support.TESTFN, "__init__.py")
                fp = open(init, 'w')
                fp.write("test = 'imported'")
                fp.close()
                os.symlink(test_support.TESTFN, sym)
                module = os.path.basename(sym)
                module_obj = __import__(module)
                self.assertEquals(module_obj.test, 'imported')

            finally:
                shutil.rmtree(test_support.TESTFN)
                test_support.unlink(sym) 
Example #16
Source File: test_import_jy.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_issue1952(self):
        # CPython 2.x ignores non-dict's in second arg to __import__
        # The following threw an exception in Jython previously.
        __import__("os", [], level=-1) 
Example #17
Source File: test_import_jy.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_corrupt_bytecode(self):
        f = open("empty$py.class", "w")
        f.close()
        self.assertRaises(ImportError, __import__, "empty") 
Example #18
Source File: test_import_pep328.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def runImport(self, expected, name, globals, fromlist=None, level=None):
        self.expected = expected
        if isinstance(globals, types.ModuleType):
            globals = globals.__dict__
        try:
            if level is not None:
                __import__(name, globals, None, fromlist, level)
            else:
                __import__(name, globals, None, fromlist)                
        except TestImportFunctionError:
            return
        self.fail("Expected a TestImportFunctionError") 
Example #19
Source File: test_import_pep328.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
        __builtin__.__import__ = origImport 
Example #20
Source File: test_import_jy.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_override(self):
        modname = os.path.__name__
        tests = [
            ("import os.path"         , "('os.path', None, -1, 'os')"),
            ("import os.path as path2", "('os.path', None, -1, 'os')"),
            ("from os.path import *"  ,
             "('os.path', ('*',), -1, '%s')" % modname),
            ("from os.path import join",
                 "('os.path', ('join',), -1, '%s')" % modname),
            ("from os.path import join as join2",
                 "('os.path', ('join',), -1, '%s')" % modname),
            ("from os.path import join as join2, split as split2",
                 "('os.path', ('join', 'split'), -1, '%s')" % modname),
        ]

        import sys
        # Replace __builtin__.__import__ to trace the calls
        import __builtin__
        oldimp = __builtin__.__import__
        try:
            def __import__(name, globs, locs, fromlist, level=-1):
                mod = oldimp(name, globs, locs, fromlist, level)
                globs["result"] = str((name, fromlist, level, mod.__name__))
                raise ImportError

            __builtin__.__import__ = __import__
            failed = 0
            for statement, expected in tests:
                try:
                    c = compile(statement, "<unknown>", "exec")
                    exec c in locals(), globals()
                    raise Exception("ImportError expected.")
                except ImportError:
                    pass
                self.assertEquals(expected, result)
        finally:
            __builtin__.__import__ = oldimp 
Example #21
Source File: pluginbase.py    From ZEROScan with MIT License 5 votes vote down vote up
def get_plugin_source(module=None, stacklevel=None):
    """Returns the :class:`PluginSource` for the current module or the given
    module.  The module can be provided by name (in which case an import
    will be attempted) or as a module object.

    If no plugin source can be discovered, the return value from this method
    is `None`.

    This function can be very useful if additional data has been attached
    to the plugin source.  For instance this could allow plugins to get
    access to a back reference to the application that created them.

    :param module: optionally the module to locate the plugin source of.
    :param stacklevel: defines how many levels up the module should search
                       for before it discovers the plugin frame.  The
                       default is 0.  This can be useful for writing wrappers
                       around this function.
    """
    if module is None:
        frm = sys._getframe((stacklevel or 0) + 1)
        name = frm.f_globals['__name__']
        glob = frm.f_globals
    elif isinstance(module, string_types):
        frm = sys._getframe(1)
        name = module
        glob = __import__(module, frm.f_globals,
                          frm.f_locals, ['__dict__']).__dict__
    else:
        name = module.__name__
        glob = module.__dict__
    return _discover_space(name, glob) 
Example #22
Source File: reloader.py    From celery-monitor with GNU General Public License v3.0 5 votes vote down vote up
def _import(name, globals=None, locals=None, fromlist=None, level=_default_level):
	"""__import__() replacement function that tracks module dependencies."""
	# Track our current parent module.  This is used to find our current place
	# in the dependency graph.
	global _parent
	parent = _parent
	_parent = name

	# Perform the actual import work using the base import function.
	base = _baseimport(name, globals, locals, fromlist, level)

	if base is not None and parent is not None:
		m = base

		# We manually walk through the imported hierarchy because the import
		# function only returns the top-level package reference for a nested
		# import statement (e.g. 'package' for `import package.module`) when
		# no fromlist has been specified.  It's possible that the package
		# might not have all of its descendents as attributes, in which case
		# we fall back to using the immediate ancestor of the module instead.
		if fromlist is None:
			for component in name.split('.')[1:]:
				try:
					m = getattr(m, component)
				except AttributeError:
					m = sys.modules[m.__name__ + '.' + component]

		# If this is a nested import for a reloadable (source-based) module,
		# we append ourself to our parent's dependency list.
		if hasattr(m, '__file__'):
			l = _dependencies.setdefault(parent, [])
			l.append(m)

	# Lastly, we always restore our global _parent pointer.
	_parent = parent

	return base 
Example #23
Source File: reloader.py    From celery-monitor with GNU General Public License v3.0 5 votes vote down vote up
def disable():
	"""Disable global module dependency tracking."""
	global _blacklist, _parent
	builtins.__import__ = _baseimport
	_blacklist = None
	_dependencies.clear()
	_parent = None 
Example #24
Source File: remoteproxy.py    From soapy with GNU General Public License v3.0 5 votes vote down vote up
def _import(self, mod, **kwds):
        """
        Request the remote process import a module (or symbols from a module)
        and return the proxied results. Uses built-in __import__() function, but 
        adds a bit more processing:
        
            _import('module')  =>  returns module
            _import('module.submodule')  =>  returns submodule 
                                             (note this differs from behavior of __import__)
            _import('module', fromlist=[name1, name2, ...])  =>  returns [module.name1, module.name2, ...]
                                             (this also differs from behavior of __import__)
            
        """
        return self.send(request='import', callSync='sync', opts=dict(module=mod), **kwds) 
Example #25
Source File: reloader.py    From celery-monitor with GNU General Public License v3.0 5 votes vote down vote up
def enable(blacklist=None):
	"""Enable global module dependency tracking.
	A blacklist can be specified to exclude specific modules (and their import
	hierachies) from the reloading process.  The blacklist can be any iterable
	listing the fully-qualified names of modules that should be ignored.  Note
	that blacklisted modules will still appear in the dependency graph; they
	will just not be reloaded.
	"""
	global _blacklist
	builtins.__import__ = _import
	if blacklist is not None:
		_blacklist = frozenset(blacklist) 
Example #26
Source File: pluginbase.py    From PFramer with GNU General Public License v3.0 5 votes vote down vote up
def load_plugin(self, name):
        """This automatically loads a plugin by the given name from the
        current source and returns the module.  This is a convenient
        alternative to the import statement and saves you from invoking
        ``__import__`` or a similar function yourself.

        :param name: the name of the plugin to load.
        """
        if '.' in name:
            raise ImportError('Plugin names cannot contain dots.')
        with self:
            return __import__(self.base.package + '.' + name,
                              globals(), {}, ['__name__']) 
Example #27
Source File: test_importpkg.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test___import___and_packages(self):
        try:
            mod_backup = dict(sys.modules)
            _f_module = os.path.join(self.test_dir, 'the_test.py')
            _f_dir    = os.path.join(self.test_dir, 'the_dir')
            _f_init   = os.path.join(_f_dir, '__init__.py')
            _f_pkg_y  = os.path.join(_f_dir, 'y.py')
            _f_y      = os.path.join(self.test_dir, 'y.py')

            # write the files
            self.ensure_directory_present(_f_dir)
            self.write_to_file(_f_module, 'import the_dir.y\n')
            self.write_to_file(_f_init, '')
            self.write_to_file(_f_pkg_y, 'a=1\ny = __import__("y")\nimport sys\n')
            self.write_to_file(_f_y, 'a=2\n')

            import y
            self.assertEqual(y.a, 2)

            sys.modules = mod_backup
            mod_backup = dict(sys.modules)

            y = __import__('y', globals(), locals())
            self.assertEqual(y.a, 2)

        finally:
            sys.modules = mod_backup
            os.unlink(_f_module)
            os.unlink(_f_init)
            os.unlink(_f_pkg_y)
            os.unlink(_f_y)
            self.clean_directory(_f_dir)

    #TODO: @skip("multiple_execute") 
Example #28
Source File: typechecker.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def _install_import_hook():
    global _import_hook_installed
    if not _import_hook_installed:
        builtins.__import__ = _pytypes___import__
        _import_hook_installed = True 
Example #29
Source File: pluginbase.py    From PFramer with GNU General Public License v3.0 5 votes vote down vote up
def get_plugin_source(module=None, stacklevel=None):
    """Returns the :class:`PluginSource` for the current module or the given
    module.  The module can be provided by name (in which case an import
    will be attempted) or as a module object.

    If no plugin source can be discovered, the return value from this method
    is `None`.

    This function can be very useful if additional data has been attached
    to the plugin source.  For instance this could allow plugins to get
    access to a back reference to the application that created them.

    :param module: optionally the module to locate the plugin source of.
    :param stacklevel: defines how many levels up the module should search
                       for before it discovers the plugin frame.  The
                       default is 0.  This can be useful for writing wrappers
                       around this function.
    """
    if module is None:
        frm = sys._getframe((stacklevel or 0) + 1)
        name = frm.f_globals['__name__']
        glob = frm.f_globals
    elif isinstance(module, string_types):
        frm = sys._getframe(1)
        name = module
        glob = __import__(module, frm.f_globals,
                          frm.f_locals, ['__dict__']).__dict__
    else:
        name = module.__name__
        glob = module.__dict__
    return _discover_space(name, glob) 
Example #30
Source File: _compat.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __import__(name, globals={}, locals={}, fromlist=[], level=-1):
        """Compatibility definition for Python 2.4.

        Silently ignore the `level` argument missing in Python < 2.5.
        """
        # we need the level arg because the default changed in Python 3.3
        return __builtin__.__import__(name, globals, locals, fromlist)