python entry_points
Python setuptools
is amazing. It allows your programs to expose itself to the command line or to other programs.
If you want to expose to command line, do this:
entry_points={
'console_scripts': [
'cursive = cursive.tools.cmd:cursive_command',
],
},
Now, you can use the cursive
command on the cmd after pip installing this package.
You can also expose the program under a certain namespace:
entry_points = {
'my_ep_group_id': [
'my_ep_func = myns.mypkg.mymodule:the_function'
]
},
Here, from any other python program, you can get access to this function using this:
import pkg_resources
named_objects = {}
for ep in pkg_resources.iter_entry_points(group='my_ep_group_id'):
named_objects.update({ep.name: ep.load()})
# call the function like so
named_objects['my_ep_func']()
This is exactly what is being used in statscache as well.
The plugins need to register themselves under the statscache.plugin
namespace in the statscache_plugins
repo and statscache
will just pick them up from there.
for entry_point in pkg_resources.iter_entry_points('statscache.plugin'):
try:
entry_object = entry_point.load()
# the entry-point object is either a plugin or a collection of them
try:
for entry_element in entry_object:
init_plugin(entry_element)
except TypeError:
init_plugin(entry_object)
except Exception:
log.exception("Failed to load plugin from %r" % entry_point)