From 95c5edb76b60bc9fb9a97be41112e7fe7821f278 Mon Sep 17 00:00:00 2001 From: minerobber Date: Mon, 28 Jan 2019 23:30:50 +0000 Subject: [PATCH] Add initial draft of importlib code --- bot.py | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/bot.py b/bot.py index 2446296..cd1e6e3 100644 --- a/bot.py +++ b/bot.py @@ -1,8 +1,28 @@ -import teambot, sys, traceback, imp, plugin, os +import teambot, sys, traceback, plugin, os +import importlib, importlib.util BOTOP = "~minerobber@127.0.0.1" PREFIX = "!" PLUGIN_MODULES = dict() +PLUGIN_SPECS = dict() + +# hacky re-implementation of reload, uses importlib internals and hardcoded stuffs +def reloadModule(modname): + if modname not in PLUGIN_MODULES: + return False + if modname not in sys.modules: + sys.modules[modname]=PLUGIN_MODULES[modname] + # Alright, this needs some explaining. + # When you do importlib.reload, it does some juju magic shist to find the spec and calls importlib._bootstrap._exec. + # When you dynamically import a module it won't do its magic correctly and it'll error. + # Luckily, we can skip all the juju magic since we can just store the spec. + try: + importlib._bootstrap._exec(PLUGIN_SPECS[modname],PLUGIN_MODULES[modname]) + except: + print("On reloading `{}`:".format(modname)) + traceback.print_exc() + return False + return True class MinerbotPhoenix(teambot.Handler): def on_connection_established(self,*args): @@ -14,13 +34,20 @@ class MinerbotPhoenix(teambot.Handler): bot.handler.load_module(name[:-3],os.path.join("plugins",name)) def load_module(self,modname,path): if modname in PLUGIN_MODULES: - importlib.reload(PLUGIN_MODULES[modname]) + print("{} already imported, reloading".format(modname)) + if reloadModule(modname): + print("{} reloaded".format(modname)) + else: + print("{} reload errored, skipping".format(modname)) return try: + print("importing {}".format(modname)) spec = importlib.util.spec_from_file_location(modname,path) + PLUGIN_SPECS[modname]=spec module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) PLUGIN_MODULES[modname]=module + sys.modules[modname]=module except: print("Unable to load plugin {}".format(modname)) traceback.print_exc()