1 from __future__
import absolute_import
16 if sys
.version_info
[0] == 2:
17 from StringIO
import StringIO
as BytesIO
18 from StringIO
import StringIO
21 from io
import BytesIO
, StringIO
25 def imp_find_module(name
, path
=None):
27 same as imp.find_module, but handles dotted names
29 names
= name
.split('.')
31 if isinstance(path
, (str, unicode)):
32 path
= [os
.path
.realpath(path
)]
34 result
= imp
.find_module(name
, path
)
35 if result
[0] is not None:
40 def _check_importer_for_path(name
, path_item
):
42 importer
= sys
.path_importer_cache
[path_item
]
44 for path_hook
in sys
.path_hooks
:
46 importer
= path_hook(path_item
)
52 sys
.path_importer_cache
.setdefault(path_item
, importer
)
57 return imp
.find_module(name
, [path_item
])
60 return importer
.find_module(name
)
64 yields namepart, tuple_or_importer for each path item
66 raise ImportError if a name can not be found.
68 warnings
.warn("imp_walk will be removed in a future version", DeprecationWarning)
70 if name
in sys
.builtin_module_names
:
71 yield name
, (None, None, ("", "", imp
.C_BUILTIN
))
75 for namepart
in name
.split('.'):
76 for path_item
in paths
:
77 res
= _check_importer_for_path(namepart
, path_item
)
78 if hasattr(res
, 'load_module'):
79 if res
.path
.endswith('.py') or res
.path
.endswith('.pyw'):
80 fp
= StringIO(res
.get_source(namepart
))
81 res
= (fp
, res
.path
, ('.py', 'rU', imp
.PY_SOURCE
))
82 elif res
.path
.endswith('.pyc') or res
.path
.endswith('.pyo'):
83 co
= res
.get_code(namepart
)
84 fp
= BytesIO(imp
.get_magic() + b
'\0\0\0\0' + marshal
.dumps(co
))
85 res
= (fp
, res
.path
, ('.pyc', 'rb', imp
.PY_COMPILED
))
88 res
= (None, loader
.path
, (os
.path
.splitext(loader
.path
)[-1], 'rb', imp
.C_EXTENSION
))
91 elif isinstance(res
, tuple):
97 paths
= [os
.path
.join(path_item
, namepart
)]
101 raise ImportError('No module named %s' % (name
,))
104 cookie_re
= re
.compile(b
"coding[:=]\s*([-\w.]+)")
105 if sys
.version_info
[0] == 2:
106 default_encoding
= 'ascii'
108 default_encoding
= 'utf-8'
110 def guess_encoding(fp
):
115 m
= cookie_re
.search(ln
)
117 return m
.group(1).decode('ascii')
119 return default_encoding