sys.meta_path.insert

Here are the examples of the python api sys.meta_path.insert taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

21 Examples 7

Example 1

Project: imagrium Source File: test_import_pep328.py
Function: set_up
    def setUp(self):
        self.modX = imp.new_module(self.nameX)
        self.modX.__path__ = ['X']
        
        self.modX2 = imp.new_module(self.nameX+"2")
        self.modY = imp.new_module(self.nameX+".Y")
        self.modY.__path__ = ['X/Y']
        self.modY2 = imp.new_module(self.nameX+".Y2")
        self.modY2.__path__ = ['X/Y']
        self.modZ1 = imp.new_module(self.nameX+".Y.Z1")
        self.modZ2 = imp.new_module(self.nameX+".Y.Z2")

        self.expected = "something_completely_different"
        sys.meta_path.insert(0, self)

Example 2

Project: typesafety Source File: finder.py
Function: install
    def install(self):
        '''
        Install the module finder. If already installed, this will do nothing.
        After installation, each loaded module will be decorated.
        '''

        if not self.installed:
            sys.meta_path.insert(0, self)

Example 3

Project: brython Source File: test_threaded_import.py
Function: test_parallel_meta_path
    def test_parallel_meta_path(self):
        finder = Finder()
        sys.meta_path.insert(0, finder)
        try:
            self.check_parallel_module_init()
            self.assertGreater(finder.numcalls, 0)
            self.assertEqual(finder.x, finder.numcalls)
        finally:
            sys.meta_path.remove(finder)

Example 4

Project: GitSavvy Source File: reload.py
@contextmanager
def intercepting_imports(hook):
    sys.meta_path.insert(0, hook)
    try:
        yield hook
    finally:
        if hook in sys.meta_path:
            sys.meta_path.remove(hook)

Example 5

Project: keystonemiddleware Source File: utils.py
Function: set_up
    def setUp(self):
        """Ensure ImportError for the specified module."""
        super(DisableModuleFixture, self).setUp()

        # Clear 'module' references in sys.modules
        self._cleared_modules.update(self.clear_module())

        finder = NoModuleFinder(self.module)
        self._finders.append(finder)
        sys.meta_path.insert(0, finder)

Example 6

Project: pymo Source File: test_pkgutil.py
Function: set_up
    def setUp(self):
        sys.meta_path.insert(0, self.MyTestImporter())

Example 7

Project: py-impala Source File: __init__.py
Function: register
def register(aliases):
  sys.meta_path.insert(0, Finder(aliases))

Example 8

Project: asv Source File: benchmark.py
def update_sys_path(root):
    sys.meta_path.insert(0, SpecificImporter(os.path.basename(root),
                                             os.path.dirname(root)))

Example 9

Project: brython Source File: test_api.py
    def test_method_called(self):
        # If defined the method should be called.
        class InvalidatingNullFinder:
            def __init__(self, *ignored):
                self.called = False
            def find_module(self, *args):
                return None
            def invalidate_caches(self):
                self.called = True

        key = 'gobledeegook'
        meta_ins = InvalidatingNullFinder()
        path_ins = InvalidatingNullFinder()
        sys.meta_path.insert(0, meta_ins)
        self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
        sys.path_importer_cache[key] = path_ins
        self.addCleanup(lambda: sys.meta_path.remove(meta_ins))
        importlib.invalidate_caches()
        self.assertTrue(meta_ins.called)
        self.assertTrue(path_ins.called)

Example 10

Project: cython Source File: pyximport.py
Function: install
def install(pyximport=True, pyimport=False, build_dir=None, build_in_temp=True,
            setup_args=None, reload_support=False,
            load_py_module_on_import_failure=False, inplace=False,
            language_level=None):
    """Main entry point. Call this to install the .pyx import hook in
    your meta-path for a single Python process.  If you want it to be
    installed whenever you use Python, add it to your sitecustomize
    (as described above).

    You can pass ``pyimport=True`` to also install the .py import hook
    in your meta-path.  Note, however, that it is highly experimental,
    will not work for most .py files, and will therefore only slow
    down your imports.  Use at your own risk.

    By default, compiled modules will end up in a ``.pyxbld``
    directory in the user's home directory.  Passing a different path
    as ``build_dir`` will override this.

    ``build_in_temp=False`` will produce the C files locally. Working
    with complex dependencies and debugging becomes more easy. This
    can principally interfere with existing files of the same name.
    build_in_temp can be overriden by <modulename>.pyxbld/make_setup_args()
    by a dict item of 'build_in_temp'

    ``setup_args``: dict of arguments for Distribution - see
    distutils.core.setup() . They are extended/overriden by those of
    <modulename>.pyxbld/make_setup_args()

    ``reload_support``:  Enables support for dynamic
    reload(<pyxmodulename>), e.g. after a change in the Cython code.
    Additional files <so_path>.reloadNN may arise on that account, when
    the previously loaded module file cannot be overwritten.

    ``load_py_module_on_import_failure``: If the compilation of a .py
    file succeeds, but the subsequent import fails for some reason,
    retry the import with the normal .py module instead of the
    compiled module.  Note that this may lead to unpredictable results
    for modules that change the system state during their import, as
    the second import will rerun these modifications in whatever state
    the system was left after the import of the compiled module
    failed.

    ``inplace``: Install the compiled module next to the source file.

    ``language_level``: The source language level to use: 2 or 3.
    The default is to use the language level of the current Python
    runtime for .py files and Py2 for .pyx files.
    """
    if setup_args is None:
        setup_args = {}
    if not build_dir:
        build_dir = os.path.join(os.path.expanduser('~'), '.pyxbld')
        
    global pyxargs
    pyxargs = PyxArgs()  #$pycheck_no
    pyxargs.build_dir = build_dir
    pyxargs.build_in_temp = build_in_temp
    pyxargs.setup_args = (setup_args or {}).copy()
    pyxargs.reload_support = reload_support
    pyxargs.load_py_module_on_import_failure = load_py_module_on_import_failure

    has_py_importer, has_pyx_importer = _have_importers()
    py_importer, pyx_importer = None, None

    if pyimport and not has_py_importer:
        py_importer = PyImporter(pyxbuild_dir=build_dir, inplace=inplace,
                                 language_level=language_level)
        # make sure we import Cython before we install the import hook
        import Cython.Compiler.Main, Cython.Compiler.Pipeline, Cython.Compiler.Optimize
        sys.meta_path.insert(0, py_importer)

    if pyximport and not has_pyx_importer:
        pyx_importer = PyxImporter(pyxbuild_dir=build_dir, inplace=inplace,
                                   language_level=language_level)
        sys.meta_path.append(pyx_importer)

    return py_importer, pyx_importer

Example 11

Project: attest Source File: hook.py
Function: enable
    @classmethod
    def enable(cls):
        """Enable the import hook."""
        cls.disable()
        sys.meta_path.insert(0, cls())

Example 12

Project: attest Source File: hook.py
Function: enter
    def __enter__(self):
        sys.meta_path.insert(0, self)

Example 13

Project: wrapt Source File: importer.py
Function: register_post_import_hook
@synchronized(_post_import_hooks_lock)
def register_post_import_hook(hook, name):
    # Create a deferred import hook if hook is a string name rather than
    # a callable function.

    if isinstance(hook, string_types):
        hook = _create_import_hook_from_string(hook)

    # Automatically install the import hook finder if it has not already
    # been installed.

    global _post_import_hooks_init

    if not _post_import_hooks_init:
        _post_import_hooks_init = True
        sys.meta_path.insert(0, ImportHookFinder())

    # Determine if any prior registration of a post import hook for
    # the target modules has occurred and act appropriately.

    hooks = _post_import_hooks.get(name, None)

    if hooks is None:
        # No prior registration of post import hooks for the target
        # module. We need to check whether the module has already been
        # imported. If it has we fire the hook immediately and add an
        # empty list to the registry to indicate that the module has
        # already been imported and hooks have fired. Otherwise add
        # the post import hook to the registry.

        module = sys.modules.get(name, None)

        if module is not None:
            _post_import_hooks[name] = []
            hook(module)

        else:
            _post_import_hooks[name] = [hook]

    elif hooks == []:
        # A prior registration of port import hooks for the target
        # module was done and the hooks already fired. Fire the hook
        # immediately.

        module = sys.modules[name]
        hook(module)

    else:
        # A prior registration of port import hooks for the target
        # module was done but the module has not yet been imported.

        _post_import_hooks[name].append(hook)

Example 14

Project: mochi Source File: importer.py
Function: set_importer
def set_importer():
    sys.meta_path.insert(0, Importer())
    sys.path.insert(0, '')

Example 15

Project: django-configurations Source File: importer.py
Function: install
def install(check_options=False):
    global installed
    if not installed:
        orig_create_parser = base.BaseCommand.create_parser

        def create_parser(self, prog_name, subcommand):
            parser = orig_create_parser(self, prog_name, subcommand)
            if isinstance(parser, OptionParser):
                # in case the option_list is set the create_parser
                # will actually return a OptionParser for backward
                # compatibility. In that case we should tack our
                # options on to the end of the parser on the way out.
                for option in configuration_options:
                    parser.add_option(option)
            else:
                # probably argparse, let's not import argparse though
                parser.add_argument(CONFIGURATION_ARGUMENT,
                                    help=CONFIGURATION_ARGUMENT_HELP)
            return parser

        base.BaseCommand.create_parser = create_parser
        importer = ConfigurationImporter(check_options=check_options)
        sys.meta_path.insert(0, importer)
        installed = True

Example 16

Project: django-classbasedsettings Source File: __init__.py
def configure(factory=None, **kwargs):
    if not factory:
        factory = os.environ.get(ENVIRONMENT_VARIABLE)
        if not factory:
            raise ImportError(
                'Settings could not be imported because configure was called'
                ' without arguments and the environment variable %s is'
                ' undefined.' % ENVIRONMENT_VARIABLE)
    if '.' in factory:
        factory_module, factory_name = factory.rsplit('.', 1)
        try:
            mod = import_module(factory_module)
            factory_obj = getattr(mod, factory_name)
        except (ImportError, AttributeError) as err:
            raise SettingsFactoryDoesNotExist(
                'The object "%s" could not be found (Is it on sys.path?):'
                ' %s' % (factory, err))

        settings_obj = factory_obj()
        settings_dict = dict((k, getattr(settings_obj, k)) for k in
                             dir(settings_obj) if not str(k).startswith('_'))

        if 'SETTINGS_MODULE' not in settings_dict:
            settings_dict['SETTINGS_MODULE'] = (
                '%s_%s_unrolledcbsettings' % (factory_module, factory_name))

        # Create an importer for handling imports of our constructed settings
        # module.
        sys.meta_path.insert(
            0,
            SettingsImporter(settings_dict['SETTINGS_MODULE'], settings_dict)
        )

        os.environ[DJANGO_SETTINGS_MODULE] = settings_dict['SETTINGS_MODULE']

        return mod, settings_obj
    else:
        raise InvalidSettingsFactory(
            '%s is not a valid settings factory. Please provide something of'
            ' the form `path.to.MySettingsFactory`' % factory)

Example 17

Project: iot-utilities Source File: test_api.py
Function: test_method_called
    def test_method_called(self):
        # If defined the method should be called.
        class InvalidatingNullFinder:
            def __init__(self, *ignored):
                self.called = False
            def find_module(self, *args):
                return None
            def invalidate_caches(self):
                self.called = True

        key = 'gobledeegook'
        meta_ins = InvalidatingNullFinder()
        path_ins = InvalidatingNullFinder()
        sys.meta_path.insert(0, meta_ins)
        self.addCleanup(lambda: sys.path_importer_cache.__delitem__(key))
        sys.path_importer_cache[key] = path_ins
        self.addCleanup(lambda: sys.meta_path.remove(meta_ins))
        self.init.invalidate_caches()
        self.assertTrue(meta_ins.called)
        self.assertTrue(path_ins.called)

Example 18

Project: django-compat Source File: test_module_loading.py
Function: set_up
    def setUp(self):
        sys.meta_path.insert(0, ProxyFinder())

Example 19

Project: medicare-demo Source File: console.py
Function: main
def main():
    usage ="usage: socialite [options] [script] [script args]"
    from optparse import OptionParser
    parser=OptionParser(usage)
    parser.add_option("-v", "--verbose", action="store_true", dest="v",
                      help="Run SociaLite script with verbose level=1")
    parser.add_option("-c", "--cpu", type="int", default=None, dest="cpu", 
                      help="Set # of cpu to be used")
    parser.add_option("-i", action="store_true", dest="inspect",
                      help="inspect interactively after running script")
    parser.add_option("-d", "--dist", action="store_true", dest="dist",
                      help="Run SociaLite script on a distributed cluster (see conf/ for cluster info).  ")
 
    opts, args = parser.parse_args()

    interactive = False
    if len(args)==0:
        interactive = True

    if opts.cpu==None: SociaLite.init(dist=opts.dist, interactive=interactive, verbose=opts.v)
    else: SociaLite.init(opts.cpu, dist=opts.dist, interactive=interactive, verbose=opts.v)

    if opts.dist: show_cluster_status()

    import atexit
    atexit.register(SociaLite.cleanupOnExit)

    sys.meta_path.insert(0, SocialiteImporter())

    if interactive: 
        installKeyboardInterruptHandler()
        interact(verbose=opts.v)
    else:  
        run_files(args, verbose=opts.v, inspect = opts.inspect)

Example 20

Project: medicare-demo Source File: jy_impSocialite.py
Function: init
def init():
    sys.meta_path.insert(0, SocialiteImporter())

Example 21

Project: opbeat_python Source File: importer.py
Function: register_post_import_hook
@synchronized(_post_import_hooks_lock)
def register_post_import_hook(hook, name):
    # Automatically install the import hook finder if it has not already
    # been installed.

    global _post_import_hooks_init

    if not _post_import_hooks_init:
        _post_import_hooks_init = True
        sys.meta_path.insert(0, ImportHookFinder())

    # Determine if any prior registration of a post import hook for
    # the target modules has occurred and act appropriately.

    hooks = _post_import_hooks.get(name, None)

    if hooks is None:
        # No prior registration of post import hooks for the target
        # module. We need to check whether the module has already been
        # imported. If it has we fire the hook immediately and add an
        # empty list to the registry to indicate that the module has
        # already been imported and hooks have fired. Otherwise add
        # the post import hook to the registry.

        module = sys.modules.get(name, None)

        if module is not None:
            _post_import_hooks[name] = []
            hook(module)

        else:
            _post_import_hooks[name] = [hook]

    elif hooks == []:
        # A prior registration of port import hooks for the target
        # module was done and the hooks already fired. Fire the hook
        # immediately.

        hook(module)

    else:
        # A prior registration of port import hooks for the target
        # module was done but the module has not yet been imported.

        _post_import_hooks[name].append(hook)