home *** CD-ROM | disk | FTP | other *** search
/ H4CK3R 14 / hacker14.iso / programacao / pythonwin / python.exe / TRACE.PY < prev    next >
Encoding:
Python Source  |  2003-07-15  |  25.0 KB  |  689 lines

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