In my last article on Pynsive I showed you an easy way to get started using Pynsive. Pynsive is a simple plugin library that follows PEP 302. Today I’m going to show you step-by-step how to create and use a plugin context.
Note: The Pynsive documentation has just undergone a large update so getting started just got easier.
The first step is to create a new project. I’m using Virtualenv to keep my projects organized as well as to keep any installed packages in their own project rather than polluting the global site-packages.
Using virtualenv from the terminal I created my project like this:
$ mkdir PythonProjects && cd PythonProjects $ virtualenv PynsiveExample $ cd PynsiveExample $ mkdir src $ mkdir plugins $ source bin/activate $ pip install pynsive $ cd src $ touch app.py $ touch __init__.py $ touch plugins/__init__.py $ touch plugins/myplugin.py
Your project is now setup.
Inside the __init.py__ add the following code:
import pynsive plugin_manager = pynsive.PluginManager() plugin_manager.plug_into('plugins/')
Go into the app.py file and add the following:
def main(): try: import plugins.myplugin as plugin except Exception as ex: print(ex.message) return plugin.EchoSomething() hello_class = plugin.HelloWorldClass() if __name__ == "__main__": main()
Note: Keep in mind you can put your plugins wherever you wish. Just make sure the PluginManager is aware of the location.
The last thing to do is add the code to the myplugin.py file in the plugins folder. Incidentally, this is the same code from my original Pynsive article.
def EchoSomething(str='Hello'): print(str) class HelloWorldClass(object): def __init__(self): print 'Hello World'
Assuming the code is all in the correct places and the project folder structure is correct then you are ready to test it out.
$ python app.py
Hello Hello World