1 | n/a | """Find modules used by a script, using introspection.""" |
---|
2 | n/a | |
---|
3 | n/a | import dis |
---|
4 | n/a | import importlib._bootstrap_external |
---|
5 | n/a | import importlib.machinery |
---|
6 | n/a | import marshal |
---|
7 | n/a | import os |
---|
8 | n/a | import sys |
---|
9 | n/a | import types |
---|
10 | n/a | import warnings |
---|
11 | n/a | with warnings.catch_warnings(): |
---|
12 | n/a | warnings.simplefilter('ignore', DeprecationWarning) |
---|
13 | n/a | import imp |
---|
14 | n/a | |
---|
15 | n/a | LOAD_CONST = dis.opmap['LOAD_CONST'] |
---|
16 | n/a | IMPORT_NAME = dis.opmap['IMPORT_NAME'] |
---|
17 | n/a | STORE_NAME = dis.opmap['STORE_NAME'] |
---|
18 | n/a | STORE_GLOBAL = dis.opmap['STORE_GLOBAL'] |
---|
19 | n/a | STORE_OPS = STORE_NAME, STORE_GLOBAL |
---|
20 | n/a | EXTENDED_ARG = dis.EXTENDED_ARG |
---|
21 | n/a | |
---|
22 | n/a | # Modulefinder does a good job at simulating Python's, but it can not |
---|
23 | n/a | # handle __path__ modifications packages make at runtime. Therefore there |
---|
24 | n/a | # is a mechanism whereby you can register extra paths in this map for a |
---|
25 | n/a | # package, and it will be honored. |
---|
26 | n/a | |
---|
27 | n/a | # Note this is a mapping is lists of paths. |
---|
28 | n/a | packagePathMap = {} |
---|
29 | n/a | |
---|
30 | n/a | # A Public interface |
---|
31 | n/a | def AddPackagePath(packagename, path): |
---|
32 | n/a | packagePathMap.setdefault(packagename, []).append(path) |
---|
33 | n/a | |
---|
34 | n/a | replacePackageMap = {} |
---|
35 | n/a | |
---|
36 | n/a | # This ReplacePackage mechanism allows modulefinder to work around |
---|
37 | n/a | # situations in which a package injects itself under the name |
---|
38 | n/a | # of another package into sys.modules at runtime by calling |
---|
39 | n/a | # ReplacePackage("real_package_name", "faked_package_name") |
---|
40 | n/a | # before running ModuleFinder. |
---|
41 | n/a | |
---|
42 | n/a | def ReplacePackage(oldname, newname): |
---|
43 | n/a | replacePackageMap[oldname] = newname |
---|
44 | n/a | |
---|
45 | n/a | |
---|
46 | n/a | class Module: |
---|
47 | n/a | |
---|
48 | n/a | def __init__(self, name, file=None, path=None): |
---|
49 | n/a | self.__name__ = name |
---|
50 | n/a | self.__file__ = file |
---|
51 | n/a | self.__path__ = path |
---|
52 | n/a | self.__code__ = None |
---|
53 | n/a | # The set of global names that are assigned to in the module. |
---|
54 | n/a | # This includes those names imported through starimports of |
---|
55 | n/a | # Python modules. |
---|
56 | n/a | self.globalnames = {} |
---|
57 | n/a | # The set of starimports this module did that could not be |
---|
58 | n/a | # resolved, ie. a starimport from a non-Python module. |
---|
59 | n/a | self.starimports = {} |
---|
60 | n/a | |
---|
61 | n/a | def __repr__(self): |
---|
62 | n/a | s = "Module(%r" % (self.__name__,) |
---|
63 | n/a | if self.__file__ is not None: |
---|
64 | n/a | s = s + ", %r" % (self.__file__,) |
---|
65 | n/a | if self.__path__ is not None: |
---|
66 | n/a | s = s + ", %r" % (self.__path__,) |
---|
67 | n/a | s = s + ")" |
---|
68 | n/a | return s |
---|
69 | n/a | |
---|
70 | n/a | class ModuleFinder: |
---|
71 | n/a | |
---|
72 | n/a | def __init__(self, path=None, debug=0, excludes=[], replace_paths=[]): |
---|
73 | n/a | if path is None: |
---|
74 | n/a | path = sys.path |
---|
75 | n/a | self.path = path |
---|
76 | n/a | self.modules = {} |
---|
77 | n/a | self.badmodules = {} |
---|
78 | n/a | self.debug = debug |
---|
79 | n/a | self.indent = 0 |
---|
80 | n/a | self.excludes = excludes |
---|
81 | n/a | self.replace_paths = replace_paths |
---|
82 | n/a | self.processed_paths = [] # Used in debugging only |
---|
83 | n/a | |
---|
84 | n/a | def msg(self, level, str, *args): |
---|
85 | n/a | if level <= self.debug: |
---|
86 | n/a | for i in range(self.indent): |
---|
87 | n/a | print(" ", end=' ') |
---|
88 | n/a | print(str, end=' ') |
---|
89 | n/a | for arg in args: |
---|
90 | n/a | print(repr(arg), end=' ') |
---|
91 | n/a | print() |
---|
92 | n/a | |
---|
93 | n/a | def msgin(self, *args): |
---|
94 | n/a | level = args[0] |
---|
95 | n/a | if level <= self.debug: |
---|
96 | n/a | self.indent = self.indent + 1 |
---|
97 | n/a | self.msg(*args) |
---|
98 | n/a | |
---|
99 | n/a | def msgout(self, *args): |
---|
100 | n/a | level = args[0] |
---|
101 | n/a | if level <= self.debug: |
---|
102 | n/a | self.indent = self.indent - 1 |
---|
103 | n/a | self.msg(*args) |
---|
104 | n/a | |
---|
105 | n/a | def run_script(self, pathname): |
---|
106 | n/a | self.msg(2, "run_script", pathname) |
---|
107 | n/a | with open(pathname) as fp: |
---|
108 | n/a | stuff = ("", "r", imp.PY_SOURCE) |
---|
109 | n/a | self.load_module('__main__', fp, pathname, stuff) |
---|
110 | n/a | |
---|
111 | n/a | def load_file(self, pathname): |
---|
112 | n/a | dir, name = os.path.split(pathname) |
---|
113 | n/a | name, ext = os.path.splitext(name) |
---|
114 | n/a | with open(pathname) as fp: |
---|
115 | n/a | stuff = (ext, "r", imp.PY_SOURCE) |
---|
116 | n/a | self.load_module(name, fp, pathname, stuff) |
---|
117 | n/a | |
---|
118 | n/a | def import_hook(self, name, caller=None, fromlist=None, level=-1): |
---|
119 | n/a | self.msg(3, "import_hook", name, caller, fromlist, level) |
---|
120 | n/a | parent = self.determine_parent(caller, level=level) |
---|
121 | n/a | q, tail = self.find_head_package(parent, name) |
---|
122 | n/a | m = self.load_tail(q, tail) |
---|
123 | n/a | if not fromlist: |
---|
124 | n/a | return q |
---|
125 | n/a | if m.__path__: |
---|
126 | n/a | self.ensure_fromlist(m, fromlist) |
---|
127 | n/a | return None |
---|
128 | n/a | |
---|
129 | n/a | def determine_parent(self, caller, level=-1): |
---|
130 | n/a | self.msgin(4, "determine_parent", caller, level) |
---|
131 | n/a | if not caller or level == 0: |
---|
132 | n/a | self.msgout(4, "determine_parent -> None") |
---|
133 | n/a | return None |
---|
134 | n/a | pname = caller.__name__ |
---|
135 | n/a | if level >= 1: # relative import |
---|
136 | n/a | if caller.__path__: |
---|
137 | n/a | level -= 1 |
---|
138 | n/a | if level == 0: |
---|
139 | n/a | parent = self.modules[pname] |
---|
140 | n/a | assert parent is caller |
---|
141 | n/a | self.msgout(4, "determine_parent ->", parent) |
---|
142 | n/a | return parent |
---|
143 | n/a | if pname.count(".") < level: |
---|
144 | n/a | raise ImportError("relative importpath too deep") |
---|
145 | n/a | pname = ".".join(pname.split(".")[:-level]) |
---|
146 | n/a | parent = self.modules[pname] |
---|
147 | n/a | self.msgout(4, "determine_parent ->", parent) |
---|
148 | n/a | return parent |
---|
149 | n/a | if caller.__path__: |
---|
150 | n/a | parent = self.modules[pname] |
---|
151 | n/a | assert caller is parent |
---|
152 | n/a | self.msgout(4, "determine_parent ->", parent) |
---|
153 | n/a | return parent |
---|
154 | n/a | if '.' in pname: |
---|
155 | n/a | i = pname.rfind('.') |
---|
156 | n/a | pname = pname[:i] |
---|
157 | n/a | parent = self.modules[pname] |
---|
158 | n/a | assert parent.__name__ == pname |
---|
159 | n/a | self.msgout(4, "determine_parent ->", parent) |
---|
160 | n/a | return parent |
---|
161 | n/a | self.msgout(4, "determine_parent -> None") |
---|
162 | n/a | return None |
---|
163 | n/a | |
---|
164 | n/a | def find_head_package(self, parent, name): |
---|
165 | n/a | self.msgin(4, "find_head_package", parent, name) |
---|
166 | n/a | if '.' in name: |
---|
167 | n/a | i = name.find('.') |
---|
168 | n/a | head = name[:i] |
---|
169 | n/a | tail = name[i+1:] |
---|
170 | n/a | else: |
---|
171 | n/a | head = name |
---|
172 | n/a | tail = "" |
---|
173 | n/a | if parent: |
---|
174 | n/a | qname = "%s.%s" % (parent.__name__, head) |
---|
175 | n/a | else: |
---|
176 | n/a | qname = head |
---|
177 | n/a | q = self.import_module(head, qname, parent) |
---|
178 | n/a | if q: |
---|
179 | n/a | self.msgout(4, "find_head_package ->", (q, tail)) |
---|
180 | n/a | return q, tail |
---|
181 | n/a | if parent: |
---|
182 | n/a | qname = head |
---|
183 | n/a | parent = None |
---|
184 | n/a | q = self.import_module(head, qname, parent) |
---|
185 | n/a | if q: |
---|
186 | n/a | self.msgout(4, "find_head_package ->", (q, tail)) |
---|
187 | n/a | return q, tail |
---|
188 | n/a | self.msgout(4, "raise ImportError: No module named", qname) |
---|
189 | n/a | raise ImportError("No module named " + qname) |
---|
190 | n/a | |
---|
191 | n/a | def load_tail(self, q, tail): |
---|
192 | n/a | self.msgin(4, "load_tail", q, tail) |
---|
193 | n/a | m = q |
---|
194 | n/a | while tail: |
---|
195 | n/a | i = tail.find('.') |
---|
196 | n/a | if i < 0: i = len(tail) |
---|
197 | n/a | head, tail = tail[:i], tail[i+1:] |
---|
198 | n/a | mname = "%s.%s" % (m.__name__, head) |
---|
199 | n/a | m = self.import_module(head, mname, m) |
---|
200 | n/a | if not m: |
---|
201 | n/a | self.msgout(4, "raise ImportError: No module named", mname) |
---|
202 | n/a | raise ImportError("No module named " + mname) |
---|
203 | n/a | self.msgout(4, "load_tail ->", m) |
---|
204 | n/a | return m |
---|
205 | n/a | |
---|
206 | n/a | def ensure_fromlist(self, m, fromlist, recursive=0): |
---|
207 | n/a | self.msg(4, "ensure_fromlist", m, fromlist, recursive) |
---|
208 | n/a | for sub in fromlist: |
---|
209 | n/a | if sub == "*": |
---|
210 | n/a | if not recursive: |
---|
211 | n/a | all = self.find_all_submodules(m) |
---|
212 | n/a | if all: |
---|
213 | n/a | self.ensure_fromlist(m, all, 1) |
---|
214 | n/a | elif not hasattr(m, sub): |
---|
215 | n/a | subname = "%s.%s" % (m.__name__, sub) |
---|
216 | n/a | submod = self.import_module(sub, subname, m) |
---|
217 | n/a | if not submod: |
---|
218 | n/a | raise ImportError("No module named " + subname) |
---|
219 | n/a | |
---|
220 | n/a | def find_all_submodules(self, m): |
---|
221 | n/a | if not m.__path__: |
---|
222 | n/a | return |
---|
223 | n/a | modules = {} |
---|
224 | n/a | # 'suffixes' used to be a list hardcoded to [".py", ".pyc"]. |
---|
225 | n/a | # But we must also collect Python extension modules - although |
---|
226 | n/a | # we cannot separate normal dlls from Python extensions. |
---|
227 | n/a | suffixes = [] |
---|
228 | n/a | suffixes += importlib.machinery.EXTENSION_SUFFIXES[:] |
---|
229 | n/a | suffixes += importlib.machinery.SOURCE_SUFFIXES[:] |
---|
230 | n/a | suffixes += importlib.machinery.BYTECODE_SUFFIXES[:] |
---|
231 | n/a | for dir in m.__path__: |
---|
232 | n/a | try: |
---|
233 | n/a | names = os.listdir(dir) |
---|
234 | n/a | except OSError: |
---|
235 | n/a | self.msg(2, "can't list directory", dir) |
---|
236 | n/a | continue |
---|
237 | n/a | for name in names: |
---|
238 | n/a | mod = None |
---|
239 | n/a | for suff in suffixes: |
---|
240 | n/a | n = len(suff) |
---|
241 | n/a | if name[-n:] == suff: |
---|
242 | n/a | mod = name[:-n] |
---|
243 | n/a | break |
---|
244 | n/a | if mod and mod != "__init__": |
---|
245 | n/a | modules[mod] = mod |
---|
246 | n/a | return modules.keys() |
---|
247 | n/a | |
---|
248 | n/a | def import_module(self, partname, fqname, parent): |
---|
249 | n/a | self.msgin(3, "import_module", partname, fqname, parent) |
---|
250 | n/a | try: |
---|
251 | n/a | m = self.modules[fqname] |
---|
252 | n/a | except KeyError: |
---|
253 | n/a | pass |
---|
254 | n/a | else: |
---|
255 | n/a | self.msgout(3, "import_module ->", m) |
---|
256 | n/a | return m |
---|
257 | n/a | if fqname in self.badmodules: |
---|
258 | n/a | self.msgout(3, "import_module -> None") |
---|
259 | n/a | return None |
---|
260 | n/a | if parent and parent.__path__ is None: |
---|
261 | n/a | self.msgout(3, "import_module -> None") |
---|
262 | n/a | return None |
---|
263 | n/a | try: |
---|
264 | n/a | fp, pathname, stuff = self.find_module(partname, |
---|
265 | n/a | parent and parent.__path__, parent) |
---|
266 | n/a | except ImportError: |
---|
267 | n/a | self.msgout(3, "import_module ->", None) |
---|
268 | n/a | return None |
---|
269 | n/a | try: |
---|
270 | n/a | m = self.load_module(fqname, fp, pathname, stuff) |
---|
271 | n/a | finally: |
---|
272 | n/a | if fp: |
---|
273 | n/a | fp.close() |
---|
274 | n/a | if parent: |
---|
275 | n/a | setattr(parent, partname, m) |
---|
276 | n/a | self.msgout(3, "import_module ->", m) |
---|
277 | n/a | return m |
---|
278 | n/a | |
---|
279 | n/a | def load_module(self, fqname, fp, pathname, file_info): |
---|
280 | n/a | suffix, mode, type = file_info |
---|
281 | n/a | self.msgin(2, "load_module", fqname, fp and "fp", pathname) |
---|
282 | n/a | if type == imp.PKG_DIRECTORY: |
---|
283 | n/a | m = self.load_package(fqname, pathname) |
---|
284 | n/a | self.msgout(2, "load_module ->", m) |
---|
285 | n/a | return m |
---|
286 | n/a | if type == imp.PY_SOURCE: |
---|
287 | n/a | co = compile(fp.read()+'\n', pathname, 'exec') |
---|
288 | n/a | elif type == imp.PY_COMPILED: |
---|
289 | n/a | try: |
---|
290 | n/a | marshal_data = importlib._bootstrap_external._validate_bytecode_header(fp.read()) |
---|
291 | n/a | except ImportError as exc: |
---|
292 | n/a | self.msgout(2, "raise ImportError: " + str(exc), pathname) |
---|
293 | n/a | raise |
---|
294 | n/a | co = marshal.loads(marshal_data) |
---|
295 | n/a | else: |
---|
296 | n/a | co = None |
---|
297 | n/a | m = self.add_module(fqname) |
---|
298 | n/a | m.__file__ = pathname |
---|
299 | n/a | if co: |
---|
300 | n/a | if self.replace_paths: |
---|
301 | n/a | co = self.replace_paths_in_code(co) |
---|
302 | n/a | m.__code__ = co |
---|
303 | n/a | self.scan_code(co, m) |
---|
304 | n/a | self.msgout(2, "load_module ->", m) |
---|
305 | n/a | return m |
---|
306 | n/a | |
---|
307 | n/a | def _add_badmodule(self, name, caller): |
---|
308 | n/a | if name not in self.badmodules: |
---|
309 | n/a | self.badmodules[name] = {} |
---|
310 | n/a | if caller: |
---|
311 | n/a | self.badmodules[name][caller.__name__] = 1 |
---|
312 | n/a | else: |
---|
313 | n/a | self.badmodules[name]["-"] = 1 |
---|
314 | n/a | |
---|
315 | n/a | def _safe_import_hook(self, name, caller, fromlist, level=-1): |
---|
316 | n/a | # wrapper for self.import_hook() that won't raise ImportError |
---|
317 | n/a | if name in self.badmodules: |
---|
318 | n/a | self._add_badmodule(name, caller) |
---|
319 | n/a | return |
---|
320 | n/a | try: |
---|
321 | n/a | self.import_hook(name, caller, level=level) |
---|
322 | n/a | except ImportError as msg: |
---|
323 | n/a | self.msg(2, "ImportError:", str(msg)) |
---|
324 | n/a | self._add_badmodule(name, caller) |
---|
325 | n/a | else: |
---|
326 | n/a | if fromlist: |
---|
327 | n/a | for sub in fromlist: |
---|
328 | n/a | if sub in self.badmodules: |
---|
329 | n/a | self._add_badmodule(sub, caller) |
---|
330 | n/a | continue |
---|
331 | n/a | try: |
---|
332 | n/a | self.import_hook(name, caller, [sub], level=level) |
---|
333 | n/a | except ImportError as msg: |
---|
334 | n/a | self.msg(2, "ImportError:", str(msg)) |
---|
335 | n/a | fullname = name + "." + sub |
---|
336 | n/a | self._add_badmodule(fullname, caller) |
---|
337 | n/a | |
---|
338 | n/a | def scan_opcodes(self, co): |
---|
339 | n/a | # Scan the code, and yield 'interesting' opcode combinations |
---|
340 | n/a | code = co.co_code |
---|
341 | n/a | names = co.co_names |
---|
342 | n/a | consts = co.co_consts |
---|
343 | n/a | opargs = [(op, arg) for _, op, arg in dis._unpack_opargs(code) |
---|
344 | n/a | if op != EXTENDED_ARG] |
---|
345 | n/a | for i, (op, oparg) in enumerate(opargs): |
---|
346 | n/a | if op in STORE_OPS: |
---|
347 | n/a | yield "store", (names[oparg],) |
---|
348 | n/a | continue |
---|
349 | n/a | if (op == IMPORT_NAME and i >= 2 |
---|
350 | n/a | and opargs[i-1][0] == opargs[i-2][0] == LOAD_CONST): |
---|
351 | n/a | level = consts[opargs[i-2][1]] |
---|
352 | n/a | fromlist = consts[opargs[i-1][1]] |
---|
353 | n/a | if level == 0: # absolute import |
---|
354 | n/a | yield "absolute_import", (fromlist, names[oparg]) |
---|
355 | n/a | else: # relative import |
---|
356 | n/a | yield "relative_import", (level, fromlist, names[oparg]) |
---|
357 | n/a | continue |
---|
358 | n/a | |
---|
359 | n/a | def scan_code(self, co, m): |
---|
360 | n/a | code = co.co_code |
---|
361 | n/a | scanner = self.scan_opcodes |
---|
362 | n/a | for what, args in scanner(co): |
---|
363 | n/a | if what == "store": |
---|
364 | n/a | name, = args |
---|
365 | n/a | m.globalnames[name] = 1 |
---|
366 | n/a | elif what == "absolute_import": |
---|
367 | n/a | fromlist, name = args |
---|
368 | n/a | have_star = 0 |
---|
369 | n/a | if fromlist is not None: |
---|
370 | n/a | if "*" in fromlist: |
---|
371 | n/a | have_star = 1 |
---|
372 | n/a | fromlist = [f for f in fromlist if f != "*"] |
---|
373 | n/a | self._safe_import_hook(name, m, fromlist, level=0) |
---|
374 | n/a | if have_star: |
---|
375 | n/a | # We've encountered an "import *". If it is a Python module, |
---|
376 | n/a | # the code has already been parsed and we can suck out the |
---|
377 | n/a | # global names. |
---|
378 | n/a | mm = None |
---|
379 | n/a | if m.__path__: |
---|
380 | n/a | # At this point we don't know whether 'name' is a |
---|
381 | n/a | # submodule of 'm' or a global module. Let's just try |
---|
382 | n/a | # the full name first. |
---|
383 | n/a | mm = self.modules.get(m.__name__ + "." + name) |
---|
384 | n/a | if mm is None: |
---|
385 | n/a | mm = self.modules.get(name) |
---|
386 | n/a | if mm is not None: |
---|
387 | n/a | m.globalnames.update(mm.globalnames) |
---|
388 | n/a | m.starimports.update(mm.starimports) |
---|
389 | n/a | if mm.__code__ is None: |
---|
390 | n/a | m.starimports[name] = 1 |
---|
391 | n/a | else: |
---|
392 | n/a | m.starimports[name] = 1 |
---|
393 | n/a | elif what == "relative_import": |
---|
394 | n/a | level, fromlist, name = args |
---|
395 | n/a | if name: |
---|
396 | n/a | self._safe_import_hook(name, m, fromlist, level=level) |
---|
397 | n/a | else: |
---|
398 | n/a | parent = self.determine_parent(m, level=level) |
---|
399 | n/a | self._safe_import_hook(parent.__name__, None, fromlist, level=0) |
---|
400 | n/a | else: |
---|
401 | n/a | # We don't expect anything else from the generator. |
---|
402 | n/a | raise RuntimeError(what) |
---|
403 | n/a | |
---|
404 | n/a | for c in co.co_consts: |
---|
405 | n/a | if isinstance(c, type(co)): |
---|
406 | n/a | self.scan_code(c, m) |
---|
407 | n/a | |
---|
408 | n/a | def load_package(self, fqname, pathname): |
---|
409 | n/a | self.msgin(2, "load_package", fqname, pathname) |
---|
410 | n/a | newname = replacePackageMap.get(fqname) |
---|
411 | n/a | if newname: |
---|
412 | n/a | fqname = newname |
---|
413 | n/a | m = self.add_module(fqname) |
---|
414 | n/a | m.__file__ = pathname |
---|
415 | n/a | m.__path__ = [pathname] |
---|
416 | n/a | |
---|
417 | n/a | # As per comment at top of file, simulate runtime __path__ additions. |
---|
418 | n/a | m.__path__ = m.__path__ + packagePathMap.get(fqname, []) |
---|
419 | n/a | |
---|
420 | n/a | fp, buf, stuff = self.find_module("__init__", m.__path__) |
---|
421 | n/a | try: |
---|
422 | n/a | self.load_module(fqname, fp, buf, stuff) |
---|
423 | n/a | self.msgout(2, "load_package ->", m) |
---|
424 | n/a | return m |
---|
425 | n/a | finally: |
---|
426 | n/a | if fp: |
---|
427 | n/a | fp.close() |
---|
428 | n/a | |
---|
429 | n/a | def add_module(self, fqname): |
---|
430 | n/a | if fqname in self.modules: |
---|
431 | n/a | return self.modules[fqname] |
---|
432 | n/a | self.modules[fqname] = m = Module(fqname) |
---|
433 | n/a | return m |
---|
434 | n/a | |
---|
435 | n/a | def find_module(self, name, path, parent=None): |
---|
436 | n/a | if parent is not None: |
---|
437 | n/a | # assert path is not None |
---|
438 | n/a | fullname = parent.__name__+'.'+name |
---|
439 | n/a | else: |
---|
440 | n/a | fullname = name |
---|
441 | n/a | if fullname in self.excludes: |
---|
442 | n/a | self.msgout(3, "find_module -> Excluded", fullname) |
---|
443 | n/a | raise ImportError(name) |
---|
444 | n/a | |
---|
445 | n/a | if path is None: |
---|
446 | n/a | if name in sys.builtin_module_names: |
---|
447 | n/a | return (None, None, ("", "", imp.C_BUILTIN)) |
---|
448 | n/a | |
---|
449 | n/a | path = self.path |
---|
450 | n/a | return imp.find_module(name, path) |
---|
451 | n/a | |
---|
452 | n/a | def report(self): |
---|
453 | n/a | """Print a report to stdout, listing the found modules with their |
---|
454 | n/a | paths, as well as modules that are missing, or seem to be missing. |
---|
455 | n/a | """ |
---|
456 | n/a | print() |
---|
457 | n/a | print(" %-25s %s" % ("Name", "File")) |
---|
458 | n/a | print(" %-25s %s" % ("----", "----")) |
---|
459 | n/a | # Print modules found |
---|
460 | n/a | keys = sorted(self.modules.keys()) |
---|
461 | n/a | for key in keys: |
---|
462 | n/a | m = self.modules[key] |
---|
463 | n/a | if m.__path__: |
---|
464 | n/a | print("P", end=' ') |
---|
465 | n/a | else: |
---|
466 | n/a | print("m", end=' ') |
---|
467 | n/a | print("%-25s" % key, m.__file__ or "") |
---|
468 | n/a | |
---|
469 | n/a | # Print missing modules |
---|
470 | n/a | missing, maybe = self.any_missing_maybe() |
---|
471 | n/a | if missing: |
---|
472 | n/a | print() |
---|
473 | n/a | print("Missing modules:") |
---|
474 | n/a | for name in missing: |
---|
475 | n/a | mods = sorted(self.badmodules[name].keys()) |
---|
476 | n/a | print("?", name, "imported from", ', '.join(mods)) |
---|
477 | n/a | # Print modules that may be missing, but then again, maybe not... |
---|
478 | n/a | if maybe: |
---|
479 | n/a | print() |
---|
480 | n/a | print("Submodules that appear to be missing, but could also be", end=' ') |
---|
481 | n/a | print("global names in the parent package:") |
---|
482 | n/a | for name in maybe: |
---|
483 | n/a | mods = sorted(self.badmodules[name].keys()) |
---|
484 | n/a | print("?", name, "imported from", ', '.join(mods)) |
---|
485 | n/a | |
---|
486 | n/a | def any_missing(self): |
---|
487 | n/a | """Return a list of modules that appear to be missing. Use |
---|
488 | n/a | any_missing_maybe() if you want to know which modules are |
---|
489 | n/a | certain to be missing, and which *may* be missing. |
---|
490 | n/a | """ |
---|
491 | n/a | missing, maybe = self.any_missing_maybe() |
---|
492 | n/a | return missing + maybe |
---|
493 | n/a | |
---|
494 | n/a | def any_missing_maybe(self): |
---|
495 | n/a | """Return two lists, one with modules that are certainly missing |
---|
496 | n/a | and one with modules that *may* be missing. The latter names could |
---|
497 | n/a | either be submodules *or* just global names in the package. |
---|
498 | n/a | |
---|
499 | n/a | The reason it can't always be determined is that it's impossible to |
---|
500 | n/a | tell which names are imported when "from module import *" is done |
---|
501 | n/a | with an extension module, short of actually importing it. |
---|
502 | n/a | """ |
---|
503 | n/a | missing = [] |
---|
504 | n/a | maybe = [] |
---|
505 | n/a | for name in self.badmodules: |
---|
506 | n/a | if name in self.excludes: |
---|
507 | n/a | continue |
---|
508 | n/a | i = name.rfind(".") |
---|
509 | n/a | if i < 0: |
---|
510 | n/a | missing.append(name) |
---|
511 | n/a | continue |
---|
512 | n/a | subname = name[i+1:] |
---|
513 | n/a | pkgname = name[:i] |
---|
514 | n/a | pkg = self.modules.get(pkgname) |
---|
515 | n/a | if pkg is not None: |
---|
516 | n/a | if pkgname in self.badmodules[name]: |
---|
517 | n/a | # The package tried to import this module itself and |
---|
518 | n/a | # failed. It's definitely missing. |
---|
519 | n/a | missing.append(name) |
---|
520 | n/a | elif subname in pkg.globalnames: |
---|
521 | n/a | # It's a global in the package: definitely not missing. |
---|
522 | n/a | pass |
---|
523 | n/a | elif pkg.starimports: |
---|
524 | n/a | # It could be missing, but the package did an "import *" |
---|
525 | n/a | # from a non-Python module, so we simply can't be sure. |
---|
526 | n/a | maybe.append(name) |
---|
527 | n/a | else: |
---|
528 | n/a | # It's not a global in the package, the package didn't |
---|
529 | n/a | # do funny star imports, it's very likely to be missing. |
---|
530 | n/a | # The symbol could be inserted into the package from the |
---|
531 | n/a | # outside, but since that's not good style we simply list |
---|
532 | n/a | # it missing. |
---|
533 | n/a | missing.append(name) |
---|
534 | n/a | else: |
---|
535 | n/a | missing.append(name) |
---|
536 | n/a | missing.sort() |
---|
537 | n/a | maybe.sort() |
---|
538 | n/a | return missing, maybe |
---|
539 | n/a | |
---|
540 | n/a | def replace_paths_in_code(self, co): |
---|
541 | n/a | new_filename = original_filename = os.path.normpath(co.co_filename) |
---|
542 | n/a | for f, r in self.replace_paths: |
---|
543 | n/a | if original_filename.startswith(f): |
---|
544 | n/a | new_filename = r + original_filename[len(f):] |
---|
545 | n/a | break |
---|
546 | n/a | |
---|
547 | n/a | if self.debug and original_filename not in self.processed_paths: |
---|
548 | n/a | if new_filename != original_filename: |
---|
549 | n/a | self.msgout(2, "co_filename %r changed to %r" \ |
---|
550 | n/a | % (original_filename,new_filename,)) |
---|
551 | n/a | else: |
---|
552 | n/a | self.msgout(2, "co_filename %r remains unchanged" \ |
---|
553 | n/a | % (original_filename,)) |
---|
554 | n/a | self.processed_paths.append(original_filename) |
---|
555 | n/a | |
---|
556 | n/a | consts = list(co.co_consts) |
---|
557 | n/a | for i in range(len(consts)): |
---|
558 | n/a | if isinstance(consts[i], type(co)): |
---|
559 | n/a | consts[i] = self.replace_paths_in_code(consts[i]) |
---|
560 | n/a | |
---|
561 | n/a | return types.CodeType(co.co_argcount, co.co_kwonlyargcount, |
---|
562 | n/a | co.co_nlocals, co.co_stacksize, co.co_flags, |
---|
563 | n/a | co.co_code, tuple(consts), co.co_names, |
---|
564 | n/a | co.co_varnames, new_filename, co.co_name, |
---|
565 | n/a | co.co_firstlineno, co.co_lnotab, co.co_freevars, |
---|
566 | n/a | co.co_cellvars) |
---|
567 | n/a | |
---|
568 | n/a | |
---|
569 | n/a | def test(): |
---|
570 | n/a | # Parse command line |
---|
571 | n/a | import getopt |
---|
572 | n/a | try: |
---|
573 | n/a | opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:") |
---|
574 | n/a | except getopt.error as msg: |
---|
575 | n/a | print(msg) |
---|
576 | n/a | return |
---|
577 | n/a | |
---|
578 | n/a | # Process options |
---|
579 | n/a | debug = 1 |
---|
580 | n/a | domods = 0 |
---|
581 | n/a | addpath = [] |
---|
582 | n/a | exclude = [] |
---|
583 | n/a | for o, a in opts: |
---|
584 | n/a | if o == '-d': |
---|
585 | n/a | debug = debug + 1 |
---|
586 | n/a | if o == '-m': |
---|
587 | n/a | domods = 1 |
---|
588 | n/a | if o == '-p': |
---|
589 | n/a | addpath = addpath + a.split(os.pathsep) |
---|
590 | n/a | if o == '-q': |
---|
591 | n/a | debug = 0 |
---|
592 | n/a | if o == '-x': |
---|
593 | n/a | exclude.append(a) |
---|
594 | n/a | |
---|
595 | n/a | # Provide default arguments |
---|
596 | n/a | if not args: |
---|
597 | n/a | script = "hello.py" |
---|
598 | n/a | else: |
---|
599 | n/a | script = args[0] |
---|
600 | n/a | |
---|
601 | n/a | # Set the path based on sys.path and the script directory |
---|
602 | n/a | path = sys.path[:] |
---|
603 | n/a | path[0] = os.path.dirname(script) |
---|
604 | n/a | path = addpath + path |
---|
605 | n/a | if debug > 1: |
---|
606 | n/a | print("path:") |
---|
607 | n/a | for item in path: |
---|
608 | n/a | print(" ", repr(item)) |
---|
609 | n/a | |
---|
610 | n/a | # Create the module finder and turn its crank |
---|
611 | n/a | mf = ModuleFinder(path, debug, exclude) |
---|
612 | n/a | for arg in args[1:]: |
---|
613 | n/a | if arg == '-m': |
---|
614 | n/a | domods = 1 |
---|
615 | n/a | continue |
---|
616 | n/a | if domods: |
---|
617 | n/a | if arg[-2:] == '.*': |
---|
618 | n/a | mf.import_hook(arg[:-2], None, ["*"]) |
---|
619 | n/a | else: |
---|
620 | n/a | mf.import_hook(arg) |
---|
621 | n/a | else: |
---|
622 | n/a | mf.load_file(arg) |
---|
623 | n/a | mf.run_script(script) |
---|
624 | n/a | mf.report() |
---|
625 | n/a | return mf # for -i debugging |
---|
626 | n/a | |
---|
627 | n/a | |
---|
628 | n/a | if __name__ == '__main__': |
---|
629 | n/a | try: |
---|
630 | n/a | mf = test() |
---|
631 | n/a | except KeyboardInterrupt: |
---|
632 | n/a | print("\n[interrupted]") |
---|