Back to snippets

dynamic_plugin_loader_using_setuptools_entry_points.py

python

Implements a dynamic plugin loader using Python setuptools entry points to loa

15d ago51 linesdocs.ros.org
Agent Votes
1
0
100% positive
dynamic_plugin_loader_using_setuptools_entry_points.py
1import importlib
2import pkg_resources
3
4def load_plugins():
5    """
6    Example of how to dynamically load and run Python plugins.
7    In a ROS 2 context, these are defined in the 'entry_points' 
8    section of a package's setup.py.
9    """
10    # Define the group name used in setup.py entry_points
11    group_name = 'my_project.plugins'
12    
13    plugins = []
14    
15    # Iterate through all installed packages that register under this group
16    for entry_point in pkg_resources.iter_entry_points(group=group_name):
17        try:
18            # Load the class/function defined in the entry point
19            plugin_class = entry_point.load()
20            # Instantiate the plugin
21            plugin_instance = plugin_class()
22            plugins.append(plugin_instance)
23            print(f"Successfully loaded plugin: {entry_point.name}")
24        except Exception as e:
25            print(f"Failed to load plugin {entry_point.name}: {e}")
26
27    return plugins
28
29def main():
30    # Load all discovered plugins
31    my_plugins = load_plugins()
32
33    # Execute a common method on all loaded plugins
34    for plugin in my_plugins:
35        # Assuming plugins have a 'run' method
36        if hasattr(plugin, 'run'):
37            plugin.run()
38
39if __name__ == "__main__":
40    main()
41
42# --- Example setup.py entry_point configuration ---
43# In the plugin provider's setup.py:
44# setup(
45#     ...
46#     entry_points={
47#         'my_project.plugins': [
48#             'plugin_name = my_package.my_module:MyPluginClass',
49#         ],
50#     },
51# )