use python importlib to load and execute extension modules

previously module attributes like __file__ where not set correctly,
leading to scripts getting the directory of the stable-diffusion repo
location instead of their own script.

This causes problem when loading user data from an external location
using the --data-dir flag, as extensions would look for their own code
in the stable-diffusion repo location instead of the data dir location.

Using pythons importlib functions sets the modules specs correctly and
executes them. But this will break extensions if they build paths based
on the previously incorrect __file__ attribute.
This commit is contained in:
Max Audron 2023-01-25 17:55:59 +01:00
parent 5eee2ac398
commit 14c0884fd0

View File

@ -1,16 +1,14 @@
import os import os
import sys import sys
import traceback import traceback
import importlib.util
from types import ModuleType from types import ModuleType
def load_module(path): def load_module(path):
with open(path, "r", encoding="utf8") as file: module_spec = importlib.util.spec_from_file_location(os.path.basename(path), path)
text = file.read() module = importlib.util.module_from_spec(module_spec)
module_spec.loader.exec_module(module)
compiled = compile(text, path, 'exec')
module = ModuleType(os.path.basename(path))
exec(compiled, module.__dict__)
return module return module