Created
June 2, 2010 14:49
-
-
Save pjlantz/422458 to your computer and use it in GitHub Desktop.
POC on dynamic module loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# moduleManager.py | |
modules = {} | |
def register(module): | |
""" | |
Decorator to be used for registering a function belonging to a module that | |
handles the configuration for that module | |
""" | |
def registered_module(funct): | |
if module in modules: | |
print "Module " + module + " already registered" | |
return | |
modules[module] = funct | |
return funct | |
return registered_module | |
def execute(module, config): | |
""" | |
Call this function to execute a module with the configurations config | |
""" | |
if module not in modules: | |
print "No such module: " + module | |
return; | |
funct = modules[module] | |
funct(config) | |
def load_modules(file, mods): | |
""" | |
Load module list mods from a file | |
""" | |
with open(file, "r") as fh: | |
for line in fh: | |
line = line.strip() | |
if line.startswith("#") or line == "": | |
continue | |
if line in mods: | |
__import__(line, globals(), locals(), [], -1) | |
# ircModule.py | |
import moduleManager | |
def start(): | |
print "Running irc bot" | |
@moduleManager.register("irc") | |
def handle_config(config): | |
""" | |
Handle configurations, then simply start | |
the bot thread with this config. | |
""" | |
print "Nick: %s" % config["nick"] | |
print "Channel: %s" % config["channel"] | |
start() | |
# modules.list | |
ircModule | |
# test.py - example code on how to use this module system | |
import moduleManager | |
# The function below could be called periodically from a thread to | |
# load modules on runtime, currently it reads modules | |
# from a config file which can be changed to read from db | |
moduleManager.load_modules("modules.list") | |
# configs could be saved/loaded to/from db and | |
# sent to the module as a dictionary as below | |
config = {"nick":"Peppe", "channel":"#irc"} | |
moduleManager.execute("irc", config) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment