我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.meta_path()。
def mount(self, append=False): pathname = os.path.abspath(os.path.join(self.dirname, self.filename)) if not self.is_compatible(): msg = 'Wheel %s not compatible with this Python.' % pathname raise DistlibException(msg) if not self.is_mountable(): msg = 'Wheel %s is marked as not mountable.' % pathname raise DistlibException(msg) if pathname in sys.path: logger.debug('%s already in path', pathname) else: if append: sys.path.append(pathname) else: sys.path.insert(0, pathname) extensions = self._get_extensions() if extensions: if _hook not in sys.meta_path: sys.meta_path.append(_hook) _hook.add(pathname, extensions)
def mount(self, append=False): pathname = os.path.abspath(os.path.join(self.dirname, self.filename)) if not is_compatible(self): msg = 'Wheel %s not mountable in this Python.' % pathname raise DistlibException(msg) if pathname in sys.path: logger.debug('%s already in path', pathname) else: if append: sys.path.append(pathname) else: sys.path.insert(0, pathname) extensions = self._get_extensions() if extensions: if _hook not in sys.meta_path: sys.meta_path.append(_hook) _hook.add(pathname, extensions)
def setup(self): # we clear this out for various reasons. The most important one is # that a real flaskext could be in there which would disable our # fake package. Secondly we want to make sure that the flaskext # import hook does not break on reloading. for entry, value in list(sys.modules.items()): if (entry.startswith('flask.ext.') or entry.startswith('flask_') or entry.startswith('flaskext.') or entry == 'flaskext') and value is not None: sys.modules.pop(entry, None) from flask import ext reload_module(ext) # reloading must not add more hooks import_hooks = 0 for item in sys.meta_path: cls = type(item) if cls.__module__ == 'flask.exthook' and \ cls.__name__ == 'ExtensionImporter': import_hooks += 1 self.assert_equal(import_hooks, 1)
def __init__(self, request, tmpdir_factory): self.request = request # XXX remove duplication with tmpdir plugin basetmp = tmpdir_factory.ensuretemp("testdir") name = request.function.__name__ for i in range(100): try: tmpdir = basetmp.mkdir(name + str(i)) except py.error.EEXIST: continue break self.tmpdir = tmpdir self.plugins = [] self._savesyspath = (list(sys.path), list(sys.meta_path)) self._savemodulekeys = set(sys.modules) self.chdir() # always chdir self.request.addfinalizer(self.finalize) method = self.request.config.getoption("--runpytest") if method == "inprocess": self._runpytest_method = self.runpytest_inprocess elif method == "subprocess": self._runpytest_method = self.runpytest_subprocess
def register_assert_rewrite(*names): """Register a module name to be rewritten on import. This function will make sure that this module or all modules inside the package will get their assert statements rewritten. Thus you should make sure to call this before the module is actually imported, usually in your __init__.py if you are a plugin using a package. :raise TypeError: if the given module names are not strings. """ for name in names: if not isinstance(name, str): msg = 'expected module names as *args, got {0} instead' raise TypeError(msg.format(repr(names))) for hook in sys.meta_path: if isinstance(hook, rewrite.AssertionRewritingHook): importhook = hook break else: importhook = DummyRewriteHook() importhook.mark_rewrite(*names)
def install_importhook(config): """Try to install the rewrite hook, raise SystemError if it fails.""" # Both Jython and CPython 2.6.0 have AST bugs that make the # assertion rewriting hook malfunction. if (sys.platform.startswith('java') or sys.version_info[:3] == (2, 6, 0)): raise SystemError('rewrite not supported') config._assertstate = AssertionState(config, 'rewrite') config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config) sys.meta_path.insert(0, hook) config._assertstate.trace('installed rewrite import hook') def undo(): hook = config._assertstate.hook if hook is not None and hook in sys.meta_path: sys.meta_path.remove(hook) config.add_cleanup(undo) return hook
def install_hooks(): """ This function installs the future.standard_library import hook into sys.meta_path. """ if PY3: return install_aliases() flog.debug('sys.meta_path was: {0}'.format(sys.meta_path)) flog.debug('Installing hooks ...') # Add it unless it's there already newhook = RenameImport(RENAMES) if not detect_hooks(): sys.meta_path.append(newhook) flog.debug('sys.meta_path is now: {0}'.format(sys.meta_path))
def remove_hooks(scrub_sys_modules=False): """ This function removes the import hook from sys.meta_path. """ if PY3: return flog.debug('Uninstalling hooks ...') # Loop backwards, so deleting items keeps the ordering: for i, hook in list(enumerate(sys.meta_path))[::-1]: if hasattr(hook, 'RENAMER'): del sys.meta_path[i] # Explicit is better than implicit. In the future the interface should # probably change so that scrubbing the import hooks requires a separate # function call. Left as is for now for backward compatibility with # v0.11.x. if scrub_sys_modules: scrub_future_sys_modules()
def activate(): """Install the path-based import components.""" # We should plug filefinder first to avoid plugging ROSDirectoryFinder, when it is not a ROS thing... filefinder2.activate() if ros_path_hook not in sys.path_hooks: # We need to be before FileFinder to be able to find our '.msg' and '.srv' files without making a namespace package # Note this must be early in the path_hook list, since we change the logic # and a namespace package becomes a ros importable package. sys.path_hooks.insert(filefinder2.get_filefinder_index_in_path_hooks(), ros_path_hook) if ROSPathFinder not in sys.meta_path: # adding metahook, before the usual pathfinder, to avoid interferences with python namespace mechanism... sys.meta_path.insert(filefinder2.get_pathfinder_index_in_meta_hooks(), ROSPathFinder) # Resetting sys.path_importer_cache # to support the case where we have an implicit (msg/srv) package inside an already loaded package, # since we need to replace the default importer. sys.path_importer_cache.clear()
def _add_git_repo(url_builder, username=None, repo=None, module=None, branch=None, commit=None): ''' Function that creates and adds to the 'sys.meta_path' an HttpImporter object equipped with a URL of a Online Git server. The 'url_builder' parameter is a function that accepts the username, repo and branch/commit, and creates a HTTP/S URL of a Git server. Compatible functions are '__create_github_url', '__create_bitbucket_url'. The 'username' parameter defines the Github username which is the repository's owner. The 'repo' parameter defines the name of the repo that contains the modules/packages to be imported. The 'module' parameter is optional and is a list containing the modules/packages that are available in the chosen Github repository. If it is not provided, it defaults to the repositories name, as it is common that the a Python repository at "github.com/someuser/somereponame" contains a module/package of "somereponame". The 'branch' and 'commit' parameters cannot be both populated at the same call. They specify the branch (last commit) or specific commit, that should be served. ''' if username == None or repo == None: raise Error("'username' and 'repo' parameters cannot be None") if commit and branch: raise Error("'branch' and 'commit' parameters cannot be both set!") if commit: branch = commit if not branch: branch = 'master' if not module: module = repo if type(module) == str: module = [module] url = url_builder(username, repo, branch) return add_remote_repo(module, url)