trace.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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 patch."""
  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))
  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. if not os.path.exists(dir):
  228. os.makedirs(dir)
  229. modulename = _fullmodname(filename)
  230. # If desired, get a list of the line numbers which represent
  231. # executable content (returned as a dict for better lookup speed)
  232. if show_missing:
  233. lnotab = _find_executable_linenos(filename)
  234. else:
  235. lnotab = {}
  236. source = linecache.getlines(filename)
  237. coverpath = os.path.join(dir, modulename + ".cover")
  238. with open(filename, 'rb') as fp:
  239. encoding, _ = tokenize.detect_encoding(fp.readline)
  240. n_hits, n_lines = self.write_results_file(coverpath, source,
  241. lnotab, count, encoding)
  242. if summary and n_lines:
  243. percent = int(100 * n_hits / n_lines)
  244. sums[modulename] = n_lines, percent, modulename, filename
  245. if summary and sums:
  246. print("lines cov% module (path)")
  247. for m in sorted(sums):
  248. n_lines, percent, modulename, filename = sums[m]
  249. print("%5d %3d%% %s (%s)" % sums[m])
  250. if self.outfile:
  251. # try and store counts and module info into self.outfile
  252. try:
  253. with open(self.outfile, 'wb') as f:
  254. pickle.dump((self.counts, self.calledfuncs, self.callers),
  255. f, 1)
  256. except OSError as err:
  257. print("Can't save counts files because %s" % err, file=sys.stderr)
  258. def write_results_file(self, path, lines, lnotab, lines_hit, encoding=None):
  259. """Return a coverage results file in path."""
  260. # ``lnotab`` is a dict of executable lines, or a line number "table"
  261. try:
  262. outfile = open(path, "w", encoding=encoding)
  263. except OSError as err:
  264. print(("trace: Could not open %r for writing: %s "
  265. "- skipping" % (path, err)), file=sys.stderr)
  266. return 0, 0
  267. n_lines = 0
  268. n_hits = 0
  269. with outfile:
  270. for lineno, line in enumerate(lines, 1):
  271. # do the blank/comment match to try to mark more lines
  272. # (help the reader find stuff that hasn't been covered)
  273. if lineno in lines_hit:
  274. outfile.write("%5d: " % lines_hit[lineno])
  275. n_hits += 1
  276. n_lines += 1
  277. elif lineno in lnotab and not PRAGMA_NOCOVER in line:
  278. # Highlight never-executed lines, unless the line contains
  279. # #pragma: NO COVER
  280. outfile.write(">>>>>> ")
  281. n_lines += 1
  282. else:
  283. outfile.write(" ")
  284. outfile.write(line.expandtabs(8))
  285. return n_hits, n_lines
  286. def _find_lines_from_code(code, strs):
  287. """Return dict where keys are lines in the line number table."""
  288. linenos = {}
  289. for _, lineno in dis.findlinestarts(code):
  290. if lineno not in strs:
  291. linenos[lineno] = 1
  292. return linenos
  293. def _find_lines(code, strs):
  294. """Return lineno dict for all code objects reachable from code."""
  295. # get all of the lineno information from the code of this scope level
  296. linenos = _find_lines_from_code(code, strs)
  297. # and check the constants for references to other code objects
  298. for c in code.co_consts:
  299. if inspect.iscode(c):
  300. # find another code object, so recurse into it
  301. linenos.update(_find_lines(c, strs))
  302. return linenos
  303. def _find_strings(filename, encoding=None):
  304. """Return a dict of possible docstring positions.
  305. The dict maps line numbers to strings. There is an entry for
  306. line that contains only a string or a part of a triple-quoted
  307. string.
  308. """
  309. d = {}
  310. # If the first token is a string, then it's the module docstring.
  311. # Add this special case so that the test in the loop passes.
  312. prev_ttype = token.INDENT
  313. with open(filename, encoding=encoding) as f:
  314. tok = tokenize.generate_tokens(f.readline)
  315. for ttype, tstr, start, end, line in tok:
  316. if ttype == token.STRING:
  317. if prev_ttype == token.INDENT:
  318. sline, scol = start
  319. eline, ecol = end
  320. for i in range(sline, eline + 1):
  321. d[i] = 1
  322. prev_ttype = ttype
  323. return d
  324. def _find_executable_linenos(filename):
  325. """Return dict where keys are line numbers in the line number table."""
  326. try:
  327. with tokenize.open(filename) as f:
  328. prog = f.read()
  329. encoding = f.encoding
  330. except OSError as err:
  331. print(("Not printing coverage data for %r: %s"
  332. % (filename, err)), file=sys.stderr)
  333. return {}
  334. code = compile(prog, filename, "exec")
  335. strs = _find_strings(filename, encoding)
  336. return _find_lines(code, strs)
  337. class Trace:
  338. def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
  339. ignoremods=(), ignoredirs=(), infile=None, outfile=None,
  340. timing=False):
  341. """
  342. @param count true iff it should count number of times each
  343. line is executed
  344. @param trace true iff it should print out each line that is
  345. being counted
  346. @param countfuncs true iff it should just output a list of
  347. (filename, modulename, funcname,) for functions
  348. that were called at least once; This overrides
  349. `count' and `trace'
  350. @param ignoremods a list of the names of modules to ignore
  351. @param ignoredirs a list of the names of directories to ignore
  352. all of the (recursive) contents of
  353. @param infile file from which to read stored counts to be
  354. added into the results
  355. @param outfile file in which to write the results
  356. @param timing true iff timing information be displayed
  357. """
  358. self.infile = infile
  359. self.outfile = outfile
  360. self.ignore = _Ignore(ignoremods, ignoredirs)
  361. self.counts = {} # keys are (filename, linenumber)
  362. self.pathtobasename = {} # for memoizing os.path.basename
  363. self.donothing = 0
  364. self.trace = trace
  365. self._calledfuncs = {}
  366. self._callers = {}
  367. self._caller_cache = {}
  368. self.start_time = None
  369. if timing:
  370. self.start_time = _time()
  371. if countcallers:
  372. self.globaltrace = self.globaltrace_trackcallers
  373. elif countfuncs:
  374. self.globaltrace = self.globaltrace_countfuncs
  375. elif trace and count:
  376. self.globaltrace = self.globaltrace_lt
  377. self.localtrace = self.localtrace_trace_and_count
  378. elif trace:
  379. self.globaltrace = self.globaltrace_lt
  380. self.localtrace = self.localtrace_trace
  381. elif count:
  382. self.globaltrace = self.globaltrace_lt
  383. self.localtrace = self.localtrace_count
  384. else:
  385. # Ahem -- do nothing? Okay.
  386. self.donothing = 1
  387. def run(self, cmd):
  388. import __main__
  389. dict = __main__.__dict__
  390. self.runctx(cmd, dict, dict)
  391. def runctx(self, cmd, globals=None, locals=None):
  392. if globals is None: globals = {}
  393. if locals is None: locals = {}
  394. if not self.donothing:
  395. threading.settrace(self.globaltrace)
  396. sys.settrace(self.globaltrace)
  397. try:
  398. exec(cmd, globals, locals)
  399. finally:
  400. if not self.donothing:
  401. sys.settrace(None)
  402. threading.settrace(None)
  403. def runfunc(self, func, /, *args, **kw):
  404. result = None
  405. if not self.donothing:
  406. sys.settrace(self.globaltrace)
  407. try:
  408. result = func(*args, **kw)
  409. finally:
  410. if not self.donothing:
  411. sys.settrace(None)
  412. return result
  413. def file_module_function_of(self, frame):
  414. code = frame.f_code
  415. filename = code.co_filename
  416. if filename:
  417. modulename = _modname(filename)
  418. else:
  419. modulename = None
  420. funcname = code.co_name
  421. clsname = None
  422. if code in self._caller_cache:
  423. if self._caller_cache[code] is not None:
  424. clsname = self._caller_cache[code]
  425. else:
  426. self._caller_cache[code] = None
  427. ## use of gc.get_referrers() was suggested by Michael Hudson
  428. # all functions which refer to this code object
  429. funcs = [f for f in gc.get_referrers(code)
  430. if inspect.isfunction(f)]
  431. # require len(func) == 1 to avoid ambiguity caused by calls to
  432. # new.function(): "In the face of ambiguity, refuse the
  433. # temptation to guess."
  434. if len(funcs) == 1:
  435. dicts = [d for d in gc.get_referrers(funcs[0])
  436. if isinstance(d, dict)]
  437. if len(dicts) == 1:
  438. classes = [c for c in gc.get_referrers(dicts[0])
  439. if hasattr(c, "__bases__")]
  440. if len(classes) == 1:
  441. # ditto for new.classobj()
  442. clsname = classes[0].__name__
  443. # cache the result - assumption is that new.* is
  444. # not called later to disturb this relationship
  445. # _caller_cache could be flushed if functions in
  446. # the new module get called.
  447. self._caller_cache[code] = clsname
  448. if clsname is not None:
  449. funcname = "%s.%s" % (clsname, funcname)
  450. return filename, modulename, funcname
  451. def globaltrace_trackcallers(self, frame, why, arg):
  452. """Handler for call events.
  453. Adds information about who called who to the self._callers dict.
  454. """
  455. if why == 'call':
  456. # XXX Should do a better job of identifying methods
  457. this_func = self.file_module_function_of(frame)
  458. parent_func = self.file_module_function_of(frame.f_back)
  459. self._callers[(parent_func, this_func)] = 1
  460. def globaltrace_countfuncs(self, frame, why, arg):
  461. """Handler for call events.
  462. Adds (filename, modulename, funcname) to the self._calledfuncs dict.
  463. """
  464. if why == 'call':
  465. this_func = self.file_module_function_of(frame)
  466. self._calledfuncs[this_func] = 1
  467. def globaltrace_lt(self, frame, why, arg):
  468. """Handler for call events.
  469. If the code block being entered is to be ignored, returns `None',
  470. else returns self.localtrace.
  471. """
  472. if why == 'call':
  473. code = frame.f_code
  474. filename = frame.f_globals.get('__file__', None)
  475. if filename:
  476. # XXX _modname() doesn't work right for packages, so
  477. # the ignore support won't work right for packages
  478. modulename = _modname(filename)
  479. if modulename is not None:
  480. ignore_it = self.ignore.names(filename, modulename)
  481. if not ignore_it:
  482. if self.trace:
  483. print((" --- modulename: %s, funcname: %s"
  484. % (modulename, code.co_name)))
  485. return self.localtrace
  486. else:
  487. return None
  488. def localtrace_trace_and_count(self, frame, why, arg):
  489. if why == "line":
  490. # record the file name and line number of every trace
  491. filename = frame.f_code.co_filename
  492. lineno = frame.f_lineno
  493. key = filename, lineno
  494. self.counts[key] = self.counts.get(key, 0) + 1
  495. if self.start_time:
  496. print('%.2f' % (_time() - self.start_time), end=' ')
  497. bname = os.path.basename(filename)
  498. print("%s(%d): %s" % (bname, lineno,
  499. linecache.getline(filename, lineno)), end='')
  500. return self.localtrace
  501. def localtrace_trace(self, frame, why, arg):
  502. if why == "line":
  503. # record the file name and line number of every trace
  504. filename = frame.f_code.co_filename
  505. lineno = frame.f_lineno
  506. if self.start_time:
  507. print('%.2f' % (_time() - self.start_time), end=' ')
  508. bname = os.path.basename(filename)
  509. print("%s(%d): %s" % (bname, lineno,
  510. linecache.getline(filename, lineno)), end='')
  511. return self.localtrace
  512. def localtrace_count(self, frame, why, arg):
  513. if why == "line":
  514. filename = frame.f_code.co_filename
  515. lineno = frame.f_lineno
  516. key = filename, lineno
  517. self.counts[key] = self.counts.get(key, 0) + 1
  518. return self.localtrace
  519. def results(self):
  520. return CoverageResults(self.counts, infile=self.infile,
  521. outfile=self.outfile,
  522. calledfuncs=self._calledfuncs,
  523. callers=self._callers)
  524. def main():
  525. import argparse
  526. parser = argparse.ArgumentParser()
  527. parser.add_argument('--version', action='version', version='trace 2.0')
  528. grp = parser.add_argument_group('Main options',
  529. 'One of these (or --report) must be given')
  530. grp.add_argument('-c', '--count', action='store_true',
  531. help='Count the number of times each line is executed and write '
  532. 'the counts to <module>.cover for each module executed, in '
  533. 'the module\'s directory. See also --coverdir, --file, '
  534. '--no-report below.')
  535. grp.add_argument('-t', '--trace', action='store_true',
  536. help='Print each line to sys.stdout before it is executed')
  537. grp.add_argument('-l', '--listfuncs', action='store_true',
  538. help='Keep track of which functions are executed at least once '
  539. 'and write the results to sys.stdout after the program exits. '
  540. 'Cannot be specified alongside --trace or --count.')
  541. grp.add_argument('-T', '--trackcalls', action='store_true',
  542. help='Keep track of caller/called pairs and write the results to '
  543. 'sys.stdout after the program exits.')
  544. grp = parser.add_argument_group('Modifiers')
  545. _grp = grp.add_mutually_exclusive_group()
  546. _grp.add_argument('-r', '--report', action='store_true',
  547. help='Generate a report from a counts file; does not execute any '
  548. 'code. --file must specify the results file to read, which '
  549. 'must have been created in a previous run with --count '
  550. '--file=FILE')
  551. _grp.add_argument('-R', '--no-report', action='store_true',
  552. help='Do not generate the coverage report files. '
  553. 'Useful if you want to accumulate over several runs.')
  554. grp.add_argument('-f', '--file',
  555. help='File to accumulate counts over several runs')
  556. grp.add_argument('-C', '--coverdir',
  557. help='Directory where the report files go. The coverage report '
  558. 'for <package>.<module> will be written to file '
  559. '<dir>/<package>/<module>.cover')
  560. grp.add_argument('-m', '--missing', action='store_true',
  561. help='Annotate executable lines that were not executed with '
  562. '">>>>>> "')
  563. grp.add_argument('-s', '--summary', action='store_true',
  564. help='Write a brief summary for each file to sys.stdout. '
  565. 'Can only be used with --count or --report')
  566. grp.add_argument('-g', '--timing', action='store_true',
  567. help='Prefix each line with the time since the program started. '
  568. 'Only used while tracing')
  569. grp = parser.add_argument_group('Filters',
  570. 'Can be specified multiple times')
  571. grp.add_argument('--ignore-module', action='append', default=[],
  572. help='Ignore the given module(s) and its submodules '
  573. '(if it is a package). Accepts comma separated list of '
  574. 'module names.')
  575. grp.add_argument('--ignore-dir', action='append', default=[],
  576. help='Ignore files in the given directory '
  577. '(multiple directories can be joined by os.pathsep).')
  578. parser.add_argument('--module', action='store_true', default=False,
  579. help='Trace a module. ')
  580. parser.add_argument('progname', nargs='?',
  581. help='file to run as main program')
  582. parser.add_argument('arguments', nargs=argparse.REMAINDER,
  583. help='arguments to the program')
  584. opts = parser.parse_args()
  585. if opts.ignore_dir:
  586. _prefix = sysconfig.get_path("stdlib")
  587. _exec_prefix = sysconfig.get_path("platstdlib")
  588. def parse_ignore_dir(s):
  589. s = os.path.expanduser(os.path.expandvars(s))
  590. s = s.replace('$prefix', _prefix).replace('$exec_prefix', _exec_prefix)
  591. return os.path.normpath(s)
  592. opts.ignore_module = [mod.strip()
  593. for i in opts.ignore_module for mod in i.split(',')]
  594. opts.ignore_dir = [parse_ignore_dir(s)
  595. for i in opts.ignore_dir for s in i.split(os.pathsep)]
  596. if opts.report:
  597. if not opts.file:
  598. parser.error('-r/--report requires -f/--file')
  599. results = CoverageResults(infile=opts.file, outfile=opts.file)
  600. return results.write_results(opts.missing, opts.summary, opts.coverdir)
  601. if not any([opts.trace, opts.count, opts.listfuncs, opts.trackcalls]):
  602. parser.error('must specify one of --trace, --count, --report, '
  603. '--listfuncs, or --trackcalls')
  604. if opts.listfuncs and (opts.count or opts.trace):
  605. parser.error('cannot specify both --listfuncs and (--trace or --count)')
  606. if opts.summary and not opts.count:
  607. parser.error('--summary can only be used with --count or --report')
  608. if opts.progname is None:
  609. parser.error('progname is missing: required with the main options')
  610. t = Trace(opts.count, opts.trace, countfuncs=opts.listfuncs,
  611. countcallers=opts.trackcalls, ignoremods=opts.ignore_module,
  612. ignoredirs=opts.ignore_dir, infile=opts.file,
  613. outfile=opts.file, timing=opts.timing)
  614. try:
  615. if opts.module:
  616. import runpy
  617. module_name = opts.progname
  618. mod_name, mod_spec, code = runpy._get_module_details(module_name)
  619. sys.argv = [code.co_filename, *opts.arguments]
  620. globs = {
  621. '__name__': '__main__',
  622. '__file__': code.co_filename,
  623. '__package__': mod_spec.parent,
  624. '__loader__': mod_spec.loader,
  625. '__spec__': mod_spec,
  626. '__cached__': None,
  627. }
  628. else:
  629. sys.argv = [opts.progname, *opts.arguments]
  630. sys.path[0] = os.path.dirname(opts.progname)
  631. with io.open_code(opts.progname) as fp:
  632. code = compile(fp.read(), opts.progname, 'exec')
  633. # try to emulate __main__ namespace as much as possible
  634. globs = {
  635. '__file__': opts.progname,
  636. '__name__': '__main__',
  637. '__package__': None,
  638. '__cached__': None,
  639. }
  640. t.runctx(code, globs, globs)
  641. except OSError as err:
  642. sys.exit("Cannot run file %r because: %s" % (sys.argv[0], err))
  643. except SystemExit:
  644. pass
  645. results = t.results()
  646. if not opts.no_report:
  647. results.write_results(opts.missing, opts.summary, opts.coverdir)
  648. if __name__=='__main__':
  649. main()