In the words of the Pynsive author “Sometimes it’s the simplest project that is most useful”. Pynsive according the the readme is a simple plugin library that uses the sys.meta_path list along with a custom finder and loader definitions to hook into the Python import process. Pynsive also follows PEP 302.
Today I’ll show you the most simple way to use this new library.
Create yourself a project folder and run the following command to install Pynsive:
$ pip install pynsive
Inside your project folder create a folder called plugins. In the project’s root folder create a file called app.py. Inside the plugins folder create a file called myplugin.py.
Note: Anytime you load plugin code using a library like Pynsive you want to be 100% sure you know what code your executing. It can be dangerous to load plugins of which you didn’t write yourself or don’t trust. Always verify the code.
Go into the myplugin.py file and add the following code:
def EchoSomething(str='Hello'): print(str) class HelloWorldClass(object): def __init__(self): print 'Hello World'
I added one class called HelloWorldClass and a standalone function called EchoSomething. As you can tell they simply print some output.
Now, we can write the code to load this file and run the contents.
Go into the app.py and add the following code:
import pynsive plugin_manager = pynsive.PluginManager() plugin_manager.plug_into( '/path/to/your/plugins/') if __name__ == "__main__": try: myplugin = pynsive.import_module('myplugin') myplugin.EchoSomething('Hello Pynsive') hello_class = myplugin.HelloWorldClass() finally: plugin_manager.destroy()
You will need to set your path correctly to the plugins folder. Once that is done you can see I call Pynsive’s import_module and load the plugin. At this point I can call the function EchoSomething and pass an argument to it to echo back. I can also create an instance of the HelloWorldClass and see the output triggered by the class’s constructor.
Hello Pynsive Hello World
A very simple and trivial example to be sure but enough to get started writing plugins. You can experiment further by examining a couple more topics:
Note: Pynsive is still in active development and things may change but you can keep up to date through the documentation.
Feel free to check out my other blog post: Pynsive: A Simple Plugin Library for Python – A Second Look