modulefinder.py 21 KB

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