Files
morbidissimo/modman/modman.py

74 lines
1.8 KiB
Python

from time import sleep
from pathlib import Path
from module import Module, ModuleLoadError, MissingRunFunctionError
from utils import printable_exception
class ModuleManager:
def __init__(self, folder):
self.folder = Path(folder)
self.modules = {}
self.update()
def run(self, sleep_time=1):
while True:
print("-" * 20)
self.update()
sleep(sleep_time)
def update(self):
self._update_cached()
self._update_new()
self._run_all()
def _update_cached(self):
for fn, mod in tuple(self.modules.items()):
if not mod.file_exists():
print(f"{fn} does not exist... removing cached module")
del self.modules[fn]
elif mod.has_changed():
print(f"{fn} has changed... removing cached module for reloading")
del self.modules[fn]
def _update_new(self):
for fn in self.fnames:
if fn in self.modules:
print(f"{fn} already cached... skipping")
continue
mod = Module(fn)
print("loading:", mod)
try:
mod.load()
except ModuleLoadError as e:
print(f"loading {fn} raised", printable_exception(e))
except MissingRunFunctionError as e:
print(f"missing run function in {fn}")
self.modules[fn] = mod
def _run_all(self):
for mod in self.modules.values():
if mod.is_running:
print(f"{mod.name} is running already")
else:
print(f"{mod.name} starting")
mod.start()
@property
def fnames(self):
fns = self.folder.glob("*.py")
return sorted(fns)