trace.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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 linecache
  48. import os
  49. import sys
  50. import sysconfig
  51. import token
  52. import tokenize
  53. import inspect
  54. import gc
  55. import dis
  56. import pickle
  57. from time import monotonic as _time
  58. import threading
  59. PRAGMA_NOCOVER = "#pragma NO COVER"
  60. class _Ignore:
  61. def __init__(self, modules=None, dirs=None):
  62. self._mods = set() if not modules else set(modules)
  63. self._dirs = [] if not dirs else [os.path.normpath(d)
  64. for d in dirs]
  65. self._ignore = { '<string>': 1 }
  66. def names(self, filename, modulename):
  67. if modulename in self._ignore:
  68. return self._ignore[modulename]
  69. # haven't seen this one before, so see if the module name is
  70. # on the ignore list.
  71. if modulename in self._mods: # Identical names, so ignore
  72. self._ignore[modulename] = 1
  73. return 1
  74. # check if the module is a proper submodule of something on
  75. # the ignore list
  76. for mod in self._mods:
  77. # Need to take some care since ignoring
  78. # "cmp" mustn't mean ignoring "cmpcache" but ignoring
  79. # "Spam" must also mean ignoring "Spam.Eggs".
  80. if modulename.startswith(mod + '.'):
  81. self._ignore[modulename] = 1
  82. return 1
  83. # Now check that filename isn't in one of the directories
  84. if filename is None:
  85. # must be a built-in, so we must ignore
  86. self._ignore[modulename] = 1
  87. return 1
  88. # Ignore a file when it contains one of the ignorable paths
  89. for d in self._dirs:
  90. # The '+ os.sep' is to ensure that d is a parent directory,
  91. # as compared to cases like:
  92. # d = "/usr/local"
  93. # filename = "/usr/local.py"
  94. # or
  95. # d = "/usr/local.py"
  96. # filename = "/usr/local.py"
  97. if filename.startswith(d + os.sep):
  98. self._ignore[modulename] = 1
  99. return 1
  100. # Tried the different ways, so we don't ignore this module
  101. self._ignore[modulename] = 0
  102. return 0
  103. def _modname(path):
  104. """Return a plausible module name for the patch."""
  105. base = os.path.basename(path)
  106. filename, ext = os.path.splitext(base)
  107. return filename
  108. def _fullmodname(path):
  109. """Return a plausible module name for the path."""
  110. # If the file 'path' is part of a package, then the filename isn't
  111. # enough to uniquely identify it. Try to do the right thing by
  112. # looking in sys.path for the longest matching prefix. We'll
  113. # assume that the rest is the package name.
  114. comparepath = os.path.normcase(path)
  115. longest = ""
  116. for dir in sys.path:
  117. dir = os.path.normcase(dir)
  118. if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
  119. if len(dir) > len(longest):
  120. longest = dir
  121. if longest:
  122. base = path[len(longest) + 1:]
  123. else:
  124. base = path
  125. # the drive letter is never part of the module name
  126. drive, base = os.path.splitdrive(base)
  127. base = base.replace(os.sep, ".")
  128. if os.altsep:
  129. base = base.replace(os.altsep, ".")
  130. filename, ext = os.path.splitext(base)
  131. return filename.lstrip(".")
  132. class CoverageResults:
  133. def __init__(self, counts=None, calledfuncs=None, infile=None,
  134. callers=None, outfile=None):
  135. self.counts = counts
  136. if self.counts is None:
  137. self.counts = {}
  138. self.counter = self.counts.copy() # map (filename, lineno) to count
  139. self.calledfuncs = calledfuncs
  140. if self.calledfuncs is None:
  141. self.calledfuncs = {}
  142. self.calledfuncs = self.calledfuncs.copy()
  143. self.callers = callers
  144. if self.callers is None:
  145. self.callers = {}
  146. self.callers = self.callers.copy()
  147. self.infile = infile
  148. self.outfile = outfile
  149. if self.infile:
  150. # Try to merge existing counts file.
  151. try:
  152. with open(self.infile, 'rb') as f:
  153. counts, calledfuncs, callers = pickle.load(f)
  154. self.update(self.__class__(counts, calledfuncs, callers))
  155. except (OSError, EOFError, ValueError) as err:
  156. print(("Skipping counts file %r: %s"
  157. % (self.infile, err)), file=sys.stderr)
  158. def is_ignored_filename(self, filename):
  159. """Return True if the filename does not refer to a file
  160. we want to have reported.
  161. """
  162. return filename.startswith('<') and filename.endswith('>')
  163. def update(self, other):
  164. """Merge in the data from another CoverageResults"""
  165. counts = self.counts
  166. calledfuncs = self.calledfuncs
  167. callers = self.callers
  168. other_counts = other.counts
  169. other_calledfuncs = other.calledfuncs
  170. other_callers = other.callers
  171. for key in other_counts:
  172. counts[key] = counts.get(key, 0) + other_counts[key]
  173. for key in other_calledfuncs:
  174. calledfuncs[key] = 1
  175. for key in other_callers:
  176. callers[key] = 1
  177. def write_results(self, show_missing=True, summary=False, coverdir=None):
  178. """
  179. Write the coverage results.
  180. :param show_missing: Show lines that had no hits.
  181. :param summary: Include coverage summary per module.
  182. :param coverdir: If None, the results of each module are placed in its
  183. directory, otherwise it is included in the directory
  184. specified.
  185. """
  186. if self.calledfuncs:
  187. print()
  188. print("functions called:")
  189. calls = self.calledfuncs
  190. for filename, modulename, funcname in sorted(calls):
  191. print(("filename: %s, modulename: %s, funcname: %s"
  192. % (filename, modulename, funcname)))
  193. if self.callers:
  194. print()
  195. print("calling relationships:")
  196. lastfile = lastcfile = ""
  197. for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) \
  198. in sorted(self.callers):
  199. if pfile != lastfile:
  200. print()
  201. print("***", pfile, "***")
  202. lastfile = pfile
  203. lastcfile = ""
  204. if cfile != pfile and lastcfile != cfile:
  205. print(" -->", cfile)
  206. lastcfile = cfile
  207. print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc))
  208. # turn the counts data ("(filename, lineno) = count") into something
  209. # accessible on a per-file basis
  210. per_file = {}
  211. for filename, lineno in self.counts:
  212. lines_hit = per_file[filename] = per_file.get(filename, {})
  213. lines_hit[lineno] = self.counts[(filename, lineno)]
  214. # accumulate summary info, if needed
  215. sums = {}
  216. for filename, count in per_file.items():
  217. if self.is_ignored_filename(filename):
  218. continue
  219. if filename.endswith(".pyc"):
  220. filename = filename[:-1]
  221. if coverdir is None:
  222. dir = os.path.dirname(os.path.abspath(filename))
  223. modulename = _modname(filename)
  224. else:
  225. dir = coverdir
  226. if not os.path.exists(dir):
  227. os.makedirs(dir)
  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. print("%s(%d): %s" % (bname, lineno,
  498. linecache.getline(filename, lineno)), end='')
  499. return self.localtrace
  500. def localtrace_trace(self, frame, why, arg):
  501. if why == "line":
  502. # record the file name and line number of every trace
  503. filename = frame.f_code.co_filename
  504. lineno = frame.f_lineno
  505. if self.start_time:
  506. print('%.2f' % (_time() - self.start_time), end=' ')
  507. bname = os.path.basename(filename)
  508. print("%s(%d): %s" % (bname, lineno,
  509. linecache.getline(filename, lineno)), end='')
  510. return self.localtrace
  511. def localtrace_count(self, frame, why, arg):
  512. if why == "line":
  513. filename = frame.f_code.co_filename
  514. lineno = frame.f_lineno
  515. key = filename, lineno
  516. self.counts[key] = self.counts.get(key, 0) + 1
  517. return self.localtrace
  518. def results(self):
  519. return CoverageResults(self.counts, infile=self.infile,
  520. outfile=self.outfile,
  521. calledfuncs=self._calledfuncs,
  522. callers=self._callers)
  523. def main():
  524. import argparse
  525. parser = argparse.ArgumentParser()
  526. parser.add_argument('--version', action='version', version='trace 2.0')
  527. grp = parser.add_argument_group('Main options',
  528. 'One of these (or --report) must be given')
  529. grp.add_argument('-c', '--count', action='store_true',
  530. help='Count the number of times each line is executed and write '
  531. 'the counts to <module>.cover for each module executed, in '
  532. 'the module\'s directory. See also --coverdir, --file, '
  533. '--no-report below.')
  534. grp.add_argument('-t', '--trace', action='store_true',
  535. help='Print each line to sys.stdout before it is executed')
  536. grp.add_argument('-l', '--listfuncs', action='store_true',
  537. help='Keep track of which functions are executed at least once '
  538. 'and write the results to sys.stdout after the program exits. '
  539. 'Cannot be specified alongside --trace or --count.')
  540. grp.add_argument('-T', '--trackcalls', action='store_true',
  541. help='Keep track of caller/called pairs and write the results to '
  542. 'sys.stdout after the program exits.')
  543. grp = parser.add_argument_group('Modifiers')
  544. _grp = grp.add_mutually_exclusive_group()
  545. _grp.add_argument('-r', '--report', action='store_true',
  546. help='Generate a report from a counts file; does not execute any '
  547. 'code. --file must specify the results file to read, which '
  548. 'must have been created in a previous run with --count '
  549. '--file=FILE')
  550. _grp.add_argument('-R', '--no-report', action='store_true',
  551. help='Do not generate the coverage report files. '
  552. 'Useful if you want to accumulate over several runs.')
  553. grp.add_argument('-f', '--file',
  554. help='File to accumulate counts over several runs')
  555. grp.add_argument('-C', '--coverdir',
  556. help='Directory where the report files go. The coverage report '
  557. 'for <package>.<module> will be written to file '
  558. '<dir>/<package>/<module>.cover')
  559. grp.add_argument('-m', '--missing', action='store_true',
  560. help='Annotate executable lines that were not executed with '
  561. '">>>>>> "')
  562. grp.add_argument('-s', '--summary', action='store_true',
  563. help='Write a brief summary for each file to sys.stdout. '
  564. 'Can only be used with --count or --report')
  565. grp.add_argument('-g', '--timing', action='store_true',
  566. help='Prefix each line with the time since the program started. '
  567. 'Only used while tracing')
  568. grp = parser.add_argument_group('Filters',
  569. 'Can be specified multiple times')
  570. grp.add_argument('--ignore-module', action='append', default=[],
  571. help='Ignore the given module(s) and its submodules '
  572. '(if it is a package). Accepts comma separated list of '
  573. 'module names.')
  574. grp.add_argument('--ignore-dir', action='append', default=[],
  575. help='Ignore files in the given directory '
  576. '(multiple directories can be joined by os.pathsep).')
  577. parser.add_argument('--module', action='store_true', default=False,
  578. help='Trace a module. ')
  579. parser.add_argument('progname', nargs='?',
  580. help='file to run as main program')
  581. parser.add_argument('arguments', nargs=argparse.REMAINDER,
  582. help='arguments to the program')
  583. opts = parser.parse_args()
  584. if opts.ignore_dir:
  585. _prefix = sysconfig.get_path("stdlib")
  586. _exec_prefix = sysconfig.get_path("platstdlib")
  587. def parse_ignore_dir(s):
  588. s = os.path.expanduser(os.path.expandvars(s))
  589. s = s.replace('$prefix', _prefix).replace('$exec_prefix', _exec_prefix)
  590. return os.path.normpath(s)
  591. opts.ignore_module = [mod.strip()
  592. for i in opts.ignore_module for mod in i.split(',')]
  593. opts.ignore_dir = [parse_ignore_dir(s)
  594. for i in opts.ignore_dir for s in i.split(os.pathsep)]
  595. if opts.report:
  596. if not opts.file:
  597. parser.error('-r/--report requires -f/--file')
  598. results = CoverageResults(infile=opts.file, outfile=opts.file)
  599. return results.write_results(opts.missing, opts.summary, opts.coverdir)
  600. if not any([opts.trace, opts.count, opts.listfuncs, opts.trackcalls]):
  601. parser.error('must specify one of --trace, --count, --report, '
  602. '--listfuncs, or --trackcalls')
  603. if opts.listfuncs and (opts.count or opts.trace):
  604. parser.error('cannot specify both --listfuncs and (--trace or --count)')
  605. if opts.summary and not opts.count:
  606. parser.error('--summary can only be used with --count or --report')
  607. if opts.progname is None:
  608. parser.error('progname is missing: required with the main options')
  609. t = Trace(opts.count, opts.trace, countfuncs=opts.listfuncs,
  610. countcallers=opts.trackcalls, ignoremods=opts.ignore_module,
  611. ignoredirs=opts.ignore_dir, infile=opts.file,
  612. outfile=opts.file, timing=opts.timing)
  613. try:
  614. if opts.module:
  615. import runpy
  616. module_name = opts.progname
  617. mod_name, mod_spec, code = runpy._get_module_details(module_name)
  618. sys.argv = [code.co_filename, *opts.arguments]
  619. globs = {
  620. '__name__': '__main__',
  621. '__file__': code.co_filename,
  622. '__package__': mod_spec.parent,
  623. '__loader__': mod_spec.loader,
  624. '__spec__': mod_spec,
  625. '__cached__': None,
  626. }
  627. else:
  628. sys.argv = [opts.progname, *opts.arguments]
  629. sys.path[0] = os.path.dirname(opts.progname)
  630. with open(opts.progname, 'rb') as fp:
  631. code = compile(fp.read(), opts.progname, 'exec')
  632. # try to emulate __main__ namespace as much as possible
  633. globs = {
  634. '__file__': opts.progname,
  635. '__name__': '__main__',
  636. '__package__': None,
  637. '__cached__': None,
  638. }
  639. t.runctx(code, globs, globs)
  640. except OSError as err:
  641. sys.exit("Cannot run file %r because: %s" % (sys.argv[0], err))
  642. except SystemExit:
  643. pass
  644. results = t.results()
  645. if not opts.no_report:
  646. results.write_results(opts.missing, opts.summary, opts.coverdir)
  647. if __name__=='__main__':
  648. main()