root / commissioning / api / importing.py @ 9f1a1bd0
History | View | Annotate | Download (1.1 kB)
1 |
from imp import find_module, load_module |
---|---|
2 |
|
3 |
_modules = {} |
4 |
|
5 |
def imp_module(fullname): |
6 |
if fullname in _modules: |
7 |
return _modules[fullname]
|
8 |
|
9 |
components = fullname.split('.')
|
10 |
if not components: |
11 |
raise ValueError('invalid module name') |
12 |
|
13 |
module = None
|
14 |
modulepath = [] |
15 |
|
16 |
for name in components: |
17 |
if not name: |
18 |
raise ValueError("Relative paths not allowed") |
19 |
|
20 |
modulepath.append(name) |
21 |
modulename = '.'.join(modulepath)
|
22 |
if modulename in _modules: |
23 |
module = _modules[modulename] |
24 |
|
25 |
elif hasattr(module, name): |
26 |
module = getattr(module, name)
|
27 |
|
28 |
elif not hasattr(module, '__path__'): |
29 |
m = find_module(name) |
30 |
module = load_module(modulename, *m) |
31 |
|
32 |
else:
|
33 |
try:
|
34 |
m = find_module(name, module.__path__) |
35 |
module = load_module(modulename, *m) |
36 |
except ImportError: |
37 |
m = "No module '%s' in '%s'" % (name, module.__path__)
|
38 |
raise ImportError(m) |
39 |
|
40 |
_modules[modulename] = module |
41 |
|
42 |
return module
|
43 |
|
44 |
|
45 |
def list_modules(): |
46 |
return sorted(_modules.keys()) |
47 |
|
48 |
|