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
3
Example 1
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)
3
Example 2
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)
3
Example 3
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)
3
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)
3
Example 5
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)
0
Example 6
def setUp(self):
sys.meta_path.insert(0, self.MyTestImporter())
0
Example 7
def register(aliases):
sys.meta_path.insert(0, Finder(aliases))
0
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)))
0
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)
0
Example 10
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
0
Example 11
@classmethod
def enable(cls):
"""Enable the import hook."""
cls.disable()
sys.meta_path.insert(0, cls())
0
Example 12
def __enter__(self):
sys.meta_path.insert(0, self)
0
Example 13
@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)
0
Example 14
def set_importer():
sys.meta_path.insert(0, Importer())
sys.path.insert(0, '')
0
Example 15
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
0
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)
0
Example 17
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)
0
Example 18
def setUp(self):
sys.meta_path.insert(0, ProxyFinder())
0
Example 19
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)
0
Example 20
def init():
sys.meta_path.insert(0, SocialiteImporter())
0
Example 21
@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)