Adrian Vladu 954753b6b8 replace imp module with importlib
When trying to run cloudbase-init using Python 3.12, it errors out
ModuleNotFoundError: No module named 'imp'.

The 'imp' module was replaced with similar functionality from module
importlib.

These two implementations are equivalent:

```python
import imp

import os
import site

wmi_path = None
for packages_path in site.getsitepackages():
    path = os.path.join(packages_path, "wmi.py")
    if os.path.isfile(path):
        wmi_path = path
        break

wmi_module_name = "wmi"
wmi_module = imp.load_source(wmi_module_name, wmi_path)

```

```python
import importlib.util

import os
import site

wmi_path = None
for packages_path in site.getsitepackages():
    path = os.path.join(packages_path, "wmi.py")
    if os.path.isfile(path):
        wmi_path = path
        break

wmi_module_name = "wmi"
wmi_module_spec = importlib.util.spec_from_file_location(wmi_module_name, wmi_path)
wmi_module = importlib.util.module_from_spec(wmi_module_spec)
wmi_module_spec.loader.exec_module(wmi_module)
```

Fixes: https://github.com/cloudbase/cloudbase-init/issues/139

Change-Id: I6490c6d9922efea26ab8d167a0d6e41ce34d6c2c
Signed-off-by: Adrian Vladu <avladu@cloudbasesolutions.com>
2024-05-30 14:02:14 +00:00

45 lines
1.4 KiB
Python

# Copyright 2018 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import site
from oslo_log import log as oslo_logging
from cloudbaseinit import exception
from cloudbaseinit.utils.classloader import load_module_from_path
LOG = oslo_logging.getLogger(__name__)
def wmi():
try:
# PyMI depends on the MI API, not available by default on systems older
# than Windows 8 / Windows Server 2012
import wmi
return wmi
except ImportError:
LOG.debug("Couldn't load PyMI module, using legacy WMI")
wmi_path = None
for packages_path in site.getsitepackages():
path = os.path.join(packages_path, "wmi.py")
if os.path.isfile(path):
wmi_path = path
break
if wmi_path is None:
raise exception.ItemNotFoundException("wmi module not found")
return load_module_from_path("wmi", wmi_path)