1. Sohail
  2. plugins

Wiki

Clone wiki

plugins / Home

This repository contains a simple example of how to create a C++ application which uses Python plugins to add functionality.

About the application

Command-line interface which executes commands entered by the user. For example:

$ build\stage\app.exe plugins
[DEBUG]: Loading 4 plugins.
[DEBUG]: Loading file: plugins/add.py
[DEBUG]: <class 'add.AddCommand'> is a plugin class
[DEBUG]: Loading file: plugins/download-webpage.py
[DEBUG]: <class 'download-webpage.HttpDownloaderCommand'> is a plugin class
[DEBUG]: Loading file: plugins/nested/echo.py
[DEBUG]: <class 'echo.EchoCommand'> is a plugin class
[DEBUG]: Loading file: plugins/nested/noplugin.py
[DEBUG]: Error: class Foo has no attribute '__class__' - ignoring
[DEBUG]: Found 3 Python plugins
[DEBUG]: Instantiating <class 'add.AddCommand'>
[DEBUG]: Instantiating <class 'download-webpage.HttpDownloaderCommand'>
[DEBUG]: Instantiating <class 'echo.EchoCommand'>
>>> help
        add
        echo
        help
        http-download
        reload
Result: OK
>>> add 1 2 3 4 5 6 7 8 9 10.5
Result: 55.5
>>> add 1 2 3 4 'a'
An error occurred: Traceback (most recent call last):

  File "plugins/add.py", line 10, in execute
    result += float(p)

ValueError: invalid literal for float(): 'a'
>>> http-download http://google.com
Result: <!doctype html><html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"><
>>> http-download http://google.com 10
Result: <!doctype
>>> reload
[DEBUG]: Loading 4 plugins.
[DEBUG]: Loading file: plugins/add.py
[DEBUG]: <class 'add.AddCommand'> is a plugin class
[DEBUG]: Loading file: plugins/download-webpage.py
[DEBUG]: <class 'download-webpage.HttpDownloaderCommand'> is a plugin class
[DEBUG]: Loading file: plugins/nested/echo.py
[DEBUG]: <class 'echo.EchoCommand'> is a plugin class
[DEBUG]: Loading file: plugins/nested/noplugin.py
[DEBUG]: Error: class Foo has no attribute '__class__' - ignoring
[DEBUG]: Found 3 Python plugins
[DEBUG]: Instantiating <class 'add.AddCommand'>
[DEBUG]: Instantiating <class 'download-webpage.HttpDownloaderCommand'>
[DEBUG]: Instantiating <class 'echo.EchoCommand'>
Result: reload succeeded
>>> foo
An error occurred: Unknown command

Design

The application has two main extension points: Plugin and Command. The Command class is a sub-class of the Plugin class.

Plugins are loaded by PluginLoader instances. In this application, there is one such loader: the PythonPluginLoader.

Given a path, the PythonPluginLoader recursively loads all .py files looking for classes that inherit from the C++ Plugin class. The Python API is created using Boost.Python.

Hope you find it interesting and useful!

Updated