/Lib/trace.py

http://unladen-swallow.googlecode.com/ · Python · 813 lines · 612 code · 86 blank · 115 comment · 139 complexity · 0516990ae48de6e95fb21681908ef1b2 MD5 · raw file

  1. #!/usr/bin/env python
  2. # portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
  3. # err... reserved and offered to the public under the terms of the
  4. # Python 2.2 license.
  5. # Author: Zooko O'Whielacronx
  6. # http://zooko.com/
  7. # mailto:zooko@zooko.com
  8. #
  9. # Copyright 2000, Mojam Media, Inc., all rights reserved.
  10. # Author: Skip Montanaro
  11. #
  12. # Copyright 1999, Bioreason, Inc., all rights reserved.
  13. # Author: Andrew Dalke
  14. #
  15. # Copyright 1995-1997, Automatrix, Inc., all rights reserved.
  16. # Author: Skip Montanaro
  17. #
  18. # Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.
  19. #
  20. #
  21. # Permission to use, copy, modify, and distribute this Python software and
  22. # its associated documentation for any purpose without fee is hereby
  23. # granted, provided that the above copyright notice appears in all copies,
  24. # and that both that copyright notice and this permission notice appear in
  25. # supporting documentation, and that the name of neither Automatrix,
  26. # Bioreason or Mojam Media be used in advertising or publicity pertaining to
  27. # distribution of the software without specific, written prior permission.
  28. #
  29. """program/module to trace Python program or function execution
  30. Sample use, command line:
  31. trace.py -c -f counts --ignore-dir '$prefix' spam.py eggs
  32. trace.py -t --ignore-dir '$prefix' spam.py eggs
  33. trace.py --trackcalls spam.py eggs
  34. Sample use, programmatically
  35. import sys
  36. # create a Trace object, telling it what to ignore, and whether to
  37. # do tracing or line-counting or both.
  38. tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0,
  39. count=1)
  40. # run the new command using the given tracer
  41. tracer.run('main()')
  42. # make a report, placing output in /tmp
  43. r = tracer.results()
  44. r.write_results(show_missing=True, coverdir="/tmp")
  45. """
  46. import linecache
  47. import os
  48. import re
  49. import sys
  50. import threading
  51. import time
  52. import token
  53. import tokenize
  54. import types
  55. import gc
  56. try:
  57. import cPickle
  58. pickle = cPickle
  59. except ImportError:
  60. import pickle
  61. def usage(outfile):
  62. outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
  63. Meta-options:
  64. --help Display this help then exit.
  65. --version Output version information then exit.
  66. Otherwise, exactly one of the following three options must be given:
  67. -t, --trace Print each line to sys.stdout before it is executed.
  68. -c, --count Count the number of times each line is executed
  69. and write the counts to <module>.cover for each
  70. module executed, in the module's directory.
  71. See also `--coverdir', `--file', `--no-report' below.
  72. -l, --listfuncs Keep track of which functions are executed at least
  73. once and write the results to sys.stdout after the
  74. program exits.
  75. -T, --trackcalls Keep track of caller/called pairs and write the
  76. results to sys.stdout after the program exits.
  77. -r, --report Generate a report from a counts file; do not execute
  78. any code. `--file' must specify the results file to
  79. read, which must have been created in a previous run
  80. with `--count --file=FILE'.
  81. Modifiers:
  82. -f, --file=<file> File to accumulate counts over several runs.
  83. -R, --no-report Do not generate the coverage report files.
  84. Useful if you want to accumulate over several runs.
  85. -C, --coverdir=<dir> Directory where the report files. The coverage
  86. report for <package>.<module> is written to file
  87. <dir>/<package>/<module>.cover.
  88. -m, --missing Annotate executable lines that were not executed
  89. with '>>>>>> '.
  90. -s, --summary Write a brief summary on stdout for each file.
  91. (Can only be used with --count or --report.)
  92. -g, --timing Prefix each line with the time since the program started.
  93. Only used while tracing.
  94. Filters, may be repeated multiple times:
  95. --ignore-module=<mod> Ignore the given module(s) and its submodules
  96. (if it is a package). Accepts comma separated
  97. list of module names
  98. --ignore-dir=<dir> Ignore files in the given directory (multiple
  99. directories can be joined by os.pathsep).
  100. """ % sys.argv[0])
  101. PRAGMA_NOCOVER = "#pragma NO COVER"
  102. # Simple rx to find lines with no code.
  103. rx_blank = re.compile(r'^\s*(#.*)?$')
  104. class Ignore:
  105. def __init__(self, modules = None, dirs = None):
  106. self._mods = modules or []
  107. self._dirs = dirs or []
  108. self._dirs = map(os.path.normpath, self._dirs)
  109. self._ignore = { '<string>': 1 }
  110. def names(self, filename, modulename):
  111. if self._ignore.has_key(modulename):
  112. return self._ignore[modulename]
  113. # haven't seen this one before, so see if the module name is
  114. # on the ignore list. Need to take some care since ignoring
  115. # "cmp" musn't mean ignoring "cmpcache" but ignoring
  116. # "Spam" must also mean ignoring "Spam.Eggs".
  117. for mod in self._mods:
  118. if mod == modulename: # Identical names, so ignore
  119. self._ignore[modulename] = 1
  120. return 1
  121. # check if the module is a proper submodule of something on
  122. # the ignore list
  123. n = len(mod)
  124. # (will not overflow since if the first n characters are the
  125. # same and the name has not already occurred, then the size
  126. # of "name" is greater than that of "mod")
  127. if mod == modulename[:n] and modulename[n] == '.':
  128. self._ignore[modulename] = 1
  129. return 1
  130. # Now check that __file__ isn't in one of the directories
  131. if filename is None:
  132. # must be a built-in, so we must ignore
  133. self._ignore[modulename] = 1
  134. return 1
  135. # Ignore a file when it contains one of the ignorable paths
  136. for d in self._dirs:
  137. # The '+ os.sep' is to ensure that d is a parent directory,
  138. # as compared to cases like:
  139. # d = "/usr/local"
  140. # filename = "/usr/local.py"
  141. # or
  142. # d = "/usr/local.py"
  143. # filename = "/usr/local.py"
  144. if filename.startswith(d + os.sep):
  145. self._ignore[modulename] = 1
  146. return 1
  147. # Tried the different ways, so we don't ignore this module
  148. self._ignore[modulename] = 0
  149. return 0
  150. def modname(path):
  151. """Return a plausible module name for the patch."""
  152. base = os.path.basename(path)
  153. filename, ext = os.path.splitext(base)
  154. return filename
  155. def fullmodname(path):
  156. """Return a plausible module name for the path."""
  157. # If the file 'path' is part of a package, then the filename isn't
  158. # enough to uniquely identify it. Try to do the right thing by
  159. # looking in sys.path for the longest matching prefix. We'll
  160. # assume that the rest is the package name.
  161. comparepath = os.path.normcase(path)
  162. longest = ""
  163. for dir in sys.path:
  164. dir = os.path.normcase(dir)
  165. if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
  166. if len(dir) > len(longest):
  167. longest = dir
  168. if longest:
  169. base = path[len(longest) + 1:]
  170. else:
  171. base = path
  172. base = base.replace(os.sep, ".")
  173. if os.altsep:
  174. base = base.replace(os.altsep, ".")
  175. filename, ext = os.path.splitext(base)
  176. return filename
  177. class CoverageResults:
  178. def __init__(self, counts=None, calledfuncs=None, infile=None,
  179. callers=None, outfile=None):
  180. self.counts = counts
  181. if self.counts is None:
  182. self.counts = {}
  183. self.counter = self.counts.copy() # map (filename, lineno) to count
  184. self.calledfuncs = calledfuncs
  185. if self.calledfuncs is None:
  186. self.calledfuncs = {}
  187. self.calledfuncs = self.calledfuncs.copy()
  188. self.callers = callers
  189. if self.callers is None:
  190. self.callers = {}
  191. self.callers = self.callers.copy()
  192. self.infile = infile
  193. self.outfile = outfile
  194. if self.infile:
  195. # Try to merge existing counts file.
  196. try:
  197. counts, calledfuncs, callers = \
  198. pickle.load(open(self.infile, 'rb'))
  199. self.update(self.__class__(counts, calledfuncs, callers))
  200. except (IOError, EOFError, ValueError), err:
  201. print >> sys.stderr, ("Skipping counts file %r: %s"
  202. % (self.infile, err))
  203. def update(self, other):
  204. """Merge in the data from another CoverageResults"""
  205. counts = self.counts
  206. calledfuncs = self.calledfuncs
  207. callers = self.callers
  208. other_counts = other.counts
  209. other_calledfuncs = other.calledfuncs
  210. other_callers = other.callers
  211. for key in other_counts.keys():
  212. counts[key] = counts.get(key, 0) + other_counts[key]
  213. for key in other_calledfuncs.keys():
  214. calledfuncs[key] = 1
  215. for key in other_callers.keys():
  216. callers[key] = 1
  217. def write_results(self, show_missing=True, summary=False, coverdir=None):
  218. """
  219. @param coverdir
  220. """
  221. if self.calledfuncs:
  222. print
  223. print "functions called:"
  224. calls = self.calledfuncs.keys()
  225. calls.sort()
  226. for filename, modulename, funcname in calls:
  227. print ("filename: %s, modulename: %s, funcname: %s"
  228. % (filename, modulename, funcname))
  229. if self.callers:
  230. print
  231. print "calling relationships:"
  232. calls = self.callers.keys()
  233. calls.sort()
  234. lastfile = lastcfile = ""
  235. for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
  236. if pfile != lastfile:
  237. print
  238. print "***", pfile, "***"
  239. lastfile = pfile
  240. lastcfile = ""
  241. if cfile != pfile and lastcfile != cfile:
  242. print " -->", cfile
  243. lastcfile = cfile
  244. print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)
  245. # turn the counts data ("(filename, lineno) = count") into something
  246. # accessible on a per-file basis
  247. per_file = {}
  248. for filename, lineno in self.counts.keys():
  249. lines_hit = per_file[filename] = per_file.get(filename, {})
  250. lines_hit[lineno] = self.counts[(filename, lineno)]
  251. # accumulate summary info, if needed
  252. sums = {}
  253. for filename, count in per_file.iteritems():
  254. # skip some "files" we don't care about...
  255. if filename == "<string>":
  256. continue
  257. if filename.startswith("<doctest "):
  258. continue
  259. if filename.endswith((".pyc", ".pyo")):
  260. filename = filename[:-1]
  261. if coverdir is None:
  262. dir = os.path.dirname(os.path.abspath(filename))
  263. modulename = modname(filename)
  264. else:
  265. dir = coverdir
  266. if not os.path.exists(dir):
  267. os.makedirs(dir)
  268. modulename = fullmodname(filename)
  269. # If desired, get a list of the line numbers which represent
  270. # executable content (returned as a dict for better lookup speed)
  271. if show_missing:
  272. lnotab = find_executable_linenos(filename)
  273. else:
  274. lnotab = {}
  275. source = linecache.getlines(filename)
  276. coverpath = os.path.join(dir, modulename + ".cover")
  277. n_hits, n_lines = self.write_results_file(coverpath, source,
  278. lnotab, count)
  279. if summary and n_lines:
  280. percent = int(100 * n_hits / n_lines)
  281. sums[modulename] = n_lines, percent, modulename, filename
  282. if summary and sums:
  283. mods = sums.keys()
  284. mods.sort()
  285. print "lines cov% module (path)"
  286. for m in mods:
  287. n_lines, percent, modulename, filename = sums[m]
  288. print "%5d %3d%% %s (%s)" % sums[m]
  289. if self.outfile:
  290. # try and store counts and module info into self.outfile
  291. try:
  292. pickle.dump((self.counts, self.calledfuncs, self.callers),
  293. open(self.outfile, 'wb'), 1)
  294. except IOError, err:
  295. print >> sys.stderr, "Can't save counts files because %s" % err
  296. def write_results_file(self, path, lines, lnotab, lines_hit):
  297. """Return a coverage results file in path."""
  298. try:
  299. outfile = open(path, "w")
  300. except IOError, err:
  301. print >> sys.stderr, ("trace: Could not open %r for writing: %s"
  302. "- skipping" % (path, err))
  303. return 0, 0
  304. n_lines = 0
  305. n_hits = 0
  306. for i, line in enumerate(lines):
  307. lineno = i + 1
  308. # do the blank/comment match to try to mark more lines
  309. # (help the reader find stuff that hasn't been covered)
  310. if lineno in lines_hit:
  311. outfile.write("%5d: " % lines_hit[lineno])
  312. n_hits += 1
  313. n_lines += 1
  314. elif rx_blank.match(line):
  315. outfile.write(" ")
  316. else:
  317. # lines preceded by no marks weren't hit
  318. # Highlight them if so indicated, unless the line contains
  319. # #pragma: NO COVER
  320. if lineno in lnotab and not PRAGMA_NOCOVER in lines[i]:
  321. outfile.write(">>>>>> ")
  322. n_lines += 1
  323. else:
  324. outfile.write(" ")
  325. outfile.write(lines[i].expandtabs(8))
  326. outfile.close()
  327. return n_hits, n_lines
  328. def find_lines_from_code(code, strs):
  329. """Return dict where keys are lines in the line number table."""
  330. linenos = {}
  331. line_increments = [ord(c) for c in code.co_lnotab[1::2]]
  332. table_length = len(line_increments)
  333. docstring = False
  334. lineno = code.co_firstlineno
  335. for li in line_increments:
  336. lineno += li
  337. if lineno not in strs:
  338. linenos[lineno] = 1
  339. return linenos
  340. def find_lines(code, strs):
  341. """Return lineno dict for all code objects reachable from code."""
  342. # get all of the lineno information from the code of this scope level
  343. linenos = find_lines_from_code(code, strs)
  344. # and check the constants for references to other code objects
  345. for c in code.co_consts:
  346. if isinstance(c, types.CodeType):
  347. # find another code object, so recurse into it
  348. linenos.update(find_lines(c, strs))
  349. return linenos
  350. def find_strings(filename):
  351. """Return a dict of possible docstring positions.
  352. The dict maps line numbers to strings. There is an entry for
  353. line that contains only a string or a part of a triple-quoted
  354. string.
  355. """
  356. d = {}
  357. # If the first token is a string, then it's the module docstring.
  358. # Add this special case so that the test in the loop passes.
  359. prev_ttype = token.INDENT
  360. f = open(filename)
  361. for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
  362. if ttype == token.STRING:
  363. if prev_ttype == token.INDENT:
  364. sline, scol = start
  365. eline, ecol = end
  366. for i in range(sline, eline + 1):
  367. d[i] = 1
  368. prev_ttype = ttype
  369. f.close()
  370. return d
  371. def find_executable_linenos(filename):
  372. """Return dict where keys are line numbers in the line number table."""
  373. try:
  374. prog = open(filename, "rU").read()
  375. except IOError, err:
  376. print >> sys.stderr, ("Not printing coverage data for %r: %s"
  377. % (filename, err))
  378. return {}
  379. code = compile(prog, filename, "exec")
  380. strs = find_strings(filename)
  381. return find_lines(code, strs)
  382. class Trace:
  383. def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
  384. ignoremods=(), ignoredirs=(), infile=None, outfile=None,
  385. timing=False):
  386. """
  387. @param count true iff it should count number of times each
  388. line is executed
  389. @param trace true iff it should print out each line that is
  390. being counted
  391. @param countfuncs true iff it should just output a list of
  392. (filename, modulename, funcname,) for functions
  393. that were called at least once; This overrides
  394. `count' and `trace'
  395. @param ignoremods a list of the names of modules to ignore
  396. @param ignoredirs a list of the names of directories to ignore
  397. all of the (recursive) contents of
  398. @param infile file from which to read stored counts to be
  399. added into the results
  400. @param outfile file in which to write the results
  401. @param timing true iff timing information be displayed
  402. """
  403. self.infile = infile
  404. self.outfile = outfile
  405. self.ignore = Ignore(ignoremods, ignoredirs)
  406. self.counts = {} # keys are (filename, linenumber)
  407. self.blabbed = {} # for debugging
  408. self.pathtobasename = {} # for memoizing os.path.basename
  409. self.donothing = 0
  410. self.trace = trace
  411. self._calledfuncs = {}
  412. self._callers = {}
  413. self._caller_cache = {}
  414. self.start_time = None
  415. if timing:
  416. self.start_time = time.time()
  417. if countcallers:
  418. self.globaltrace = self.globaltrace_trackcallers
  419. elif countfuncs:
  420. self.globaltrace = self.globaltrace_countfuncs
  421. elif trace and count:
  422. self.globaltrace = self.globaltrace_lt
  423. self.localtrace = self.localtrace_trace_and_count
  424. elif trace:
  425. self.globaltrace = self.globaltrace_lt
  426. self.localtrace = self.localtrace_trace
  427. elif count:
  428. self.globaltrace = self.globaltrace_lt
  429. self.localtrace = self.localtrace_count
  430. else:
  431. # Ahem -- do nothing? Okay.
  432. self.donothing = 1
  433. def run(self, cmd):
  434. import __main__
  435. dict = __main__.__dict__
  436. if not self.donothing:
  437. sys.settrace(self.globaltrace)
  438. threading.settrace(self.globaltrace)
  439. try:
  440. exec cmd in dict, dict
  441. finally:
  442. if not self.donothing:
  443. sys.settrace(None)
  444. threading.settrace(None)
  445. def runctx(self, cmd, globals=None, locals=None):
  446. if globals is None: globals = {}
  447. if locals is None: locals = {}
  448. if not self.donothing:
  449. sys.settrace(self.globaltrace)
  450. threading.settrace(self.globaltrace)
  451. try:
  452. exec cmd in globals, locals
  453. finally:
  454. if not self.donothing:
  455. sys.settrace(None)
  456. threading.settrace(None)
  457. def runfunc(self, func, *args, **kw):
  458. result = None
  459. if not self.donothing:
  460. sys.settrace(self.globaltrace)
  461. try:
  462. result = func(*args, **kw)
  463. finally:
  464. if not self.donothing:
  465. sys.settrace(None)
  466. return result
  467. def file_module_function_of(self, frame):
  468. code = frame.f_code
  469. filename = code.co_filename
  470. if filename:
  471. modulename = modname(filename)
  472. else:
  473. modulename = None
  474. funcname = code.co_name
  475. clsname = None
  476. if code in self._caller_cache:
  477. if self._caller_cache[code] is not None:
  478. clsname = self._caller_cache[code]
  479. else:
  480. self._caller_cache[code] = None
  481. ## use of gc.get_referrers() was suggested by Michael Hudson
  482. # all functions which refer to this code object
  483. funcs = [f for f in gc.get_referrers(code)
  484. if hasattr(f, "func_doc")]
  485. # require len(func) == 1 to avoid ambiguity caused by calls to
  486. # new.function(): "In the face of ambiguity, refuse the
  487. # temptation to guess."
  488. if len(funcs) == 1:
  489. dicts = [d for d in gc.get_referrers(funcs[0])
  490. if isinstance(d, dict)]
  491. if len(dicts) == 1:
  492. classes = [c for c in gc.get_referrers(dicts[0])
  493. if hasattr(c, "__bases__")]
  494. if len(classes) == 1:
  495. # ditto for new.classobj()
  496. clsname = str(classes[0])
  497. # cache the result - assumption is that new.* is
  498. # not called later to disturb this relationship
  499. # _caller_cache could be flushed if functions in
  500. # the new module get called.
  501. self._caller_cache[code] = clsname
  502. if clsname is not None:
  503. # final hack - module name shows up in str(cls), but we've already
  504. # computed module name, so remove it
  505. clsname = clsname.split(".")[1:]
  506. clsname = ".".join(clsname)
  507. funcname = "%s.%s" % (clsname, funcname)
  508. return filename, modulename, funcname
  509. def globaltrace_trackcallers(self, frame, why, arg):
  510. """Handler for call events.
  511. Adds information about who called who to the self._callers dict.
  512. """
  513. if why == 'call':
  514. # XXX Should do a better job of identifying methods
  515. this_func = self.file_module_function_of(frame)
  516. parent_func = self.file_module_function_of(frame.f_back)
  517. self._callers[(parent_func, this_func)] = 1
  518. def globaltrace_countfuncs(self, frame, why, arg):
  519. """Handler for call events.
  520. Adds (filename, modulename, funcname) to the self._calledfuncs dict.
  521. """
  522. if why == 'call':
  523. this_func = self.file_module_function_of(frame)
  524. self._calledfuncs[this_func] = 1
  525. def globaltrace_lt(self, frame, why, arg):
  526. """Handler for call events.
  527. If the code block being entered is to be ignored, returns `None',
  528. else returns self.localtrace.
  529. """
  530. if why == 'call':
  531. code = frame.f_code
  532. filename = frame.f_globals.get('__file__', None)
  533. if filename:
  534. # XXX modname() doesn't work right for packages, so
  535. # the ignore support won't work right for packages
  536. modulename = modname(filename)
  537. if modulename is not None:
  538. ignore_it = self.ignore.names(filename, modulename)
  539. if not ignore_it:
  540. if self.trace:
  541. print (" --- modulename: %s, funcname: %s"
  542. % (modulename, code.co_name))
  543. return self.localtrace
  544. else:
  545. return None
  546. def localtrace_trace_and_count(self, frame, why, arg):
  547. if why == "line":
  548. # record the file name and line number of every trace
  549. filename = frame.f_code.co_filename
  550. lineno = frame.f_lineno
  551. key = filename, lineno
  552. self.counts[key] = self.counts.get(key, 0) + 1
  553. if self.start_time:
  554. print '%.2f' % (time.time() - self.start_time),
  555. bname = os.path.basename(filename)
  556. print "%s(%d): %s" % (bname, lineno,
  557. linecache.getline(filename, lineno)),
  558. return self.localtrace
  559. def localtrace_trace(self, frame, why, arg):
  560. if why == "line":
  561. # record the file name and line number of every trace
  562. filename = frame.f_code.co_filename
  563. lineno = frame.f_lineno
  564. if self.start_time:
  565. print '%.2f' % (time.time() - self.start_time),
  566. bname = os.path.basename(filename)
  567. print "%s(%d): %s" % (bname, lineno,
  568. linecache.getline(filename, lineno)),
  569. return self.localtrace
  570. def localtrace_count(self, frame, why, arg):
  571. if why == "line":
  572. filename = frame.f_code.co_filename
  573. lineno = frame.f_lineno
  574. key = filename, lineno
  575. self.counts[key] = self.counts.get(key, 0) + 1
  576. return self.localtrace
  577. def results(self):
  578. return CoverageResults(self.counts, infile=self.infile,
  579. outfile=self.outfile,
  580. calledfuncs=self._calledfuncs,
  581. callers=self._callers)
  582. def _err_exit(msg):
  583. sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
  584. sys.exit(1)
  585. def main(argv=None):
  586. import getopt
  587. if argv is None:
  588. argv = sys.argv
  589. try:
  590. opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
  591. ["help", "version", "trace", "count",
  592. "report", "no-report", "summary",
  593. "file=", "missing",
  594. "ignore-module=", "ignore-dir=",
  595. "coverdir=", "listfuncs",
  596. "trackcalls", "timing"])
  597. except getopt.error, msg:
  598. sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
  599. sys.stderr.write("Try `%s --help' for more information\n"
  600. % sys.argv[0])
  601. sys.exit(1)
  602. trace = 0
  603. count = 0
  604. report = 0
  605. no_report = 0
  606. counts_file = None
  607. missing = 0
  608. ignore_modules = []
  609. ignore_dirs = []
  610. coverdir = None
  611. summary = 0
  612. listfuncs = False
  613. countcallers = False
  614. timing = False
  615. for opt, val in opts:
  616. if opt == "--help":
  617. usage(sys.stdout)
  618. sys.exit(0)
  619. if opt == "--version":
  620. sys.stdout.write("trace 2.0\n")
  621. sys.exit(0)
  622. if opt == "-T" or opt == "--trackcalls":
  623. countcallers = True
  624. continue
  625. if opt == "-l" or opt == "--listfuncs":
  626. listfuncs = True
  627. continue
  628. if opt == "-g" or opt == "--timing":
  629. timing = True
  630. continue
  631. if opt == "-t" or opt == "--trace":
  632. trace = 1
  633. continue
  634. if opt == "-c" or opt == "--count":
  635. count = 1
  636. continue
  637. if opt == "-r" or opt == "--report":
  638. report = 1
  639. continue
  640. if opt == "-R" or opt == "--no-report":
  641. no_report = 1
  642. continue
  643. if opt == "-f" or opt == "--file":
  644. counts_file = val
  645. continue
  646. if opt == "-m" or opt == "--missing":
  647. missing = 1
  648. continue
  649. if opt == "-C" or opt == "--coverdir":
  650. coverdir = val
  651. continue
  652. if opt == "-s" or opt == "--summary":
  653. summary = 1
  654. continue
  655. if opt == "--ignore-module":
  656. for mod in val.split(","):
  657. ignore_modules.append(mod.strip())
  658. continue
  659. if opt == "--ignore-dir":
  660. for s in val.split(os.pathsep):
  661. s = os.path.expandvars(s)
  662. # should I also call expanduser? (after all, could use $HOME)
  663. s = s.replace("$prefix",
  664. os.path.join(sys.prefix, "lib",
  665. "python" + sys.version[:3]))
  666. s = s.replace("$exec_prefix",
  667. os.path.join(sys.exec_prefix, "lib",
  668. "python" + sys.version[:3]))
  669. s = os.path.normpath(s)
  670. ignore_dirs.append(s)
  671. continue
  672. assert 0, "Should never get here"
  673. if listfuncs and (count or trace):
  674. _err_exit("cannot specify both --listfuncs and (--trace or --count)")
  675. if not (count or trace or report or listfuncs or countcallers):
  676. _err_exit("must specify one of --trace, --count, --report, "
  677. "--listfuncs, or --trackcalls")
  678. if report and no_report:
  679. _err_exit("cannot specify both --report and --no-report")
  680. if report and not counts_file:
  681. _err_exit("--report requires a --file")
  682. if no_report and len(prog_argv) == 0:
  683. _err_exit("missing name of file to run")
  684. # everything is ready
  685. if report:
  686. results = CoverageResults(infile=counts_file, outfile=counts_file)
  687. results.write_results(missing, summary=summary, coverdir=coverdir)
  688. else:
  689. sys.argv = prog_argv
  690. progname = prog_argv[0]
  691. sys.path[0] = os.path.split(progname)[0]
  692. t = Trace(count, trace, countfuncs=listfuncs,
  693. countcallers=countcallers, ignoremods=ignore_modules,
  694. ignoredirs=ignore_dirs, infile=counts_file,
  695. outfile=counts_file, timing=timing)
  696. try:
  697. t.run('execfile(%r)' % (progname,))
  698. except IOError, err:
  699. _err_exit("Cannot run file %r because: %s" % (sys.argv[0], err))
  700. except SystemExit:
  701. pass
  702. results = t.results()
  703. if not no_report:
  704. results.write_results(missing, summary=summary, coverdir=coverdir)
  705. if __name__=='__main__':
  706. main()