Skip to content

Instantly share code, notes, and snippets.

@lemon24
Last active July 7, 2019 15:55
Show Gist options
  • Save lemon24/cebafa37e90db3fa8bf16b3add27b5d2 to your computer and use it in GitHub Desktop.
Save lemon24/cebafa37e90db3fa8bf16b3add27b5d2 to your computer and use it in GitHub Desktop.
def example():
print('Example!')
import pkg_resources
import configparser
class PluginConfigParser(configparser.ConfigParser):
optionxform = staticmethod(str)
def __init__(self):
super().__init__(
allow_no_value=True,
delimiters=('=', ),
comment_prefixes=('#', ),
inline_comment_prefixes=('#', ),
)
def write_config_with_available_entry_points(file, groups):
import_name = lambda ep: "{ep.module_name}:{ep.attrs[0]}".format(ep=ep)
config = PluginConfigParser()
for group in groups:
entry_points = sorted(pkg_resources.iter_entry_points(group), key=import_name)
config.add_section(group)
for ep in entry_points:
comment = ' # {ep.name} from {ep.dist.project_name}'.format(ep=ep)
config[group][import_name(ep) + comment] = None
config.write(file)
def import_string(import_name):
ep = pkg_resources.EntryPoint.parse('none = ' + import_name)
return ep.load(require=False)
def load_entry_points_from_file(file):
config = PluginConfigParser()
config.read_file(file)
rv = {}
for section in config.sections():
rv[section] = []
for ep in config[section]:
rv.setdefault(section, []).append(import_string(ep))
return rv
if __name__ == '__main__':
import io
file = io.StringIO()
write_config_with_available_entry_points(file, [
'reader.plugins.examples',
'reader.plugins.otherexamples'
])
print(file.getvalue())
file.seek(0)
entry_points = load_entry_points_from_file(file)
for group, entry_points in sorted(entry_points.items()):
for ep in entry_points:
print('running', ep, 'from group', group)
ep()
from setuptools import setup
setup(
name='ExamplePlugin',
version='1.0',
author='lemon24',
url='https://github.com/lemon24/reader',
py_modules=['exampleplugin'],
entry_points={
'reader.plugins.examples': ['example_name=exampleplugin:example'],
},
description="",
)
$ pip install -e .
Obtaining file:///home/lemon/code/reader/_plugins
Installing collected packages: ExamplePlugin
Found existing installation: ExamplePlugin 1.0
Uninstalling ExamplePlugin-1.0:
Successfully uninstalled ExamplePlugin-1.0
Running setup.py develop for ExamplePlugin
Successfully installed ExamplePlugin
$ python loadplugin.py
[reader.plugins.examples]
exampleplugin:example # example_name from ExamplePlugin
[reader.plugins.otherexamples]
running <function example at 0x7f9cfc78b2f0> from group reader.plugins.examples
Example!
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment