|
29
|
1 |
import imp |
|
|
2 |
import os |
|
|
3 |
import sys |
|
|
4 |
|
|
|
5 |
|
|
|
6 |
def module_has_submodule(package, module_name): |
|
|
7 |
"""See if 'module' is in 'package'.""" |
|
|
8 |
name = ".".join([package.__name__, module_name]) |
|
|
9 |
if name in sys.modules: |
|
|
10 |
return True |
|
|
11 |
for finder in sys.meta_path: |
|
|
12 |
if finder.find_module(name): |
|
|
13 |
return True |
|
|
14 |
for entry in package.__path__: # No __path__, then not a package. |
|
|
15 |
try: |
|
|
16 |
# Try the cached finder. |
|
|
17 |
finder = sys.path_importer_cache[entry] |
|
|
18 |
if finder is None: |
|
|
19 |
# Implicit import machinery should be used. |
|
|
20 |
try: |
|
|
21 |
file_, _, _ = imp.find_module(module_name, [entry]) |
|
|
22 |
if file_: |
|
|
23 |
file_.close() |
|
|
24 |
return True |
|
|
25 |
except ImportError: |
|
|
26 |
continue |
|
|
27 |
# Else see if the finder knows of a loader. |
|
|
28 |
elif finder.find_module(name): |
|
|
29 |
return True |
|
|
30 |
else: |
|
|
31 |
continue |
|
|
32 |
except KeyError: |
|
|
33 |
# No cached finder, so try and make one. |
|
|
34 |
for hook in sys.path_hooks: |
|
|
35 |
try: |
|
|
36 |
finder = hook(entry) |
|
|
37 |
# XXX Could cache in sys.path_importer_cache |
|
|
38 |
if finder.find_module(name): |
|
|
39 |
return True |
|
|
40 |
else: |
|
|
41 |
# Once a finder is found, stop the search. |
|
|
42 |
break |
|
|
43 |
except ImportError: |
|
|
44 |
# Continue the search for a finder. |
|
|
45 |
continue |
|
|
46 |
else: |
|
|
47 |
# No finder found. |
|
|
48 |
# Try the implicit import machinery if searching a directory. |
|
|
49 |
if os.path.isdir(entry): |
|
|
50 |
try: |
|
|
51 |
file_, _, _ = imp.find_module(module_name, [entry]) |
|
|
52 |
if file_: |
|
|
53 |
file_.close() |
|
|
54 |
return True |
|
|
55 |
except ImportError: |
|
|
56 |
pass |
|
|
57 |
# XXX Could insert None or NullImporter |
|
|
58 |
else: |
|
|
59 |
# Exhausted the search, so the module cannot be found. |
|
|
60 |
return False |