cmdline.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """Command-line support for coverage.py."""
  4. import glob
  5. import optparse
  6. import os.path
  7. import sys
  8. import textwrap
  9. import traceback
  10. from coverage import env
  11. from coverage.collector import CTracer
  12. from coverage.execfile import run_python_file, run_python_module
  13. from coverage.misc import CoverageException, ExceptionDuringRun, NoSource
  14. from coverage.debug import info_formatter, info_header
  15. class Opts(object):
  16. """A namespace class for individual options we'll build parsers from."""
  17. append = optparse.make_option(
  18. '-a', '--append', action='store_true',
  19. help="Append coverage data to .coverage, otherwise it starts clean each time.",
  20. )
  21. branch = optparse.make_option(
  22. '', '--branch', action='store_true',
  23. help="Measure branch coverage in addition to statement coverage.",
  24. )
  25. CONCURRENCY_CHOICES = [
  26. "thread", "gevent", "greenlet", "eventlet", "multiprocessing",
  27. ]
  28. concurrency = optparse.make_option(
  29. '', '--concurrency', action='store', metavar="LIB",
  30. choices=CONCURRENCY_CHOICES,
  31. help=(
  32. "Properly measure code using a concurrency library. "
  33. "Valid values are: %s."
  34. ) % ", ".join(CONCURRENCY_CHOICES),
  35. )
  36. debug = optparse.make_option(
  37. '', '--debug', action='store', metavar="OPTS",
  38. help="Debug options, separated by commas",
  39. )
  40. directory = optparse.make_option(
  41. '-d', '--directory', action='store', metavar="DIR",
  42. help="Write the output files to DIR.",
  43. )
  44. fail_under = optparse.make_option(
  45. '', '--fail-under', action='store', metavar="MIN", type="int",
  46. help="Exit with a status of 2 if the total coverage is less than MIN.",
  47. )
  48. help = optparse.make_option(
  49. '-h', '--help', action='store_true',
  50. help="Get help on this command.",
  51. )
  52. ignore_errors = optparse.make_option(
  53. '-i', '--ignore-errors', action='store_true',
  54. help="Ignore errors while reading source files.",
  55. )
  56. include = optparse.make_option(
  57. '', '--include', action='store',
  58. metavar="PAT1,PAT2,...",
  59. help=(
  60. "Include only files whose paths match one of these patterns. "
  61. "Accepts shell-style wildcards, which must be quoted."
  62. ),
  63. )
  64. pylib = optparse.make_option(
  65. '-L', '--pylib', action='store_true',
  66. help=(
  67. "Measure coverage even inside the Python installed library, "
  68. "which isn't done by default."
  69. ),
  70. )
  71. show_missing = optparse.make_option(
  72. '-m', '--show-missing', action='store_true',
  73. help="Show line numbers of statements in each module that weren't executed.",
  74. )
  75. skip_covered = optparse.make_option(
  76. '--skip-covered', action='store_true',
  77. help="Skip files with 100% coverage.",
  78. )
  79. omit = optparse.make_option(
  80. '', '--omit', action='store',
  81. metavar="PAT1,PAT2,...",
  82. help=(
  83. "Omit files whose paths match one of these patterns. "
  84. "Accepts shell-style wildcards, which must be quoted."
  85. ),
  86. )
  87. output_xml = optparse.make_option(
  88. '-o', '', action='store', dest="outfile",
  89. metavar="OUTFILE",
  90. help="Write the XML report to this file. Defaults to 'coverage.xml'",
  91. )
  92. parallel_mode = optparse.make_option(
  93. '-p', '--parallel-mode', action='store_true',
  94. help=(
  95. "Append the machine name, process id and random number to the "
  96. ".coverage data file name to simplify collecting data from "
  97. "many processes."
  98. ),
  99. )
  100. module = optparse.make_option(
  101. '-m', '--module', action='store_true',
  102. help=(
  103. "<pyfile> is an importable Python module, not a script path, "
  104. "to be run as 'python -m' would run it."
  105. ),
  106. )
  107. rcfile = optparse.make_option(
  108. '', '--rcfile', action='store',
  109. help="Specify configuration file. Defaults to '.coveragerc'",
  110. )
  111. source = optparse.make_option(
  112. '', '--source', action='store', metavar="SRC1,SRC2,...",
  113. help="A list of packages or directories of code to be measured.",
  114. )
  115. timid = optparse.make_option(
  116. '', '--timid', action='store_true',
  117. help=(
  118. "Use a simpler but slower trace method. Try this if you get "
  119. "seemingly impossible results!"
  120. ),
  121. )
  122. title = optparse.make_option(
  123. '', '--title', action='store', metavar="TITLE",
  124. help="A text string to use as the title on the HTML.",
  125. )
  126. version = optparse.make_option(
  127. '', '--version', action='store_true',
  128. help="Display version information and exit.",
  129. )
  130. class CoverageOptionParser(optparse.OptionParser, object):
  131. """Base OptionParser for coverage.py.
  132. Problems don't exit the program.
  133. Defaults are initialized for all options.
  134. """
  135. def __init__(self, *args, **kwargs):
  136. super(CoverageOptionParser, self).__init__(
  137. add_help_option=False, *args, **kwargs
  138. )
  139. self.set_defaults(
  140. action=None,
  141. append=None,
  142. branch=None,
  143. concurrency=None,
  144. debug=None,
  145. directory=None,
  146. fail_under=None,
  147. help=None,
  148. ignore_errors=None,
  149. include=None,
  150. module=None,
  151. omit=None,
  152. parallel_mode=None,
  153. pylib=None,
  154. rcfile=True,
  155. show_missing=None,
  156. skip_covered=None,
  157. source=None,
  158. timid=None,
  159. title=None,
  160. version=None,
  161. )
  162. self.disable_interspersed_args()
  163. self.help_fn = self.help_noop
  164. def help_noop(self, error=None, topic=None, parser=None):
  165. """No-op help function."""
  166. pass
  167. class OptionParserError(Exception):
  168. """Used to stop the optparse error handler ending the process."""
  169. pass
  170. def parse_args_ok(self, args=None, options=None):
  171. """Call optparse.parse_args, but return a triple:
  172. (ok, options, args)
  173. """
  174. try:
  175. options, args = \
  176. super(CoverageOptionParser, self).parse_args(args, options)
  177. except self.OptionParserError:
  178. return False, None, None
  179. return True, options, args
  180. def error(self, msg):
  181. """Override optparse.error so sys.exit doesn't get called."""
  182. self.help_fn(msg)
  183. raise self.OptionParserError
  184. class GlobalOptionParser(CoverageOptionParser):
  185. """Command-line parser for coverage.py global option arguments."""
  186. def __init__(self):
  187. super(GlobalOptionParser, self).__init__()
  188. self.add_options([
  189. Opts.help,
  190. Opts.version,
  191. ])
  192. class CmdOptionParser(CoverageOptionParser):
  193. """Parse one of the new-style commands for coverage.py."""
  194. def __init__(self, action, options, defaults=None, usage=None, description=None):
  195. """Create an OptionParser for a coverage.py command.
  196. `action` is the slug to put into `options.action`.
  197. `options` is a list of Option's for the command.
  198. `defaults` is a dict of default value for options.
  199. `usage` is the usage string to display in help.
  200. `description` is the description of the command, for the help text.
  201. """
  202. if usage:
  203. usage = "%prog " + usage
  204. super(CmdOptionParser, self).__init__(
  205. usage=usage,
  206. description=description,
  207. )
  208. self.set_defaults(action=action, **(defaults or {}))
  209. self.add_options(options)
  210. self.cmd = action
  211. def __eq__(self, other):
  212. # A convenience equality, so that I can put strings in unit test
  213. # results, and they will compare equal to objects.
  214. return (other == "<CmdOptionParser:%s>" % self.cmd)
  215. def get_prog_name(self):
  216. """Override of an undocumented function in optparse.OptionParser."""
  217. program_name = super(CmdOptionParser, self).get_prog_name()
  218. # Include the sub-command for this parser as part of the command.
  219. return "%(command)s %(subcommand)s" % {'command': program_name, 'subcommand': self.cmd}
  220. GLOBAL_ARGS = [
  221. Opts.debug,
  222. Opts.help,
  223. Opts.rcfile,
  224. ]
  225. CMDS = {
  226. 'annotate': CmdOptionParser(
  227. "annotate",
  228. [
  229. Opts.directory,
  230. Opts.ignore_errors,
  231. Opts.include,
  232. Opts.omit,
  233. ] + GLOBAL_ARGS,
  234. usage="[options] [modules]",
  235. description=(
  236. "Make annotated copies of the given files, marking statements that are executed "
  237. "with > and statements that are missed with !."
  238. ),
  239. ),
  240. 'combine': CmdOptionParser(
  241. "combine",
  242. [
  243. Opts.append,
  244. ] + GLOBAL_ARGS,
  245. usage="[options] <path1> <path2> ... <pathN>",
  246. description=(
  247. "Combine data from multiple coverage files collected "
  248. "with 'run -p'. The combined results are written to a single "
  249. "file representing the union of the data. The positional "
  250. "arguments are data files or directories containing data files. "
  251. "If no paths are provided, data files in the default data file's "
  252. "directory are combined."
  253. ),
  254. ),
  255. 'debug': CmdOptionParser(
  256. "debug", GLOBAL_ARGS,
  257. usage="<topic>",
  258. description=(
  259. "Display information on the internals of coverage.py, "
  260. "for diagnosing problems. "
  261. "Topics are 'data' to show a summary of the collected data, "
  262. "or 'sys' to show installation information."
  263. ),
  264. ),
  265. 'erase': CmdOptionParser(
  266. "erase", GLOBAL_ARGS,
  267. description="Erase previously collected coverage data.",
  268. ),
  269. 'help': CmdOptionParser(
  270. "help", GLOBAL_ARGS,
  271. usage="[command]",
  272. description="Describe how to use coverage.py",
  273. ),
  274. 'html': CmdOptionParser(
  275. "html",
  276. [
  277. Opts.directory,
  278. Opts.fail_under,
  279. Opts.ignore_errors,
  280. Opts.include,
  281. Opts.omit,
  282. Opts.title,
  283. ] + GLOBAL_ARGS,
  284. usage="[options] [modules]",
  285. description=(
  286. "Create an HTML report of the coverage of the files. "
  287. "Each file gets its own page, with the source decorated to show "
  288. "executed, excluded, and missed lines."
  289. ),
  290. ),
  291. 'report': CmdOptionParser(
  292. "report",
  293. [
  294. Opts.fail_under,
  295. Opts.ignore_errors,
  296. Opts.include,
  297. Opts.omit,
  298. Opts.show_missing,
  299. Opts.skip_covered,
  300. ] + GLOBAL_ARGS,
  301. usage="[options] [modules]",
  302. description="Report coverage statistics on modules."
  303. ),
  304. 'run': CmdOptionParser(
  305. "run",
  306. [
  307. Opts.append,
  308. Opts.branch,
  309. Opts.concurrency,
  310. Opts.include,
  311. Opts.module,
  312. Opts.omit,
  313. Opts.pylib,
  314. Opts.parallel_mode,
  315. Opts.source,
  316. Opts.timid,
  317. ] + GLOBAL_ARGS,
  318. usage="[options] <pyfile> [program options]",
  319. description="Run a Python program, measuring code execution."
  320. ),
  321. 'xml': CmdOptionParser(
  322. "xml",
  323. [
  324. Opts.fail_under,
  325. Opts.ignore_errors,
  326. Opts.include,
  327. Opts.omit,
  328. Opts.output_xml,
  329. ] + GLOBAL_ARGS,
  330. usage="[options] [modules]",
  331. description="Generate an XML report of coverage results."
  332. ),
  333. }
  334. OK, ERR, FAIL_UNDER = 0, 1, 2
  335. class CoverageScript(object):
  336. """The command-line interface to coverage.py."""
  337. def __init__(self, _covpkg=None, _run_python_file=None,
  338. _run_python_module=None, _help_fn=None, _path_exists=None):
  339. # _covpkg is for dependency injection, so we can test this code.
  340. if _covpkg:
  341. self.covpkg = _covpkg
  342. else:
  343. import coverage
  344. self.covpkg = coverage
  345. # For dependency injection:
  346. self.run_python_file = _run_python_file or run_python_file
  347. self.run_python_module = _run_python_module or run_python_module
  348. self.help_fn = _help_fn or self.help
  349. self.path_exists = _path_exists or os.path.exists
  350. self.global_option = False
  351. self.coverage = None
  352. self.program_name = os.path.basename(sys.argv[0])
  353. if self.program_name == '__main__.py':
  354. self.program_name = 'coverage'
  355. if env.WINDOWS:
  356. # entry_points={'console_scripts':...} on Windows makes files
  357. # called coverage.exe, coverage3.exe, and coverage-3.5.exe. These
  358. # invoke coverage-script.py, coverage3-script.py, and
  359. # coverage-3.5-script.py. argv[0] is the .py file, but we want to
  360. # get back to the original form.
  361. auto_suffix = "-script.py"
  362. if self.program_name.endswith(auto_suffix):
  363. self.program_name = self.program_name[:-len(auto_suffix)]
  364. def command_line(self, argv):
  365. """The bulk of the command line interface to coverage.py.
  366. `argv` is the argument list to process.
  367. Returns 0 if all is well, 1 if something went wrong.
  368. """
  369. # Collect the command-line options.
  370. if not argv:
  371. self.help_fn(topic='minimum_help')
  372. return OK
  373. # The command syntax we parse depends on the first argument. Global
  374. # switch syntax always starts with an option.
  375. self.global_option = argv[0].startswith('-')
  376. if self.global_option:
  377. parser = GlobalOptionParser()
  378. else:
  379. parser = CMDS.get(argv[0])
  380. if not parser:
  381. self.help_fn("Unknown command: '%s'" % argv[0])
  382. return ERR
  383. argv = argv[1:]
  384. parser.help_fn = self.help_fn
  385. ok, options, args = parser.parse_args_ok(argv)
  386. if not ok:
  387. return ERR
  388. # Handle help and version.
  389. if self.do_help(options, args, parser):
  390. return OK
  391. # We need to be able to import from the current directory, because
  392. # plugins may try to, for example, to read Django settings.
  393. sys.path[0] = ''
  394. # Listify the list options.
  395. source = unshell_list(options.source)
  396. omit = unshell_list(options.omit)
  397. include = unshell_list(options.include)
  398. debug = unshell_list(options.debug)
  399. # Do something.
  400. self.coverage = self.covpkg.coverage(
  401. data_suffix=options.parallel_mode,
  402. cover_pylib=options.pylib,
  403. timid=options.timid,
  404. branch=options.branch,
  405. config_file=options.rcfile,
  406. source=source,
  407. omit=omit,
  408. include=include,
  409. debug=debug,
  410. concurrency=options.concurrency,
  411. )
  412. if options.action == "debug":
  413. return self.do_debug(args)
  414. elif options.action == "erase":
  415. self.coverage.erase()
  416. return OK
  417. elif options.action == "run":
  418. return self.do_run(options, args)
  419. elif options.action == "combine":
  420. if options.append:
  421. self.coverage.load()
  422. data_dirs = args or None
  423. self.coverage.combine(data_dirs)
  424. self.coverage.save()
  425. return OK
  426. # Remaining actions are reporting, with some common options.
  427. report_args = dict(
  428. morfs=unglob_args(args),
  429. ignore_errors=options.ignore_errors,
  430. omit=omit,
  431. include=include,
  432. )
  433. self.coverage.load()
  434. total = None
  435. if options.action == "report":
  436. total = self.coverage.report(
  437. show_missing=options.show_missing,
  438. skip_covered=options.skip_covered, **report_args)
  439. elif options.action == "annotate":
  440. self.coverage.annotate(
  441. directory=options.directory, **report_args)
  442. elif options.action == "html":
  443. total = self.coverage.html_report(
  444. directory=options.directory, title=options.title,
  445. **report_args)
  446. elif options.action == "xml":
  447. outfile = options.outfile
  448. total = self.coverage.xml_report(outfile=outfile, **report_args)
  449. if total is not None:
  450. # Apply the command line fail-under options, and then use the config
  451. # value, so we can get fail_under from the config file.
  452. if options.fail_under is not None:
  453. self.coverage.set_option("report:fail_under", options.fail_under)
  454. if self.coverage.get_option("report:fail_under"):
  455. # Total needs to be rounded, but don't want to report 100
  456. # unless it is really 100.
  457. if 99 < total < 100:
  458. total = 99
  459. else:
  460. total = round(total)
  461. if total >= self.coverage.get_option("report:fail_under"):
  462. return OK
  463. else:
  464. return FAIL_UNDER
  465. return OK
  466. def help(self, error=None, topic=None, parser=None):
  467. """Display an error message, or the named topic."""
  468. assert error or topic or parser
  469. if error:
  470. print(error)
  471. print("Use '%s help' for help." % (self.program_name,))
  472. elif parser:
  473. print(parser.format_help().strip())
  474. else:
  475. help_params = dict(self.covpkg.__dict__)
  476. help_params['program_name'] = self.program_name
  477. if CTracer is not None:
  478. help_params['extension_modifier'] = 'with C extension'
  479. else:
  480. help_params['extension_modifier'] = 'without C extension'
  481. help_msg = textwrap.dedent(HELP_TOPICS.get(topic, '')).strip()
  482. if help_msg:
  483. print(help_msg.format(**help_params))
  484. else:
  485. print("Don't know topic %r" % topic)
  486. def do_help(self, options, args, parser):
  487. """Deal with help requests.
  488. Return True if it handled the request, False if not.
  489. """
  490. # Handle help.
  491. if options.help:
  492. if self.global_option:
  493. self.help_fn(topic='help')
  494. else:
  495. self.help_fn(parser=parser)
  496. return True
  497. if options.action == "help":
  498. if args:
  499. for a in args:
  500. parser = CMDS.get(a)
  501. if parser:
  502. self.help_fn(parser=parser)
  503. else:
  504. self.help_fn(topic=a)
  505. else:
  506. self.help_fn(topic='help')
  507. return True
  508. # Handle version.
  509. if options.version:
  510. self.help_fn(topic='version')
  511. return True
  512. return False
  513. def do_run(self, options, args):
  514. """Implementation of 'coverage run'."""
  515. if not args:
  516. self.help_fn("Nothing to do.")
  517. return ERR
  518. if options.append and self.coverage.get_option("run:parallel"):
  519. self.help_fn("Can't append to data files in parallel mode.")
  520. return ERR
  521. if options.concurrency == "multiprocessing":
  522. # Can't set other run-affecting command line options with
  523. # multiprocessing.
  524. for opt_name in ['branch', 'include', 'omit', 'pylib', 'source', 'timid']:
  525. # As it happens, all of these options have no default, meaning
  526. # they will be None if they have not been specified.
  527. if getattr(options, opt_name) is not None:
  528. self.help_fn(
  529. "Options affecting multiprocessing must be specified "
  530. "in a configuration file."
  531. )
  532. return ERR
  533. if not self.coverage.get_option("run:parallel"):
  534. if not options.append:
  535. self.coverage.erase()
  536. # Run the script.
  537. self.coverage.start()
  538. code_ran = True
  539. try:
  540. if options.module:
  541. self.run_python_module(args[0], args)
  542. else:
  543. filename = args[0]
  544. self.run_python_file(filename, args)
  545. except NoSource:
  546. code_ran = False
  547. raise
  548. finally:
  549. self.coverage.stop()
  550. if code_ran:
  551. if options.append:
  552. data_file = self.coverage.get_option("run:data_file")
  553. if self.path_exists(data_file):
  554. self.coverage.combine(data_paths=[data_file])
  555. self.coverage.save()
  556. return OK
  557. def do_debug(self, args):
  558. """Implementation of 'coverage debug'."""
  559. if not args:
  560. self.help_fn("What information would you like: config, data, sys?")
  561. return ERR
  562. for info in args:
  563. if info == 'sys':
  564. sys_info = self.coverage.sys_info()
  565. print(info_header("sys"))
  566. for line in info_formatter(sys_info):
  567. print(" %s" % line)
  568. elif info == 'data':
  569. self.coverage.load()
  570. data = self.coverage.data
  571. print(info_header("data"))
  572. print("path: %s" % self.coverage.data_files.filename)
  573. if data:
  574. print("has_arcs: %r" % data.has_arcs())
  575. summary = data.line_counts(fullpath=True)
  576. filenames = sorted(summary.keys())
  577. print("\n%d files:" % len(filenames))
  578. for f in filenames:
  579. line = "%s: %d lines" % (f, summary[f])
  580. plugin = data.file_tracer(f)
  581. if plugin:
  582. line += " [%s]" % plugin
  583. print(line)
  584. else:
  585. print("No data collected")
  586. elif info == 'config':
  587. print(info_header("config"))
  588. config_info = self.coverage.config.__dict__.items()
  589. for line in info_formatter(config_info):
  590. print(" %s" % line)
  591. else:
  592. self.help_fn("Don't know what you mean by %r" % info)
  593. return ERR
  594. return OK
  595. def unshell_list(s):
  596. """Turn a command-line argument into a list."""
  597. if not s:
  598. return None
  599. if env.WINDOWS:
  600. # When running coverage.py as coverage.exe, some of the behavior
  601. # of the shell is emulated: wildcards are expanded into a list of
  602. # file names. So you have to single-quote patterns on the command
  603. # line, but (not) helpfully, the single quotes are included in the
  604. # argument, so we have to strip them off here.
  605. s = s.strip("'")
  606. return s.split(',')
  607. def unglob_args(args):
  608. """Interpret shell wildcards for platforms that need it."""
  609. if env.WINDOWS:
  610. globbed = []
  611. for arg in args:
  612. if '?' in arg or '*' in arg:
  613. globbed.extend(glob.glob(arg))
  614. else:
  615. globbed.append(arg)
  616. args = globbed
  617. return args
  618. HELP_TOPICS = {
  619. 'help': """\
  620. Coverage.py, version {__version__} {extension_modifier}
  621. Measure, collect, and report on code coverage in Python programs.
  622. usage: {program_name} <command> [options] [args]
  623. Commands:
  624. annotate Annotate source files with execution information.
  625. combine Combine a number of data files.
  626. erase Erase previously collected coverage data.
  627. help Get help on using coverage.py.
  628. html Create an HTML report.
  629. report Report coverage stats on modules.
  630. run Run a Python program and measure code execution.
  631. xml Create an XML report of coverage results.
  632. Use "{program_name} help <command>" for detailed help on any command.
  633. For full documentation, see {__url__}
  634. """,
  635. 'minimum_help': """\
  636. Code coverage for Python. Use '{program_name} help' for help.
  637. """,
  638. 'version': """\
  639. Coverage.py, version {__version__} {extension_modifier}
  640. Documentation at {__url__}
  641. """,
  642. }
  643. def main(argv=None):
  644. """The main entry point to coverage.py.
  645. This is installed as the script entry point.
  646. """
  647. if argv is None:
  648. argv = sys.argv[1:]
  649. try:
  650. status = CoverageScript().command_line(argv)
  651. except ExceptionDuringRun as err:
  652. # An exception was caught while running the product code. The
  653. # sys.exc_info() return tuple is packed into an ExceptionDuringRun
  654. # exception.
  655. traceback.print_exception(*err.args)
  656. status = ERR
  657. except CoverageException as err:
  658. # A controlled error inside coverage.py: print the message to the user.
  659. print(err)
  660. status = ERR
  661. except SystemExit as err:
  662. # The user called `sys.exit()`. Exit with their argument, if any.
  663. if err.args:
  664. status = err.args[0]
  665. else:
  666. status = None
  667. return status