plugins: when loading plugins, use newer importlib mechanism

fixes #4842
This commit is contained in:
SomberNight 2018-11-11 23:55:34 +01:00
parent aceb022f9d
commit e04e8d2365
No known key found for this signature in database
GPG key ID: B33B5F232C6271E9

View file

@ -26,6 +26,7 @@ import traceback
import sys import sys
import os import os
import pkgutil import pkgutil
import importlib.util
import time import time
import threading import threading
from typing import NamedTuple, Any, Union, TYPE_CHECKING, Optional from typing import NamedTuple, Any, Union, TYPE_CHECKING, Optional
@ -66,9 +67,16 @@ class Plugins(DaemonThread):
def load_plugins(self): def load_plugins(self):
for loader, name, ispkg in pkgutil.iter_modules([self.pkgpath]): for loader, name, ispkg in pkgutil.iter_modules([self.pkgpath]):
mod = pkgutil.find_loader('electrum.plugins.' + name) full_name = f'electrum.plugins.{name}'
m = mod.load_module() spec = importlib.util.find_spec(full_name)
d = m.__dict__ if spec is None: # pkgutil found it but importlib can't ?!
raise Exception(f"Error pre-loading {full_name}: no spec")
try:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
except Exception as e:
raise Exception(f"Error pre-loading {full_name}: {repr(e)}") from e
d = module.__dict__
gui_good = self.gui_name in d.get('available_for', []) gui_good = self.gui_name in d.get('available_for', [])
if not gui_good: if not gui_good:
continue continue
@ -95,16 +103,17 @@ class Plugins(DaemonThread):
def load_plugin(self, name): def load_plugin(self, name):
if name in self.plugins: if name in self.plugins:
return self.plugins[name] return self.plugins[name]
full_name = 'electrum.plugins.' + name + '.' + self.gui_name full_name = f'electrum.plugins.{name}.{self.gui_name}'
loader = pkgutil.find_loader(full_name) spec = importlib.util.find_spec(full_name)
if not loader: if spec is None:
raise RuntimeError("%s implementation for %s plugin not found" raise RuntimeError("%s implementation for %s plugin not found"
% (self.gui_name, name)) % (self.gui_name, name))
try: try:
p = loader.load_module() module = importlib.util.module_from_spec(spec)
plugin = p.Plugin(self, self.config, name) spec.loader.exec_module(module)
plugin = module.Plugin(self, self.config, name)
except Exception as e: except Exception as e:
raise Exception(f"Error loading {name} plugin: {e}") from e raise Exception(f"Error loading {name} plugin: {repr(e)}") from e
self.add_jobs(plugin.thread_jobs()) self.add_jobs(plugin.thread_jobs())
self.plugins[name] = plugin self.plugins[name] = plugin
self.print_error("loaded", name) self.print_error("loaded", name)