Use importlib.util to replace imp
Since the imp module is deprecated and scheduled for removal in
Python 3.12 in favor of importlib, update the relevant libraries to
resolve any ModuleNotFoundError issues with Python 3.12.
Changes:
- use import importlib.util instead of import imp
Tested:
- Ran basic test pass with Python 3.10 and 3.12.
Change-Id: I25dde939dd25268b2ae329b0121858bec20ed03c
Signed-off-by: Brian Ma <chma0@nuvoton.com>
diff --git a/lib/utilities.py b/lib/utilities.py
index 1ec3b71..3c54441 100755
--- a/lib/utilities.py
+++ b/lib/utilities.py
@@ -3,7 +3,7 @@
r"""
Generic utility functions.
"""
-import imp
+import importlib.util
import random
import string
import subprocess
@@ -12,6 +12,16 @@
from robot.utils import DotDict
+def load_source(name, module_path):
+ r"""
+ import util to replace deprecated imp.load_source
+ """
+ spec = importlib.util.spec_from_file_location(name, module_path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
def random_mac():
r"""
Return random mac address in the following format.
@@ -37,7 +47,7 @@
r"""
Return sensor matched ID name.
"""
- m = imp.load_source("module.name", module_name)
+ m = load_source("module.name", module_name)
for i in m.ID_LOOKUP["SENSOR"]:
if m.ID_LOOKUP["SENSOR"][i] == value:
@@ -50,7 +60,7 @@
r"""
Return sensor matched ID name from inventory.
"""
- m = imp.load_source("module.name", module_name)
+ m = load_source("module.name", module_name)
value = string.replace(value, m.INVENTORY_ROOT, "<inventory_root>")
@@ -75,7 +85,7 @@
"""
inventory_list = []
- m = imp.load_source("module.name", module_name)
+ m = load_source("module.name", module_name)
for i in m.ID_LOOKUP["FRU"]:
s = m.ID_LOOKUP["FRU"][i]
@@ -98,7 +108,7 @@
Return FRU URI(s) list of a given type from inventory.
"""
inventory_list = []
- m = imp.load_source("module.name", module_name)
+ m = load_source("module.name", module_name)
for i in m.FRU_INSTANCES.keys():
if m.FRU_INSTANCES[i]["fru_type"] == fru:
@@ -121,7 +131,7 @@
Return VPD URI(s) list of a FRU type from inventory.
"""
inventory_list = []
- m = imp.load_source("module.name", module_name)
+ m = load_source("module.name", module_name)
for i in m.ID_LOOKUP["FRU_STR"]:
x = m.ID_LOOKUP["FRU_STR"][i]