trace.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. #!/usr/bin/env python3
  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.base_prefix, sys.base_exec_prefix,],
  39. trace=0, 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. __all__ = ['Trace', 'CoverageResults']
  47. import io
  48. import linecache
  49. import os
  50. import sys
  51. import sysconfig
  52. import token
  53. import tokenize
  54. import inspect
  55. import gc
  56. import dis
  57. import pickle
  58. from time import monotonic as _time
  59. import threading
  60. PRAGMA_NOCOVER = "#pragma NO COVER"
  61. class _Ignore:
  62. def __init__(self, modules=None, dirs=None):
  63. self._mods = set() if not modules else set(modules)
  64. self._dirs = [] if not dirs else [os.path.normpath(d)
  65. for d in dirs]
  66. self._ignore = { '<string>': 1 }
  67. def names(self, filename, modulename):
  68. if modulename in self._ignore:
  69. return self._ignore[modulename]
  70. # haven't seen this one before, so see if the module name is
  71. # on the ignore list.
  72. if modulename in self._mods: # Identical names, so ignore
  73. self._ignore[modulename] = 1
  74. return 1
  75. # check if the module is a proper submodule of something on
  76. # the ignore list
  77. for mod in self._mods:
  78. # Need to take some care since ignoring
  79. # "cmp" mustn't mean ignoring "cmpcache" but ignoring
  80. # "Spam" must also mean ignoring "Spam.Eggs".
  81. if modulename.startswith(mod + '.'):
  82. self._ignore[modulename] = 1
  83. return 1
  84. # Now check that filename isn't in one of the directories
  85. if filename is None:
  86. # must be a built-in, so we must ignore
  87. self._ignore[modulename] = 1
  88. return 1
  89. # Ignore a file when it contains one of the ignorable paths
  90. for d in self._dirs:
  91. # The '+ os.sep' is to ensure that d is a parent directory,
  92. # as compared to cases like:
  93. # d = "/usr/local"
  94. # filename = "/usr/local.py"
  95. # or
  96. # d = "/usr/local.py"
  97. # filename = "/usr/local.py"
  98. if filename.startswith(d + os.sep):
  99. self._ignore[modulename] = 1
  100. return 1
  101. # Tried the different ways, so we don't ignore this module
  102. self._ignore[modulename] = 0
  103. return 0
  104. def _modname(path):
  105. """Return a plausible module name for the path."""
  106. base = os.path.basename(path)
  107. filename, ext = os.path.splitext(base)
  108. return filename
  109. def _fullmodname(path):
  110. """Return a plausible module name for the path."""
  111. # If the file 'path' is part of a package, then the filename isn't
  112. # enough to uniquely identify it. Try to do the right thing by
  113. # looking in sys.path for the longest matching prefix. We'll
  114. # assume that the rest is the package name.
  115. comparepath = os.path.normcase(path)
  116. longest = ""
  117. for dir in sys.path:
  118. dir = os.path.normcase(dir)
  119. if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
  120. if len(dir) > len(longest):
  121. longest = dir
  122. if longest:
  123. base = path[len(longest) + 1:]
  124. else:
  125. base = path
  126. # the drive letter is never part of the module name
  127. drive, base = os.path.splitdrive(base)
  128. base = base.replace(os.sep, ".")
  129. if os.altsep:
  130. base = base.replace(os.altsep, ".")
  131. filename, ext = os.path.splitext(base)
  132. return filename.lstrip(".")
  133. class CoverageResults:
  134. def __init__(self, counts=None, calledfuncs=None, infile=None,
  135. callers=None, outfile=None):
  136. self.counts = counts
  137. if self.counts is None:
  138. self.counts = {}
  139. self.counter = self.counts.copy() # map (filename, lineno) to count
  140. self.calledfuncs = calledfuncs
  141. if self.calledfuncs is None:
  142. self.calledfuncs = {}
  143. self.calledfuncs = self.calledfuncs.copy()
  144. self.callers = callers
  145. if self.callers is None:
  146. self.callers = {}
  147. self.callers = self.callers.copy()
  148. self.infile = infile
  149. self.outfile = outfile
  150. if self.infile:
  151. # Try to merge existing counts file.
  152. try:
  153. with open(self.infile, 'rb') as f:
  154. counts, calledfuncs, callers = pickle.load(f)
  155. self.update(self.__class__(counts, calledfuncs, callers=callers))
  156. except (OSError, EOFError, ValueError) as err:
  157. print(("Skipping counts file %r: %s"
  158. % (self.infile, err)), file=sys.stderr)
  159. def is_ignored_filename(self, filename):
  160. """Return True if the filename does not refer to a file
  161. we want to have reported.
  162. """
  163. return filename.startswith('<') and filename.endswith('>')
  164. def update(self, other):
  165. """Merge in the data from another CoverageResults"""
  166. counts = self.counts
  167. calledfuncs = self.calledfuncs
  168. callers = self.callers
  169. other_counts = other.counts
  170. other_calledfuncs = other.calledfuncs
  171. other_callers = other.callers
  172. for key in other_counts:
  173. counts[key] = counts.get(key, 0) + other_counts[key]
  174. for key in other_calledfuncs:
  175. calledfuncs[key] = 1
  176. for key in other_callers:
  177. callers[key] = 1
  178. def write_results(self, show_missing=True, summary=False, coverdir=None):
  179. """
  180. Write the coverage results.
  181. :param show_missing: Show lines that had no hits.
  182. :param summary: Include coverage summary per module.
  183. :param coverdir: If None, the results of each module are placed in its
  184. directory, otherwise it is included in the directory
  185. specified.
  186. """
  187. if self.calledfuncs:
  188. print()
  189. print("functions called:")
  190. calls = self.calledfuncs
  191. for filename, modulename, funcname in sorted(calls):
  192. print(("filename: %s, modulename: %s, funcname: %s"
  193. % (filename, modulename, funcname)))
  194. if self.callers:
  195. print()
  196. print("calling relationships:")
  197. lastfile = lastcfile = ""
  198. for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) \
  199. in sorted(self.callers):
  200. if pfile != lastfile:
  201. print()
  202. print("***", pfile, "***")
  203. lastfile = pfile
  204. lastcfile = ""
  205. if cfile != pfile and lastcfile != cfile:
  206. print(" -->", cfile)
  207. lastcfile = cfile
  208. print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc))
  209. # turn the counts data ("(filename, lineno) = count") into something
  210. # accessible on a per-file basis
  211. per_file = {}
  212. for filename, lineno in self.counts:
  213. lines_hit = per_file[filename] = per_file.get(filename, {})
  214. lines_hit[lineno] = self.counts[(filename, lineno)]
  215. # accumulate summary info, if needed
  216. sums = {}
  217. for filename, count in per_file.items():
  218. if self.is_ignored_filename(filename):
  219. continue
  220. if filename.endswith(".pyc"):
  221. filename = filename[:-1]
  222. if coverdir is None:
  223. dir = os.path.dirname(os.path.abspath(filename))
  224. modulename = _modname(filename)
  225. else:
  226. dir = coverdir
  227. os.makedirs(dir, exist_ok=True)
  228. modulename = _fullmodname(filename)
  229. # If desired, get a list of the line numbers which represent
  230. # executable content (returned as a dict for better lookup speed)
  231. if show_missing:
  232. lnotab = _find_executable_linenos(filename)
  233. else:
  234. lnotab = {}
  235. source = linecache.getlines(filename)
  236. coverpath = os.path.join(dir, modulename + ".cover")
  237. with open(filename, 'rb') as fp:
  238. encoding, _ = tokenize.detect_encoding(fp.readline)
  239. n_hits, n_lines = self.write_results_file(coverpath, source,
  240. lnotab, count, encoding)
  241. if summary and n_lines:
  242. percent = int(100 * n_hits / n_lines)
  243. sums[modulename] = n_lines, percent, modulename, filename
  244. if summary and sums:
  245. print("lines cov% module (path)")
  246. for m in sorted(sums):
  247. n_lines, percent, modulename, filename = sums[m]
  248. print("%5d %3d%% %s (%s)" % sums[m])
  249. if self.outfile:
  250. # try and store counts and module info into self.outfile
  251. try:
  252. with open(self.outfile, 'wb') as f:
  253. pickle.dump((self.counts, self.calledfuncs, self.callers),
  254. f, 1)
  255. except OSError as err:
  256. print("Can't save counts files because %s" % err, file=sys.stderr)
  257. def write_results_file(self, path, lines, lnotab, lines_hit, encoding=None):
  258. """Return a coverage results file in path."""
  259. # ``lnotab`` is a dict of executable lines, or a line number "table"
  260. try:
  261. outfile = open(path, "w", encoding=encoding)
  262. except OSError as err:
  263. print(("trace: Could not open %r for writing: %s "
  264. "- skipping" % (path, err)), file=sys.stderr)
  265. return 0, 0
  266. n_lines = 0
  267. n_hits = 0
  268. with outfile:
  269. for lineno, line in enumerate(lines, 1):
  270. # do the blank/comment match to try to mark more lines
  271. # (help the reader find stuff that hasn't been covered)
  272. if lineno in lines_hit:
  273. outfile.write("%5d: " % lines_hit[lineno])
  274. n_hits += 1
  275. n_lines += 1
  276. elif lineno in lnotab and not PRAGMA_NOCOVER in line:
  277. # Highlight never-executed lines, unless the line contains
  278. # #pragma: NO COVER
  279. outfile.write(">>>>>> ")
  280. n_lines += 1
  281. else:
  282. outfile.write(" ")
  283. outfile.write(line.expandtabs(8))
  284. return n_hits, n_lines
  285. def _find_lines_from_code(code, strs):
  286. """Return dict where keys are lines in the line number table."""
  287. linenos = {}
  288. for _, lineno in dis.findlinestarts(code):
  289. if lineno not in strs:
  290. linenos[lineno] = 1
  291. return linenos
  292. def _find_lines(code, strs):
  293. """Return lineno dict for all code objects reachable from code."""
  294. # get all of the lineno information from the code of this scope level
  295. linenos = _find_lines_from_code(code, strs)
  296. # and check the constants for references to other code objects
  297. for c in code.co_consts:
  298. if inspect.iscode(c):
  299. # find another code object, so recurse into it
  300. linenos.update(_find_lines(c, strs))
  301. return linenos
  302. def _find_strings(filename, encoding=None):
  303. """Return a dict of possible docstring positions.
  304. The dict maps line numbers to strings. There is an entry for
  305. line that contains only a string or a part of a triple-quoted
  306. string.
  307. """
  308. d = {}
  309. # If the first token is a string, then it's the module docstring.
  310. # Add this special case so that the test in the loop passes.
  311. prev_ttype = token.INDENT
  312. with open(filename, encoding=encoding) as f:
  313. tok = tokenize.generate_tokens(f.readline)
  314. for ttype, tstr, start, end, line in tok:
  315. if ttype == token.STRING:
  316. if prev_ttype == token.INDENT:
  317. sline, scol = start
  318. eline, ecol = end
  319. for i in range(sline, eline + 1):
  320. d[i] = 1
  321. prev_ttype = ttype
  322. return d
  323. def _find_executable_linenos(filename):
  324. """Return dict where keys are line numbers in the line number table."""
  325. try:
  326. with tokenize.open(filename) as f:
  327. prog = f.read()
  328. encoding = f.encoding
  329. except OSError as err:
  330. print(("Not printing coverage data for %r: %s"
  331. % (filename, err)), file=sys.stderr)
  332. return {}
  333. code = compile(prog, filename, "exec")
  334. strs = _find_strings(filename, encoding)
  335. return _find_lines(code, strs)
  336. class Trace:
  337. def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
  338. ignoremods=(), ignoredirs=(), infile=None, outfile=None,
  339. timing=False):
  340. """
  341. @param count true iff it should count number of times each
  342. line is executed
  343. @param trace true iff it should print out each line that is
  344. being counted
  345. @param countfuncs true iff it should just output a list of
  346. (filename, modulename, funcname,) for functions
  347. that were called at least once; This overrides
  348. `count' and `trace'
  349. @param ignoremods a list of the names of modules to ignore
  350. @param ignoredirs a list of the names of directories to ignore
  351. all of the (recursive) contents of
  352. @param infile file from which to read stored counts to be
  353. added into the results
  354. @param outfile file in which to write the results
  355. @param timing true iff timing information be displayed
  356. """
  357. self.infile = infile
  358. self.outfile = outfile
  359. self.ignore = _Ignore(ignoremods, ignoredirs)
  360. self.counts = {} # keys are (filename, linenumber)
  361. self.pathtobasename = {} # for memoizing os.path.basename
  362. self.donothing = 0
  363. self.trace = trace
  364. self._calledfuncs = {}
  365. self._callers = {}
  366. self._caller_cache = {}
  367. self.start_time = None
  368. if timing:
  369. self.start_time = _time()
  370. if countcallers:
  371. self.globaltrace = self.globaltrace_trackcallers
  372. elif countfuncs:
  373. self.globaltrace = self.globaltrace_countfuncs
  374. elif trace and count:
  375. self.globaltrace = self.globaltrace_lt
  376. self.localtrace = self.localtrace_trace_and_count
  377. elif trace:
  378. self.globaltrace = self.globaltrace_lt
  379. self.localtrace = self.localtrace_trace
  380. elif count:
  381. self.globaltrace = self.globaltrace_lt
  382. self.localtrace = self.localtrace_count
  383. else:
  384. # Ahem -- do nothing? Okay.
  385. self.donothing = 1
  386. def run(self, cmd):
  387. import __main__
  388. dict = __main__.__dict__
  389. self.runctx(cmd, dict, dict)
  390. def runctx(self, cmd, globals=None, locals=None):
  391. if globals is None: globals = {}
  392. if locals is None: locals = {}
  393. if not self.donothing:
  394. threading.settrace(self.globaltrace)
  395. sys.settrace(self.globaltrace)
  396. try:
  397. exec(cmd, globals, locals)
  398. finally:
  399. if not self.donothing:
  400. sys.settrace(None)
  401. threading.settrace(None)
  402. def runfunc(self, func, /, *args, **kw):
  403. result = None
  404. if not self.donothing:
  405. sys.settrace(self.globaltrace)
  406. try:
  407. result = func(*args, **kw)
  408. finally:
  409. if not self.donothing:
  410. sys.settrace(None)
  411. return result
  412. def file_module_function_of(self, frame):
  413. code = frame.f_code
  414. filename = code.co_filename
  415. if filename:
  416. modulename = _modname(filename)
  417. else:
  418. modulename = None
  419. funcname = code.co_name
  420. clsname = None
  421. if code in self._caller_cache:
  422. if self._caller_cache[code] is not None:
  423. clsname = self._caller_cache[code]
  424. else:
  425. self._caller_cache[code] = None
  426. ## use of gc.get_referrers() was suggested by Michael Hudson
  427. # all functions which refer to this code object
  428. funcs = [f for f in gc.get_referrers(code)
  429. if inspect.isfunction(f)]
  430. # require len(func) == 1 to avoid ambiguity caused by calls to
  431. # new.function(): "In the face of ambiguity, refuse the
  432. # temptation to guess."
  433. if len(funcs) == 1:
  434. dicts = [d for d in gc.get_referrers(funcs[0])
  435. if isinstance(d, dict)]
  436. if len(dicts) == 1:
  437. classes = [c for c in gc.get_referrers(dicts[0])
  438. if hasattr(c, "__bases__")]
  439. if len(classes) == 1:
  440. # ditto for new.classobj()
  441. clsname = classes[0].__name__
  442. # cache the result - assumption is that new.* is
  443. # not called later to disturb this relationship
  444. # _caller_cache could be flushed if functions in
  445. # the new module get called.
  446. self._caller_cache[code] = clsname
  447. if clsname is not None:
  448. funcname = "%s.%s" % (clsname, funcname)
  449. return filename, modulename, funcname
  450. def globaltrace_trackcallers(self, frame, why, arg):
  451. """Handler for call events.
  452. Adds information about who called who to the self._callers dict.
  453. """
  454. if why == 'call':
  455. # XXX Should do a better job of identifying methods
  456. this_func = self.file_module_function_of(frame)
  457. parent_func = self.file_module_function_of(frame.f_back)
  458. self._callers[(parent_func, this_func)] = 1
  459. def globaltrace_countfuncs(self, frame, why, arg):
  460. """Handler for call events.
  461. Adds (filename, modulename, funcname) to the self._calledfuncs dict.
  462. """
  463. if why == 'call':
  464. this_func = self.file_module_function_of(frame)
  465. self._calledfuncs[this_func] = 1
  466. def globaltrace_lt(self, frame, why, arg):
  467. """Handler for call events.
  468. If the code block being entered is to be ignored, returns `None',
  469. else returns self.localtrace.
  470. """
  471. if why == 'call':
  472. code = frame.f_code
  473. filename = frame.f_globals.get('__file__', None)
  474. if filename:
  475. # XXX _modname() doesn't work right for packages, so
  476. # the ignore support won't work right for packages
  477. modulename = _modname(filename)
  478. if modulename is not None:
  479. ignore_it = self.ignore.names(filename, modulename)
  480. if not ignore_it:
  481. if self.trace:
  482. print((" --- modulename: %s, funcname: %s"
  483. % (modulename, code.co_name)))
  484. return self.localtrace
  485. else:
  486. return None
  487. def localtrace_trace_and_count(self, frame, why, arg):
  488. if why == "line":
  489. # record the file name and line number of every trace
  490. filename = frame.f_code.co_filename
  491. lineno = frame.f_lineno
  492. key = filename, lineno
  493. self.counts[key] = self.counts.get(key, 0) + 1
  494. if self.start_time:
  495. print('%.2f' % (_time() - self.start_time), end=' ')
  496. bname = os.path.basename(filename)
  497. line = linecache.getline(filename, lineno)
  498. print("%s(%d)" % (bname, lineno), end='')
  499. if line:
  500. print(": ", line, end='')
  501. else:
  502. print()
  503. return self.localtrace
  504. def localtrace_trace(self, frame, why, arg):
  505. if why == "line":
  506. # record the file name and line number of every trace
  507. filename = frame.f_code.co_filename
  508. lineno = frame.f_lineno
  509. if self.start_time:
  510. print('%.2f' % (_time() - self.start_time), end=' ')
  511. bname = os.path.basename(filename)
  512. line = linecache.getline(filename, lineno)
  513. print("%s(%d)" % (bname, lineno), end='')
  514. if line:
  515. print(": ", line, end='')
  516. else:
  517. print()
  518. return self.localtrace
  519. def localtrace_count(self, frame, why, arg):
  520. if why == "line":
  521. filename = frame.f_code.co_filename
  522. lineno = frame.f_lineno
  523. key = filename, lineno
  524. self.counts[key] = self.counts.get(key, 0) + 1
  525. return self.localtrace
  526. def results(self):
  527. return CoverageResults(self.counts, infile=self.infile,
  528. outfile=self.outfile,
  529. calledfuncs=self._calledfuncs,
  530. callers=self._callers)
  531. def main():
  532. import argparse
  533. parser = argparse.ArgumentParser()
  534. parser.add_argument('--version', action='version', version='trace 2.0')
  535. grp = parser.add_argument_group('Main options',
  536. 'One of these (or --report) must be given')
  537. grp.add_argument('-c', '--count', action='store_true',
  538. help='Count the number of times each line is executed and write '
  539. 'the counts to <module>.cover for each module executed, in '
  540. 'the module\'s directory. See also --coverdir, --file, '
  541. '--no-report below.')
  542. grp.add_argument('-t', '--trace', action='store_true',
  543. help='Print each line to sys.stdout before it is executed')
  544. grp.add_argument('-l', '--listfuncs', action='store_true',
  545. help='Keep track of which functions are executed at least once '
  546. 'and write the results to sys.stdout after the program exits. '
  547. 'Cannot be specified alongside --trace or --count.')
  548. grp.add_argument('-T', '--trackcalls', action='store_true',
  549. help='Keep track of caller/called pairs and write the results to '
  550. 'sys.stdout after the program exits.')
  551. grp = parser.add_argument_group('Modifiers')
  552. _grp = grp.add_mutually_exclusive_group()
  553. _grp.add_argument('-r', '--report', action='store_true',
  554. help='Generate a report from a counts file; does not execute any '
  555. 'code. --file must specify the results file to read, which '
  556. 'must have been created in a previous run with --count '
  557. '--file=FILE')
  558. _grp.add_argument('-R', '--no-report', action='store_true',
  559. help='Do not generate the coverage report files. '
  560. 'Useful if you want to accumulate over several runs.')
  561. grp.add_argument('-f', '--file',
  562. help='File to accumulate counts over several runs')
  563. grp.add_argument('-C', '--coverdir',
  564. help='Directory where the report files go. The coverage report '
  565. 'for <package>.<module> will be written to file '
  566. '<dir>/<package>/<module>.cover')
  567. grp.add_argument('-m', '--missing', action='store_true',
  568. help='Annotate executable lines that were not executed with '
  569. '">>>>>> "')
  570. grp.add_argument('-s', '--summary', action='store_true',
  571. help='Write a brief summary for each file to sys.stdout. '
  572. 'Can only be used with --count or --report')
  573. grp.add_argument('-g', '--timing', action='store_true',
  574. help='Prefix each line with the time since the program started. '
  575. 'Only used while tracing')
  576. grp = parser.add_argument_group('Filters',
  577. 'Can be specified multiple times')
  578. grp.add_argument('--ignore-module', action='append', default=[],
  579. help='Ignore the given module(s) and its submodules '
  580. '(if it is a package). Accepts comma separated list of '
  581. 'module names.')
  582. grp.add_argument('--ignore-dir', action='append', default=[],
  583. help='Ignore files in the given directory '
  584. '(multiple directories can be joined by os.pathsep).')
  585. parser.add_argument('--module', action='store_true', default=False,
  586. help='Trace a module. ')
  587. parser.add_argument('progname', nargs='?',
  588. help='file to run as main program')
  589. parser.add_argument('arguments', nargs=argparse.REMAINDER,
  590. help='arguments to the program')
  591. opts = parser.parse_args()
  592. if opts.ignore_dir:
  593. _prefix = sysconfig.get_path("stdlib")
  594. _exec_prefix = sysconfig.get_path("platstdlib")
  595. def parse_ignore_dir(s):
  596. s = os.path.expanduser(os.path.expandvars(s))
  597. s = s.replace('$prefix', _prefix).replace('$exec_prefix', _exec_prefix)
  598. return os.path.normpath(s)
  599. opts.ignore_module = [mod.strip()
  600. for i in opts.ignore_module for mod in i.split(',')]
  601. opts.ignore_dir = [parse_ignore_dir(s)
  602. for i in opts.ignore_dir for s in i.split(os.pathsep)]
  603. if opts.report:
  604. if not opts.file:
  605. parser.error('-r/--report requires -f/--file')
  606. results = CoverageResults(infile=opts.file, outfile=opts.file)
  607. return results.write_results(opts.missing, opts.summary, opts.coverdir)
  608. if not any([opts.trace, opts.count, opts.listfuncs, opts.trackcalls]):
  609. parser.error('must specify one of --trace, --count, --report, '
  610. '--listfuncs, or --trackcalls')
  611. if opts.listfuncs and (opts.count or opts.trace):
  612. parser.error('cannot specify both --listfuncs and (--trace or --count)')
  613. if opts.summary and not opts.count:
  614. parser.error('--summary can only be used with --count or --report')
  615. if opts.progname is None:
  616. parser.error('progname is missing: required with the main options')
  617. t = Trace(opts.count, opts.trace, countfuncs=opts.listfuncs,
  618. countcallers=opts.trackcalls, ignoremods=opts.ignore_module,
  619. ignoredirs=opts.ignore_dir, infile=opts.file,
  620. outfile=opts.file, timing=opts.timing)
  621. try:
  622. if opts.module:
  623. import runpy
  624. module_name = opts.progname
  625. mod_name, mod_spec, code = runpy._get_module_details(module_name)
  626. sys.argv = [code.co_filename, *opts.arguments]
  627. globs = {
  628. '__name__': '__main__',
  629. '__file__': code.co_filename,
  630. '__package__': mod_spec.parent,
  631. '__loader__': mod_spec.loader,
  632. '__spec__': mod_spec,
  633. '__cached__': None,
  634. }
  635. else:
  636. sys.argv = [opts.progname, *opts.arguments]
  637. sys.path[0] = os.path.dirname(opts.progname)
  638. with io.open_code(opts.progname) as fp:
  639. code = compile(fp.read(), opts.progname, 'exec')
  640. # try to emulate __main__ namespace as much as possible
  641. globs = {
  642. '__file__': opts.progname,
  643. '__name__': '__main__',
  644. '__package__': None,
  645. '__cached__': None,
  646. }
  647. t.runctx(code, globs, globs)
  648. except OSError as err:
  649. sys.exit("Cannot run file %r because: %s" % (sys.argv[0], err))
  650. except SystemExit:
  651. pass
  652. results = t.results()
  653. if not opts.no_report:
  654. results.write_results(opts.missing, opts.summary, opts.coverdir)
  655. if __name__=='__main__':
  656. main()