-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmodutil.py
executable file
·54 lines (35 loc) · 1.05 KB
/
modutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python2
# coding: utf-8
import os
import pkgutil
def submodules(root_module):
mod_path = root_module.__file__
fn = os.path.basename(mod_path)
pathname = os.path.dirname(mod_path)
if fn not in ("__init__.py", "__init__.pyc"):
return None
rst = {}
for imp, name, _ in pkgutil.iter_modules([pathname]):
loader = imp.find_module(name)
mod = loader.load_module(root_module.__name__ + "." + name)
rst[name] = mod
return rst
def submodule_tree(root_module):
rst = submodules(root_module)
if rst is None:
return None
for name, mod in rst.items():
children = submodule_tree(mod)
rst[name] = {"module": mod, "children": children}
return rst
def submodule_leaf_tree(root_module):
rst = submodules(root_module)
if rst is None:
return None
for name, mod in rst.items():
children = submodule_leaf_tree(mod)
if children is None:
rst[name] = mod
else:
rst[name] = children
return rst