cmdline.py 25 KB

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