blob: 646a7852ba9d4abd617c24bde23448dab5b6cb08 [file] [log] [blame]
Guido van Rossum75dc4961998-03-05 03:42:00 +00001"""Find modules used by a script, using introspection."""
Thomas Heller919000e2002-11-25 20:21:59 +00002
Guido van Rossumfc2a0a82006-10-27 23:06:01 +00003from __future__ import generators
Guido van Rossum75dc4961998-03-05 03:42:00 +00004import dis
5import imp
6import marshal
7import os
Guido van Rossum75dc4961998-03-05 03:42:00 +00008import sys
Christian Heimes45f9af32007-11-27 21:50:00 +00009import types
Guido van Rossumfc2a0a82006-10-27 23:06:01 +000010import struct
Guido van Rossum75dc4961998-03-05 03:42:00 +000011
Benjamin Peterson821d0f82009-02-16 16:20:10 +000012READ_MODE = "rU"
Just van Rossum5d0bd1e2002-11-26 09:53:16 +000013
Brett Cannon40430012007-10-22 20:24:51 +000014# XXX Clean up once str8's cstor matches bytes.
Guido van Rossum98297ee2007-11-06 21:34:58 +000015LOAD_CONST = bytes([dis.opname.index('LOAD_CONST')])
16IMPORT_NAME = bytes([dis.opname.index('IMPORT_NAME')])
17STORE_NAME = bytes([dis.opname.index('STORE_NAME')])
18STORE_GLOBAL = bytes([dis.opname.index('STORE_GLOBAL')])
Just van Rossume29310a2002-12-31 16:33:00 +000019STORE_OPS = [STORE_NAME, STORE_GLOBAL]
Guido van Rossum98297ee2007-11-06 21:34:58 +000020HAVE_ARGUMENT = bytes([dis.HAVE_ARGUMENT])
Guido van Rossum75dc4961998-03-05 03:42:00 +000021
Guido van Rossumf1b5a0e1998-05-18 20:21:56 +000022# Modulefinder does a good job at simulating Python's, but it can not
23# handle __path__ modifications packages make at runtime. Therefore there
24# is a mechanism whereby you can register extra paths in this map for a
Thomas Wouters7e474022000-07-16 12:04:32 +000025# package, and it will be honored.
Guido van Rossumf1b5a0e1998-05-18 20:21:56 +000026
27# Note this is a mapping is lists of paths.
28packagePathMap = {}
29
30# A Public interface
31def AddPackagePath(packagename, path):
Guido van Rossume7e632a1998-09-14 16:02:28 +000032 paths = packagePathMap.get(packagename, [])
33 paths.append(path)
34 packagePathMap[packagename] = paths
Guido van Rossum75dc4961998-03-05 03:42:00 +000035
Thomas Hellerc7aaf952002-11-14 18:45:11 +000036replacePackageMap = {}
37
38# This ReplacePackage mechanism allows modulefinder to work around the
39# way the _xmlplus package injects itself under the name "xml" into
40# sys.modules at runtime by calling ReplacePackage("_xmlplus", "xml")
41# before running ModuleFinder.
42
43def ReplacePackage(oldname, newname):
44 replacePackageMap[oldname] = newname
45
46
Guido van Rossum75dc4961998-03-05 03:42:00 +000047class Module:
48
49 def __init__(self, name, file=None, path=None):
Guido van Rossum912a14c1998-03-05 04:56:37 +000050 self.__name__ = name
51 self.__file__ = file
52 self.__path__ = path
53 self.__code__ = None
Just van Rossume29310a2002-12-31 16:33:00 +000054 # The set of global names that are assigned to in the module.
55 # This includes those names imported through starimports of
56 # Python modules.
57 self.globalnames = {}
58 # The set of starimports this module did that could not be
59 # resolved, ie. a starimport from a non-Python module.
60 self.starimports = {}
Guido van Rossum75dc4961998-03-05 03:42:00 +000061
62 def __repr__(self):
Neil Schemenauer32d23c92004-02-15 16:43:20 +000063 s = "Module(%r" % (self.__name__,)
Guido van Rossum912a14c1998-03-05 04:56:37 +000064 if self.__file__ is not None:
Walter Dörwald70a6b492004-02-12 17:35:32 +000065 s = s + ", %r" % (self.__file__,)
Guido van Rossum912a14c1998-03-05 04:56:37 +000066 if self.__path__ is not None:
Walter Dörwald70a6b492004-02-12 17:35:32 +000067 s = s + ", %r" % (self.__path__,)
Guido van Rossum912a14c1998-03-05 04:56:37 +000068 s = s + ")"
69 return s
Guido van Rossum75dc4961998-03-05 03:42:00 +000070
Guido van Rossum75dc4961998-03-05 03:42:00 +000071class ModuleFinder:
72
Just van Rossume29310a2002-12-31 16:33:00 +000073 def __init__(self, path=None, debug=0, excludes=[], replace_paths=[]):
Guido van Rossum912a14c1998-03-05 04:56:37 +000074 if path is None:
75 path = sys.path
76 self.path = path
77 self.modules = {}
78 self.badmodules = {}
79 self.debug = debug
80 self.indent = 0
Guido van Rossum78fc3631998-03-20 17:37:24 +000081 self.excludes = excludes
Guido van Rossum6b767ac2001-03-20 20:43:34 +000082 self.replace_paths = replace_paths
83 self.processed_paths = [] # Used in debugging only
Guido van Rossum75dc4961998-03-05 03:42:00 +000084
85 def msg(self, level, str, *args):
Guido van Rossum912a14c1998-03-05 04:56:37 +000086 if level <= self.debug:
87 for i in range(self.indent):
Guido van Rossumbe19ed72007-02-09 05:37:30 +000088 print(" ", end=' ')
89 print(str, end=' ')
Guido van Rossum912a14c1998-03-05 04:56:37 +000090 for arg in args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000091 print(repr(arg), end=' ')
92 print()
Guido van Rossum75dc4961998-03-05 03:42:00 +000093
94 def msgin(self, *args):
Guido van Rossum912a14c1998-03-05 04:56:37 +000095 level = args[0]
96 if level <= self.debug:
97 self.indent = self.indent + 1
Guido van Rossum68468eb2003-02-27 20:14:51 +000098 self.msg(*args)
Guido van Rossum75dc4961998-03-05 03:42:00 +000099
100 def msgout(self, *args):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000101 level = args[0]
102 if level <= self.debug:
103 self.indent = self.indent - 1
Guido van Rossum68468eb2003-02-27 20:14:51 +0000104 self.msg(*args)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000105
106 def run_script(self, pathname):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000107 self.msg(2, "run_script", pathname)
Brett Cannon028011f2010-10-30 00:26:48 +0000108 with open(pathname, READ_MODE) as fp:
109 stuff = ("", "r", imp.PY_SOURCE)
110 self.load_module('__main__', fp, pathname, stuff)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000111
112 def load_file(self, pathname):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000113 dir, name = os.path.split(pathname)
114 name, ext = os.path.splitext(name)
Brett Cannon028011f2010-10-30 00:26:48 +0000115 with open(pathname, READ_MODE) as fp:
116 stuff = (ext, "r", imp.PY_SOURCE)
117 self.load_module(name, fp, pathname, stuff)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000118
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000119 def import_hook(self, name, caller=None, fromlist=None, level=-1):
120 self.msg(3, "import_hook", name, caller, fromlist, level)
121 parent = self.determine_parent(caller, level=level)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000122 q, tail = self.find_head_package(parent, name)
123 m = self.load_tail(q, tail)
124 if not fromlist:
125 return q
126 if m.__path__:
127 self.ensure_fromlist(m, fromlist)
Thomas Heller318b7b92002-11-26 08:06:50 +0000128 return None
Guido van Rossum75dc4961998-03-05 03:42:00 +0000129
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000130 def determine_parent(self, caller, level=-1):
131 self.msgin(4, "determine_parent", caller, level)
132 if not caller or level == 0:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000133 self.msgout(4, "determine_parent -> None")
134 return None
135 pname = caller.__name__
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000136 if level >= 1: # relative import
137 if caller.__path__:
138 level -= 1
139 if level == 0:
140 parent = self.modules[pname]
141 assert parent is caller
142 self.msgout(4, "determine_parent ->", parent)
143 return parent
144 if pname.count(".") < level:
Collin Winterce36ad82007-08-30 01:19:48 +0000145 raise ImportError("relative importpath too deep")
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000146 pname = ".".join(pname.split(".")[:-level])
147 parent = self.modules[pname]
148 self.msgout(4, "determine_parent ->", parent)
149 return parent
Guido van Rossum912a14c1998-03-05 04:56:37 +0000150 if caller.__path__:
151 parent = self.modules[pname]
152 assert caller is parent
153 self.msgout(4, "determine_parent ->", parent)
154 return parent
155 if '.' in pname:
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000156 i = pname.rfind('.')
Guido van Rossum912a14c1998-03-05 04:56:37 +0000157 pname = pname[:i]
158 parent = self.modules[pname]
159 assert parent.__name__ == pname
160 self.msgout(4, "determine_parent ->", parent)
161 return parent
162 self.msgout(4, "determine_parent -> None")
163 return None
Guido van Rossum75dc4961998-03-05 03:42:00 +0000164
165 def find_head_package(self, parent, name):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000166 self.msgin(4, "find_head_package", parent, name)
167 if '.' in name:
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000168 i = name.find('.')
Guido van Rossum912a14c1998-03-05 04:56:37 +0000169 head = name[:i]
170 tail = name[i+1:]
171 else:
172 head = name
173 tail = ""
174 if parent:
175 qname = "%s.%s" % (parent.__name__, head)
176 else:
177 qname = head
178 q = self.import_module(head, qname, parent)
179 if q:
180 self.msgout(4, "find_head_package ->", (q, tail))
181 return q, tail
182 if parent:
183 qname = head
184 parent = None
185 q = self.import_module(head, qname, parent)
186 if q:
187 self.msgout(4, "find_head_package ->", (q, tail))
188 return q, tail
189 self.msgout(4, "raise ImportError: No module named", qname)
Collin Winterce36ad82007-08-30 01:19:48 +0000190 raise ImportError("No module named " + qname)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000191
192 def load_tail(self, q, tail):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000193 self.msgin(4, "load_tail", q, tail)
194 m = q
195 while tail:
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000196 i = tail.find('.')
Guido van Rossum912a14c1998-03-05 04:56:37 +0000197 if i < 0: i = len(tail)
198 head, tail = tail[:i], tail[i+1:]
199 mname = "%s.%s" % (m.__name__, head)
200 m = self.import_module(head, mname, m)
201 if not m:
202 self.msgout(4, "raise ImportError: No module named", mname)
Collin Winterce36ad82007-08-30 01:19:48 +0000203 raise ImportError("No module named " + mname)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000204 self.msgout(4, "load_tail ->", m)
205 return m
Guido van Rossum75dc4961998-03-05 03:42:00 +0000206
207 def ensure_fromlist(self, m, fromlist, recursive=0):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000208 self.msg(4, "ensure_fromlist", m, fromlist, recursive)
209 for sub in fromlist:
210 if sub == "*":
211 if not recursive:
212 all = self.find_all_submodules(m)
213 if all:
214 self.ensure_fromlist(m, all, 1)
215 elif not hasattr(m, sub):
216 subname = "%s.%s" % (m.__name__, sub)
217 submod = self.import_module(sub, subname, m)
218 if not submod:
Collin Winterce36ad82007-08-30 01:19:48 +0000219 raise ImportError("No module named " + subname)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000220
221 def find_all_submodules(self, m):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000222 if not m.__path__:
223 return
224 modules = {}
Thomas Helleraaf1c8d2003-11-14 10:28:42 +0000225 # 'suffixes' used to be a list hardcoded to [".py", ".pyc", ".pyo"].
226 # But we must also collect Python extension modules - although
227 # we cannot separate normal dlls from Python extensions.
228 suffixes = []
229 for triple in imp.get_suffixes():
230 suffixes.append(triple[0])
Guido van Rossum912a14c1998-03-05 04:56:37 +0000231 for dir in m.__path__:
232 try:
233 names = os.listdir(dir)
234 except os.error:
235 self.msg(2, "can't list directory", dir)
236 continue
237 for name in names:
238 mod = None
239 for suff in suffixes:
240 n = len(suff)
241 if name[-n:] == suff:
242 mod = name[:-n]
243 break
244 if mod and mod != "__init__":
245 modules[mod] = mod
246 return modules.keys()
Guido van Rossum75dc4961998-03-05 03:42:00 +0000247
248 def import_module(self, partname, fqname, parent):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000249 self.msgin(3, "import_module", partname, fqname, parent)
250 try:
251 m = self.modules[fqname]
252 except KeyError:
253 pass
254 else:
255 self.msgout(3, "import_module ->", m)
256 return m
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000257 if fqname in self.badmodules:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000258 self.msgout(3, "import_module -> None")
259 return None
Thomas Heller2e7c8322004-05-11 15:10:59 +0000260 if parent and parent.__path__ is None:
261 self.msgout(3, "import_module -> None")
262 return None
Guido van Rossum912a14c1998-03-05 04:56:37 +0000263 try:
264 fp, pathname, stuff = self.find_module(partname,
Just van Rossumf0dfbaf2003-03-05 17:23:48 +0000265 parent and parent.__path__, parent)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000266 except ImportError:
267 self.msgout(3, "import_module ->", None)
268 return None
269 try:
270 m = self.load_module(fqname, fp, pathname, stuff)
271 finally:
272 if fp: fp.close()
273 if parent:
274 setattr(parent, partname, m)
275 self.msgout(3, "import_module ->", m)
276 return m
Guido van Rossum75dc4961998-03-05 03:42:00 +0000277
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000278 def load_module(self, fqname, fp, pathname, file_info):
279 suffix, mode, type = file_info
Guido van Rossum912a14c1998-03-05 04:56:37 +0000280 self.msgin(2, "load_module", fqname, fp and "fp", pathname)
281 if type == imp.PKG_DIRECTORY:
282 m = self.load_package(fqname, pathname)
283 self.msgout(2, "load_module ->", m)
284 return m
285 if type == imp.PY_SOURCE:
Guido van Rossum78fc3631998-03-20 17:37:24 +0000286 co = compile(fp.read()+'\n', pathname, 'exec')
Guido van Rossum912a14c1998-03-05 04:56:37 +0000287 elif type == imp.PY_COMPILED:
288 if fp.read(4) != imp.get_magic():
289 self.msgout(2, "raise ImportError: Bad magic number", pathname)
Collin Winterce36ad82007-08-30 01:19:48 +0000290 raise ImportError("Bad magic number in %s" % pathname)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000291 fp.read(4)
292 co = marshal.load(fp)
293 else:
294 co = None
295 m = self.add_module(fqname)
Guido van Rossumab045f91998-03-06 19:55:10 +0000296 m.__file__ = pathname
Guido van Rossum912a14c1998-03-05 04:56:37 +0000297 if co:
Guido van Rossum6b767ac2001-03-20 20:43:34 +0000298 if self.replace_paths:
299 co = self.replace_paths_in_code(co)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000300 m.__code__ = co
Guido van Rossum3c51cf21998-03-05 05:15:07 +0000301 self.scan_code(co, m)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000302 self.msgout(2, "load_module ->", m)
303 return m
Guido van Rossum75dc4961998-03-05 03:42:00 +0000304
Just van Rossume29310a2002-12-31 16:33:00 +0000305 def _add_badmodule(self, name, caller):
306 if name not in self.badmodules:
307 self.badmodules[name] = {}
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000308 if caller:
309 self.badmodules[name][caller.__name__] = 1
310 else:
311 self.badmodules[name]["-"] = 1
Just van Rossume29310a2002-12-31 16:33:00 +0000312
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000313 def _safe_import_hook(self, name, caller, fromlist, level=-1):
Just van Rossume29310a2002-12-31 16:33:00 +0000314 # wrapper for self.import_hook() that won't raise ImportError
315 if name in self.badmodules:
316 self._add_badmodule(name, caller)
317 return
318 try:
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000319 self.import_hook(name, caller, level=level)
Guido van Rossumb940e112007-01-10 16:19:56 +0000320 except ImportError as msg:
Just van Rossume29310a2002-12-31 16:33:00 +0000321 self.msg(2, "ImportError:", str(msg))
322 self._add_badmodule(name, caller)
323 else:
324 if fromlist:
325 for sub in fromlist:
326 if sub in self.badmodules:
327 self._add_badmodule(sub, caller)
328 continue
329 try:
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000330 self.import_hook(name, caller, [sub], level=level)
Guido van Rossumb940e112007-01-10 16:19:56 +0000331 except ImportError as msg:
Just van Rossume29310a2002-12-31 16:33:00 +0000332 self.msg(2, "ImportError:", str(msg))
333 fullname = name + "." + sub
334 self._add_badmodule(fullname, caller)
335
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000336 def scan_opcodes(self, co,
337 unpack = struct.unpack):
338 # Scan the code, and yield 'interesting' opcode combinations
339 # Version for Python 2.4 and older
340 code = co.co_code
341 names = co.co_names
342 consts = co.co_consts
343 while code:
344 c = code[0]
345 if c in STORE_OPS:
346 oparg, = unpack('<H', code[1:3])
347 yield "store", (names[oparg],)
348 code = code[3:]
349 continue
350 if c == LOAD_CONST and code[3] == IMPORT_NAME:
351 oparg_1, oparg_2 = unpack('<xHxH', code[:6])
352 yield "import", (consts[oparg_1], names[oparg_2])
353 code = code[6:]
354 continue
355 if c >= HAVE_ARGUMENT:
356 code = code[3:]
357 else:
358 code = code[1:]
359
360 def scan_opcodes_25(self, co,
361 unpack = struct.unpack):
362 # Scan the code, and yield 'interesting' opcode combinations
363 # Python 2.5 version (has absolute and relative imports)
364 code = co.co_code
365 names = co.co_names
366 consts = co.co_consts
367 LOAD_LOAD_AND_IMPORT = LOAD_CONST + LOAD_CONST + IMPORT_NAME
368 while code:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000369 c = bytes([code[0]])
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000370 if c in STORE_OPS:
371 oparg, = unpack('<H', code[1:3])
372 yield "store", (names[oparg],)
373 code = code[3:]
374 continue
375 if code[:9:3] == LOAD_LOAD_AND_IMPORT:
376 oparg_1, oparg_2, oparg_3 = unpack('<xHxHxH', code[:9])
377 level = consts[oparg_1]
378 if level == 0: # absolute import
379 yield "absolute_import", (consts[oparg_2], names[oparg_3])
380 else: # relative import
381 yield "relative_import", (level, consts[oparg_2], names[oparg_3])
382 code = code[9:]
383 continue
384 if c >= HAVE_ARGUMENT:
385 code = code[3:]
386 else:
387 code = code[1:]
388
Guido van Rossum3c51cf21998-03-05 05:15:07 +0000389 def scan_code(self, co, m):
390 code = co.co_code
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000391 if sys.version_info >= (2, 5):
392 scanner = self.scan_opcodes_25
393 else:
394 scanner = self.scan_opcodes
395 for what, args in scanner(co):
396 if what == "store":
397 name, = args
398 m.globalnames[name] = 1
399 elif what == "absolute_import":
400 fromlist, name = args
Just van Rossume29310a2002-12-31 16:33:00 +0000401 have_star = 0
402 if fromlist is not None:
403 if "*" in fromlist:
404 have_star = 1
405 fromlist = [f for f in fromlist if f != "*"]
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000406 self._safe_import_hook(name, m, fromlist, level=0)
Just van Rossume29310a2002-12-31 16:33:00 +0000407 if have_star:
408 # We've encountered an "import *". If it is a Python module,
409 # the code has already been parsed and we can suck out the
410 # global names.
411 mm = None
412 if m.__path__:
413 # At this point we don't know whether 'name' is a
414 # submodule of 'm' or a global module. Let's just try
415 # the full name first.
416 mm = self.modules.get(m.__name__ + "." + name)
417 if mm is None:
418 mm = self.modules.get(name)
419 if mm is not None:
420 m.globalnames.update(mm.globalnames)
421 m.starimports.update(mm.starimports)
422 if mm.__code__ is None:
423 m.starimports[name] = 1
424 else:
425 m.starimports[name] = 1
Guido van Rossumfc2a0a82006-10-27 23:06:01 +0000426 elif what == "relative_import":
427 level, fromlist, name = args
428 if name:
429 self._safe_import_hook(name, m, fromlist, level=level)
430 else:
431 parent = self.determine_parent(m, level=level)
432 self._safe_import_hook(parent.__name__, None, fromlist, level=0)
433 else:
434 # We don't expect anything else from the generator.
435 raise RuntimeError(what)
436
Guido van Rossum3c51cf21998-03-05 05:15:07 +0000437 for c in co.co_consts:
438 if isinstance(c, type(co)):
439 self.scan_code(c, m)
440
Guido van Rossum75dc4961998-03-05 03:42:00 +0000441 def load_package(self, fqname, pathname):
Guido van Rossum912a14c1998-03-05 04:56:37 +0000442 self.msgin(2, "load_package", fqname, pathname)
Thomas Hellerc7aaf952002-11-14 18:45:11 +0000443 newname = replacePackageMap.get(fqname)
444 if newname:
445 fqname = newname
Guido van Rossum912a14c1998-03-05 04:56:37 +0000446 m = self.add_module(fqname)
447 m.__file__ = pathname
448 m.__path__ = [pathname]
Guido van Rossumf1b5a0e1998-05-18 20:21:56 +0000449
Guido van Rossume7e632a1998-09-14 16:02:28 +0000450 # As per comment at top of file, simulate runtime __path__ additions.
451 m.__path__ = m.__path__ + packagePathMap.get(fqname, [])
Guido van Rossumf1b5a0e1998-05-18 20:21:56 +0000452
Guido van Rossum912a14c1998-03-05 04:56:37 +0000453 fp, buf, stuff = self.find_module("__init__", m.__path__)
Brett Cannon028011f2010-10-30 00:26:48 +0000454 try:
455 self.load_module(fqname, fp, buf, stuff)
456 self.msgout(2, "load_package ->", m)
457 return m
458 finally:
459 if fp:
460 fp.close()
Guido van Rossum75dc4961998-03-05 03:42:00 +0000461
462 def add_module(self, fqname):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000463 if fqname in self.modules:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000464 return self.modules[fqname]
465 self.modules[fqname] = m = Module(fqname)
466 return m
Guido van Rossum75dc4961998-03-05 03:42:00 +0000467
Just van Rossumf0dfbaf2003-03-05 17:23:48 +0000468 def find_module(self, name, path, parent=None):
469 if parent is not None:
Thomas Heller2e7c8322004-05-11 15:10:59 +0000470 # assert path is not None
Just van Rossumf0dfbaf2003-03-05 17:23:48 +0000471 fullname = parent.__name__+'.'+name
Guido van Rossum03f7f082001-10-18 19:15:32 +0000472 else:
473 fullname = name
474 if fullname in self.excludes:
475 self.msgout(3, "find_module -> Excluded", fullname)
Collin Winterce36ad82007-08-30 01:19:48 +0000476 raise ImportError(name)
Guido van Rossum78fc3631998-03-20 17:37:24 +0000477
Guido van Rossum912a14c1998-03-05 04:56:37 +0000478 if path is None:
479 if name in sys.builtin_module_names:
480 return (None, None, ("", "", imp.C_BUILTIN))
Guido van Rossum78fc3631998-03-20 17:37:24 +0000481
Guido van Rossum912a14c1998-03-05 04:56:37 +0000482 path = self.path
483 return imp.find_module(name, path)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000484
485 def report(self):
Just van Rossume29310a2002-12-31 16:33:00 +0000486 """Print a report to stdout, listing the found modules with their
487 paths, as well as modules that are missing, or seem to be missing.
488 """
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000489 print()
490 print(" %-25s %s" % ("Name", "File"))
491 print(" %-25s %s" % ("----", "----"))
Guido van Rossum912a14c1998-03-05 04:56:37 +0000492 # Print modules found
Guido van Rossumd59cde82007-06-12 00:25:08 +0000493 keys = sorted(self.modules.keys())
Guido van Rossum912a14c1998-03-05 04:56:37 +0000494 for key in keys:
495 m = self.modules[key]
496 if m.__path__:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000497 print("P", end=' ')
Guido van Rossum912a14c1998-03-05 04:56:37 +0000498 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000499 print("m", end=' ')
500 print("%-25s" % key, m.__file__ or "")
Guido van Rossum75dc4961998-03-05 03:42:00 +0000501
Guido van Rossum912a14c1998-03-05 04:56:37 +0000502 # Print missing modules
Just van Rossume29310a2002-12-31 16:33:00 +0000503 missing, maybe = self.any_missing_maybe()
504 if missing:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000505 print()
506 print("Missing modules:")
Just van Rossume29310a2002-12-31 16:33:00 +0000507 for name in missing:
Guido van Rossumd59cde82007-06-12 00:25:08 +0000508 mods = sorted(self.badmodules[name].keys())
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000509 print("?", name, "imported from", ', '.join(mods))
Just van Rossume29310a2002-12-31 16:33:00 +0000510 # Print modules that may be missing, but then again, maybe not...
511 if maybe:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000512 print()
513 print("Submodules thay appear to be missing, but could also be", end=' ')
514 print("global names in the parent package:")
Just van Rossume29310a2002-12-31 16:33:00 +0000515 for name in maybe:
Guido van Rossumd59cde82007-06-12 00:25:08 +0000516 mods = sorted(self.badmodules[name].keys())
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000517 print("?", name, "imported from", ', '.join(mods))
Guido van Rossum75dc4961998-03-05 03:42:00 +0000518
Guido van Rossum03f7f082001-10-18 19:15:32 +0000519 def any_missing(self):
Just van Rossume29310a2002-12-31 16:33:00 +0000520 """Return a list of modules that appear to be missing. Use
521 any_missing_maybe() if you want to know which modules are
522 certain to be missing, and which *may* be missing.
523 """
524 missing, maybe = self.any_missing_maybe()
525 return missing + maybe
526
527 def any_missing_maybe(self):
528 """Return two lists, one with modules that are certainly missing
529 and one with modules that *may* be missing. The latter names could
530 either be submodules *or* just global names in the package.
531
532 The reason it can't always be determined is that it's impossible to
533 tell which names are imported when "from module import *" is done
534 with an extension module, short of actually importing it.
535 """
Guido van Rossum03f7f082001-10-18 19:15:32 +0000536 missing = []
Just van Rossume29310a2002-12-31 16:33:00 +0000537 maybe = []
538 for name in self.badmodules:
539 if name in self.excludes:
540 continue
541 i = name.rfind(".")
542 if i < 0:
543 missing.append(name)
544 continue
545 subname = name[i+1:]
546 pkgname = name[:i]
547 pkg = self.modules.get(pkgname)
548 if pkg is not None:
549 if pkgname in self.badmodules[name]:
550 # The package tried to import this module itself and
551 # failed. It's definitely missing.
552 missing.append(name)
553 elif subname in pkg.globalnames:
554 # It's a global in the package: definitely not missing.
555 pass
556 elif pkg.starimports:
557 # It could be missing, but the package did an "import *"
558 # from a non-Python module, so we simply can't be sure.
559 maybe.append(name)
560 else:
561 # It's not a global in the package, the package didn't
562 # do funny star imports, it's very likely to be missing.
563 # The symbol could be inserted into the package from the
564 # outside, but since that's not good style we simply list
565 # it missing.
566 missing.append(name)
567 else:
568 missing.append(name)
569 missing.sort()
570 maybe.sort()
571 return missing, maybe
Guido van Rossum03f7f082001-10-18 19:15:32 +0000572
Guido van Rossum6b767ac2001-03-20 20:43:34 +0000573 def replace_paths_in_code(self, co):
574 new_filename = original_filename = os.path.normpath(co.co_filename)
Just van Rossume29310a2002-12-31 16:33:00 +0000575 for f, r in self.replace_paths:
Guido van Rossum6b767ac2001-03-20 20:43:34 +0000576 if original_filename.startswith(f):
Just van Rossume29310a2002-12-31 16:33:00 +0000577 new_filename = r + original_filename[len(f):]
Guido van Rossum6b767ac2001-03-20 20:43:34 +0000578 break
579
580 if self.debug and original_filename not in self.processed_paths:
Just van Rossume29310a2002-12-31 16:33:00 +0000581 if new_filename != original_filename:
Guido van Rossum6b767ac2001-03-20 20:43:34 +0000582 self.msgout(2, "co_filename %r changed to %r" \
583 % (original_filename,new_filename,))
584 else:
585 self.msgout(2, "co_filename %r remains unchanged" \
586 % (original_filename,))
587 self.processed_paths.append(original_filename)
588
589 consts = list(co.co_consts)
590 for i in range(len(consts)):
591 if isinstance(consts[i], type(co)):
592 consts[i] = self.replace_paths_in_code(consts[i])
593
Christian Heimes45f9af32007-11-27 21:50:00 +0000594 return types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize,
Tim Peters2c60f7a2003-01-29 03:49:43 +0000595 co.co_flags, co.co_code, tuple(consts), co.co_names,
596 co.co_varnames, new_filename, co.co_name,
Neal Norwitz82c72312002-11-12 23:09:12 +0000597 co.co_firstlineno, co.co_lnotab,
598 co.co_freevars, co.co_cellvars)
Guido van Rossum6b767ac2001-03-20 20:43:34 +0000599
Guido van Rossum75dc4961998-03-05 03:42:00 +0000600
601def test():
602 # Parse command line
603 import getopt
604 try:
Guido van Rossumbaf06031998-08-25 14:06:55 +0000605 opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:")
Guido van Rossumb940e112007-01-10 16:19:56 +0000606 except getopt.error as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000607 print(msg)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000608 return
Guido van Rossum75dc4961998-03-05 03:42:00 +0000609
610 # Process options
611 debug = 1
612 domods = 0
613 addpath = []
Guido van Rossumbaf06031998-08-25 14:06:55 +0000614 exclude = []
Guido van Rossum75dc4961998-03-05 03:42:00 +0000615 for o, a in opts:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000616 if o == '-d':
617 debug = debug + 1
618 if o == '-m':
619 domods = 1
620 if o == '-p':
Walter Dörwaldaaab30e2002-09-11 20:36:02 +0000621 addpath = addpath + a.split(os.pathsep)
Guido van Rossum912a14c1998-03-05 04:56:37 +0000622 if o == '-q':
623 debug = 0
Guido van Rossumbaf06031998-08-25 14:06:55 +0000624 if o == '-x':
625 exclude.append(a)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000626
627 # Provide default arguments
628 if not args:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000629 script = "hello.py"
Guido van Rossum75dc4961998-03-05 03:42:00 +0000630 else:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000631 script = args[0]
Guido van Rossum75dc4961998-03-05 03:42:00 +0000632
633 # Set the path based on sys.path and the script directory
634 path = sys.path[:]
635 path[0] = os.path.dirname(script)
636 path = addpath + path
637 if debug > 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000638 print("path:")
Guido van Rossum912a14c1998-03-05 04:56:37 +0000639 for item in path:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000640 print(" ", repr(item))
Guido van Rossum75dc4961998-03-05 03:42:00 +0000641
642 # Create the module finder and turn its crank
Guido van Rossumbaf06031998-08-25 14:06:55 +0000643 mf = ModuleFinder(path, debug, exclude)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000644 for arg in args[1:]:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000645 if arg == '-m':
646 domods = 1
647 continue
648 if domods:
649 if arg[-2:] == '.*':
650 mf.import_hook(arg[:-2], None, ["*"])
651 else:
652 mf.import_hook(arg)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000653 else:
Guido van Rossum912a14c1998-03-05 04:56:37 +0000654 mf.load_file(arg)
Guido van Rossum75dc4961998-03-05 03:42:00 +0000655 mf.run_script(script)
656 mf.report()
Just van Rossume29310a2002-12-31 16:33:00 +0000657 return mf # for -i debugging
Guido van Rossum75dc4961998-03-05 03:42:00 +0000658
659
660if __name__ == '__main__':
661 try:
Just van Rossume29310a2002-12-31 16:33:00 +0000662 mf = test()
Guido van Rossum75dc4961998-03-05 03:42:00 +0000663 except KeyboardInterrupt:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000664 print("\n[interrupt]")