当前位置: 首页>>代码示例>>Python>>正文


Python pkg_resources.iter_entry_points函数代码示例

本文整理汇总了Python中pkg_resources.iter_entry_points函数的典型用法代码示例。如果您正苦于以下问题:Python iter_entry_points函数的具体用法?Python iter_entry_points怎么用?Python iter_entry_points使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了iter_entry_points函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _default_pin_factory

def _default_pin_factory(name=os.getenv('GPIOZERO_PIN_FACTORY', None)):
    group = 'gpiozero_pin_factories'
    if name is None:
        # If no factory is explicitly specified, try various names in
        # "preferred" order. Note that in this case we only select from
        # gpiozero distribution so without explicitly specifying a name (via
        # the environment) it's impossible to auto-select a factory from
        # outside the base distribution
        #
        # We prefer RPi.GPIO here as it supports PWM, and all Pi revisions. If
        # no third-party libraries are available, however, we fall back to a
        # pure Python implementation which supports platforms like PyPy
        dist = pkg_resources.get_distribution('gpiozero')
        for name in ('rpigpio', 'rpio', 'pigpio', 'native'):
            try:
                return pkg_resources.load_entry_point(dist, group, name)()
            except Exception as e:
                warnings.warn(
                    PinFactoryFallback(
                        'Falling back from %s: %s' % (name, str(e))))
        raise BadPinFactory('Unable to load any default pin factory!')
    else:
        # Try with the name verbatim first. If that fails, attempt with the
        # lower-cased name (this ensures compatibility names work but we're
        # still case insensitive for all factories)
        for factory in pkg_resources.iter_entry_points(group, name):
            return factory.load()()
        for factory in pkg_resources.iter_entry_points(group, name.lower()):
            return factory.load()()
        raise BadPinFactory('Unable to find pin factory "%s"' % name)
开发者ID:DirkUK,项目名称:python-gpiozero,代码行数:30,代码来源:devices.py

示例2: load_external_theme

    def load_external_theme(self, name):
        # type: (unicode) -> None
        """Try to load a theme using entry_points.

        Sphinx refers to ``sphinx_themes`` entry_points.
        """
        # look up for new styled entry_points at first
        entry_points = pkg_resources.iter_entry_points('sphinx.html_themes', name)
        try:
            entry_point = next(entry_points)
            self.app.registry.load_extension(self.app, entry_point.module_name)
            return
        except StopIteration:
            pass

        # look up for old styled entry_points
        for entry_point in pkg_resources.iter_entry_points('sphinx_themes'):
            target = entry_point.load()
            if callable(target):
                themedir = target()
                if not isinstance(themedir, string_types):
                    logger.warning(__('Theme extension %r does not respond correctly.') %
                                   entry_point.module_name)
            else:
                themedir = target

            themes = self.find_themes(themedir)
            for entry, theme in iteritems(themes):
                if name == entry:
                    warnings.warn('``sphinx_themes`` entry point is now deprecated. '
                                  'Please use ``sphinx.html_themes`` instead.',
                                  RemovedInSphinx20Warning)
                    self.themes[name] = theme
开发者ID:hagenw,项目名称:sphinx,代码行数:33,代码来源:theming.py

示例3: _fetch

def _fetch():
    # get blueprints, dists, and so on from pkg_resources.
    #
    # We're careful to load all of the blueprints exactly once and before
    # registering any of them, as this ensures everything is imported before
    # any of the @bp.register-decorated methods are called
    global _blueprints
    global _distributions

    if not _distributions:
        _distributions = {}
        for dist in pkg_resources.WorkingSet():
            dist.relengapi_metadata = {}
            _distributions[dist.key] = dist

    if not _blueprints:
        _blueprints = []
        entry_points = (list(pkg_resources.iter_entry_points('relengapi_blueprints')) +
                        list(pkg_resources.iter_entry_points('relengapi.blueprints')))
        for ep in entry_points:
            bp = ep.load()
            # make sure we have only one copy of each Distribution
            bp.dist = _distributions[ep.dist.key]
            _blueprints.append(bp)

    # look for relengapi metadata for every dist containing a blueprint
    blueprint_dists = {bp.dist.key: bp.dist for bp in _blueprints}.values()
    for dist in blueprint_dists:
        ep = pkg_resources.get_entry_info(dist, 'relengapi.metadata', dist.key)
        if not ep:
            continue
        dist.relengapi_metadata = ep.load()
开发者ID:b10n1k,项目名称:build-relengapi,代码行数:32,代码来源:introspection.py

示例4: install_plugins

def install_plugins(settings):
    from sentry.plugins import register
    # entry_points={
    #    'sentry.plugins': [
    #         'phabricator = sentry_phabricator.plugins:PhabricatorPlugin'
    #     ],
    # },
    installed_apps = list(settings.INSTALLED_APPS)
    for ep in pkg_resources.iter_entry_points('sentry.apps'):
        try:
            plugin = ep.load()
        except Exception:
            import sys
            import traceback

            print >> sys.stderr, "Failed to load app %r:\n%s" % (ep.name, traceback.format_exc())
        else:
            installed_apps.append(ep.module_name)
    settings.INSTALLED_APPS = tuple(installed_apps)

    for ep in pkg_resources.iter_entry_points('sentry.plugins'):
        try:
            plugin = ep.load()
        except Exception:
            import sys
            import traceback

            print >> sys.stderr, "Failed to load plugin %r:\n%s" % (ep.name, traceback.format_exc())
        else:
            register(plugin)
开发者ID:CaseCommonsDevOps,项目名称:sentry,代码行数:30,代码来源:runner.py

示例5: load_tests

def load_tests(loader, tests, pattern):
    for entry in pkg_resources.iter_entry_points('qubes.tests.extra'):
        try:
            for test_case in entry.load()():
                tests.addTests(loader.loadTestsFromTestCase(test_case))
        except Exception as err:  # pylint: disable=broad-except
            def runTest(self):
                raise err
            ExtraLoadFailure = type('ExtraLoadFailure',
                (qubes.tests.QubesTestCase,),
                {entry.name: runTest})
            tests.addTest(ExtraLoadFailure(entry.name))

    for entry in pkg_resources.iter_entry_points(
            'qubes.tests.extra.for_template'):
        try:
            for test_case in entry.load()():
                for template in qubes.tests.list_templates():
                    tests.addTests(loader.loadTestsFromTestCase(
                        type(
                            '{}_{}_{}'.format(
                                entry.name, test_case.__name__, template),
                            (test_case,),
                            {'template': template}
                        )
                    ))
        except Exception as err:  # pylint: disable=broad-except
            def runTest(self):
                raise err
            ExtraForTemplateLoadFailure = type('ExtraForTemplateLoadFailure',
                (qubes.tests.QubesTestCase,),
                {entry.name: runTest})
            tests.addTest(ExtraForTemplateLoadFailure(entry.name))

    return tests
开发者ID:ttasket,项目名称:qubes-core-admin,代码行数:35,代码来源:extra.py

示例6: main

def main(args=None):
    parser = argparse.ArgumentParser(
        description="Releng API Command Line Tool")
    parser.add_argument("--quiet", '-q', action='store_true',
                        help="Silence all logging below WARNING level")
    subparsers = parser.add_subparsers(help='sub-command help')

    # load each of the blueprints; this defines the subcommand classes.  Note that
    # create_app does this again.
    for ep in (list(pkg_resources.iter_entry_points('relengapi_blueprints')) +
               list(pkg_resources.iter_entry_points('relengapi.blueprints'))):
        ep.load()

    subcommands = [cls() for cls in Subcommand.__subclasses__()]
    for subcommand in subcommands:
        subparser = subcommand.make_parser(subparsers)
        subparser.set_defaults(_subcommand=subcommand)

    args = parser.parse_args(args)

    if args._subcommand and args._subcommand.want_logging:
        setupConsoleLogging(args.quiet)

    app = relengapi.app.create_app(cmdline=True)
    with app.app_context():
        args._subcommand.run(parser, args)
开发者ID:grenade,项目名称:build-relengapi,代码行数:26,代码来源:subcommands.py

示例7: py_annotator

def py_annotator(verbose=False):
    """
    find python keyword plugins and update to dicts
    
Accept args:
    verbose:
        show detail message, default: False

    'verbose' argument is only for debug(will generate too mush messages).
    """
    # tw plugin
    for entrypoints in pkg_resources.iter_entry_points("zhpy.twdict"):
        tool = entrypoints.load()
        if verbose:
            print tool.title
        merger(tool.keyword, use_dict=twdict, verbose=verbose)
    merger(twdict, verbose=verbose)
    
    # cn plugin
    for entrypoints in pkg_resources.iter_entry_points("zhpy.cndict"):
        tool = entrypoints.load()
        if verbose:
            print tool.title
        merger(tool.keyword, use_dict=cndict, verbose=verbose)
    merger(cndict, verbose=verbose)
开发者ID:BGCX261,项目名称:zhpy-svn-to-git,代码行数:25,代码来源:zhpy.py

示例8: main

def main(argv=None):
    argv = argv if argv is not None else sys.argv[1:]
    args = manual_argument_parsing(argv)

    # Register patches
    callables = get_entry_callables(
        args.all, args.patches,
        tuple(pkg_resources.iter_entry_points('pymonkey')),
        attr='pymonkey_patch',
    )
    hook = PymonkeyImportHook(callables)
    # Important to insert at the beginning to be ahead of the stdlib importer
    sys.meta_path.insert(0, hook)

    # Allow hooks to do argument parsing
    argv_callables = get_entry_callables(
        args.all, args.patches,
        tuple(pkg_resources.iter_entry_points('pymonkey.argparse')),
        attr='pymonkey_argparse',
    )
    cmd, rest = args.cmd[0], tuple(args.cmd[1:])
    for entry_name, argv_callable in argv_callables.items():
        args, rest = tuple(argv_callable(rest))
        hook.set_entry_data(entry_name, args)

    # Call the thing
    entry, = tuple(pkg_resources.iter_entry_points('console_scripts', cmd))
    sys.argv = [cmd] + list(rest)
    return entry.load()()
开发者ID:asottile,项目名称:pymonkey,代码行数:29,代码来源:pymonkey.py

示例9: workflow_entry_points

def workflow_entry_points():
    """Return an iterator over all example workflows.
    """
    default = default_entry_point()
    return chain([default],
                 pkg_resources.iter_entry_points("orange.widgets.tutorials"),
                 pkg_resources.iter_entry_points("orange.widgets.workflows"))
开发者ID:PrimozGodec,项目名称:orange3,代码行数:7,代码来源:__init__.py

示例10: test_customize_via_pkgutil_entry_point

 def test_customize_via_pkgutil_entry_point(self):
     self.forge.replace(pkg_resources, "iter_entry_points")
     entry_point = self.forge.create_wildcard_mock()
     pkg_resources.iter_entry_points("shakedown.site.customize").and_return(iter([entry_point]))
     entry_point.load().and_return(self.get_customization_function())
     self.forge.replay()
     self.assert_customization_loaded()
开发者ID:alonho,项目名称:shakedown,代码行数:7,代码来源:test_site_customization.py

示例11: trigger

def trigger():
    """Trigger the primary hooks: ``sitehooks`` and ``sitecustomize``.
    
    This function may be called several times, but will only actually
    trigger the hooks once.

    """

    global triggered
    if triggered:
        return
    triggered = True

    entry_points = []
    entry_points.extend(pkg_resources.iter_entry_points('sitehooks'))
    entry_points.extend(pkg_resources.iter_entry_points('sitecustomize'))
    entry_points.sort(key=lambda ep: ep.name)

    for entry_point in entry_points:
        try:
            func = entry_point.load()
            func()
        except Exception as e:
            warnings.warn('%s during sitehook %s: %s\n%s' % (
                e.__class__.__name__,
                entry_point,
                e,
                traceback.format_exc(),
            ))
开发者ID:mikeboers,项目名称:sitehooks,代码行数:29,代码来源:core.py

示例12: load_paths

    def load_paths(self):
        """ Load the names and paths of all moksha applications and widgets.

        We must do this before actually loading the widgets or applications, to
        ensure that we parse and load each of their configuration files
        beforehand.
        """
        for app_entry in pkg_resources.iter_entry_points('moksha.application'):
            if app_entry.name in moksha._apps:
                raise MokshaException('Duplicate application name: %s' %
                                      app_entry.name)
            app_path = app_entry.dist.location
            moksha._apps[app_entry.name] = {
                    'name': app_entry.name,
                    'project_name': app_entry.dist.project_name,
                    'path': app_path,
                    }
        for widget_entry in pkg_resources.iter_entry_points('moksha.widget'):
            if widget_entry.name in moksha._widgets:
                raise MokshaException('Duplicate widget name: %s' %
                                      widget_entry.name)
            widget_path = widget_entry.dist.location
            moksha._widgets[widget_entry.name] = {
                    'name': widget_entry.name,
                    'project_name': widget_entry.dist.project_name,
                    'path': widget_path,
                    }
开发者ID:lmacken,项目名称:moksha,代码行数:27,代码来源:middleware.py

示例13: initialise_options

    def initialise_options( self, options, default_options, profiles, dependencies ):
        options['default_options'] = default_options or {}
        # env.AddMethod( self.get_option, "get_option" )
        cuppa.core.base_options.add_base_options()
        cuppa.modules.registration.add_options( self.toolchains_key )
        cuppa.modules.registration.add_options( self.dependencies_key )
        cuppa.modules.registration.add_options( self.profiles_key )
        cuppa.modules.registration.add_options( self.project_generators_key )
        cuppa.modules.registration.add_options( self.methods_key )

        for method_plugin in pkg_resources.iter_entry_points( group='cuppa.method.plugins', name=None ):
            try:
                method_plugin.load().add_options( SCons.Script.AddOption )
            except AttributeError:
                pass

        if profiles:
            for profile in profiles:
                profile.add_options( SCons.Script.AddOption )

        for profile_plugin in pkg_resources.iter_entry_points( group='cuppa.profile.plugins', name=None ):
            try:
                profile_plugin.load().add_options( SCons.Script.AddOption )
            except AttributeError:
                pass

        if dependencies:
            for dependency in dependencies:
                dependency.add_options( SCons.Script.AddOption )

        for dependency_plugin in pkg_resources.iter_entry_points( group='cuppa.dependency.plugins', name=None ):
            try:
                dependency_plugin.load().add_options( SCons.Script.AddOption )
            except AttributeError:
                pass
开发者ID:ja11sop,项目名称:cuppa,代码行数:35,代码来源:construct.py

示例14: to_foreign

	def to_foreign(self, obj, name, value):  # pylint:disable=unused-argument
		"""Transform to a MongoDB-safe value."""
		
		namespace = self.namespace
		
		try:
			explicit = self.explicit
		except AttributeError:
			explicit = not namespace
		
		if not isinstance(value, (str, unicode)):
			value = canon(value)
		
		if namespace and ':' in value:  # Try to reduce to a known plugin short name.
			for point in iter_entry_points(namespace):  # TODO: Isolate.
				qualname = point.module_name
				
				if point.attrs:
					qualname += ':' + '.'.join(point.attrs)
				
				if qualname == value:
					value = point.name
					break
		
		if ':' in value:
			if not explicit:
				raise ValueError("Explicit object references not allowed.")
			
			return value
		
		if namespace and value not in (i.name for i in iter_entry_points(namespace)):
			raise ValueError('Unknown plugin "' + value + '" for namespace "' + namespace + '".')
		
		return value
开发者ID:marrow,项目名称:mongo,代码行数:34,代码来源:plugin.py

示例15: load_plugins

def load_plugins():  # pragma: no cover
    """Load plugins with groups: isbnlib.metadata & isbnlib.formatters."""
    # get metadata plugins from entry_points
    if options.get('LOAD_METADATA_PLUGINS', True):
        try:
            for entry in iter_entry_points(group='isbnlib.metadata'):
                add_service(entry.name, entry.load())
        except Exception:
            pass
    global PROVIDERS
    _buf = list(services.keys())
    _buf.remove('default')
    PROVIDERS = sorted(_buf)
    # get formatters from entry_points
    if options.get('LOAD_FORMATTER_PLUGINS', True):
        try:
            for entry in iter_entry_points(group='isbnlib.formatters'):
                add_bibformatter(entry.name, entry.load())
        except Exception:
            pass
    global BIBFORMATS
    _buf = list(bibformatters.keys())
    _buf.remove('labels')
    _buf.remove('default')
    BIBFORMATS = sorted(_buf)
开发者ID:xlcnd,项目名称:isbnlib,代码行数:25,代码来源:registry.py


注:本文中的pkg_resources.iter_entry_points函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。