Load audioservices using importlib instead of imp
imp has been deprecated for quite some time
# See the License for the specific language governing permissions and
# limitations under the License.
-import imp
+import importlib
import sys
import time
from os import listdir
@@ -31,7 +31,7 @@ MAINMODULE = '__init__'
sys.path.append(abspath(dirname(__file__)))
-def create_service_descriptor(service_folder):
+def create_service_spec(service_folder):
"""Prepares a descriptor that can be used together with imp.
Args:
@@ -40,7 +40,11 @@ def create_service_descriptor(service_folder):
Returns:
Dict with import information
"""
- info = imp.find_module(MAINMODULE, [service_folder])
+ module_name = basename(service_folder)
+ path = join(service_folder, MAINMODULE + '.py')
+ spec = importlib.util.spec_from_file_location(module_name, path)
+ mod = importlib.util.module_from_spec(spec)
+ info = {'spec': spec, 'mod': mod, 'module_name': module_name}
return {"name": basename(service_folder), "info": info}
@@ -67,7 +71,7 @@ def get_services(services_folder):
not MAINMODULE + ".py" in listdir(name)):
continue
try:
- services.append(create_service_descriptor(name))
+ services.append(create_service_spec(name))
except Exception:
LOG.error('Failed to create service from ' + name,
exc_info=True)
@@ -75,7 +79,7 @@ def get_services(services_folder):
not MAINMODULE + ".py" in listdir(location)):
continue
try:
- services.append(create_service_descriptor(location))
+ services.append(create_service_spec(location))
except Exception:
LOG.error('Failed to create service from ' + location,
exc_info=True)
@@ -100,8 +104,11 @@ def load_services(config, bus, path=None):
for descriptor in service_directories:
LOG.info('Loading ' + descriptor['name'])
try:
- service_module = imp.load_module(descriptor["name"] + MAINMODULE,
- *descriptor["info"])
+ service_module = descriptor['info']['mod']
+ spec = descriptor['info']['spec']
+ module_name = descriptor['info']['module_name']
+ sys.modules[module_name] = service_module
+ spec.loader.exec_module(service_module)
except Exception as e:
LOG.error('Failed to import module ' + descriptor['name'] + '\n' +
repr(e))
