Merge "Use importlib to take place of imp module"

This commit is contained in:
Zuul
2020-11-23 23:45:21 +00:00
committed by Gerrit Code Review
2 changed files with 22 additions and 4 deletions

View File

@@ -14,7 +14,7 @@
import argparse import argparse
import glob import glob
import hashlib import hashlib
import imp import importlib.util
import inspect import inspect
import itertools import itertools
import math import math
@@ -462,6 +462,15 @@ def get_parsed_args(prog=None):
return options return options
def load_module(name, path):
module_spec = importlib.util.spec_from_file_location(
name, path
)
module = importlib.util.module_from_spec(module_spec)
module_spec.loader.exec_module(module)
return module
def load_check_directory(): def load_check_directory():
"""Return the initialized checks from checks_d, and a mapping of checks that failed to """Return the initialized checks from checks_d, and a mapping of checks that failed to
initialize. Only checks that have a configuration initialize. Only checks that have a configuration
@@ -508,7 +517,7 @@ def load_check_directory():
'Skipping check %s because it has already been loaded from another location', check) 'Skipping check %s because it has already been loaded from another location', check)
continue continue
try: try:
check_module = imp.load_source('checksd_%s' % check_name, check) check_module = load_module('checksd_%s' % check_name, check)
except Exception as e: except Exception as e:
traceback_message = traceback.format_exc() traceback_message = traceback.format_exc()

View File

@@ -12,7 +12,7 @@
# under the License. # under the License.
import glob import glob
import imp import importlib.util
import inspect import inspect
import logging import logging
import os import os
@@ -24,6 +24,15 @@ from monasca_setup.detection import Plugin
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
def load_module(name, path):
module_spec = importlib.util.spec_from_file_location(
name, path
)
module = importlib.util.module_from_spec(module_spec)
module_spec.loader.exec_module(module)
return module
def discover_plugins(custom_path): def discover_plugins(custom_path):
"""Find and import all detection plugins. It will look in detection/plugins dir of the code """Find and import all detection plugins. It will look in detection/plugins dir of the code
as well as custom_path as well as custom_path
@@ -47,7 +56,7 @@ def discover_plugins(custom_path):
if os.path.basename(plugin_path) == '__init__.py': if os.path.basename(plugin_path) == '__init__.py':
continue continue
try: try:
plugin = imp.load_source( plugin = load_module(
os.path.splitext( os.path.splitext(
os.path.basename(plugin_path))[0], os.path.basename(plugin_path))[0],
plugin_path) plugin_path)