Fix race condition on `KeyboardInterrupt` arriving in `Command.main()`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Closes #3802
authored by Kevin Deldycke · committed by Kevin Deldycke · parent 08a7bc6 · Browse files · 4 files·+271 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+271 added−35 removed
- tests:+179 added−0 removed
- other:+92 added−35 removed
Provenance
- Commit
fc518e4- Tree
c68088d- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
08a7bc6
4 files changed+271 added−35 removed
modified:docs/exceptions.md+37 added-11 removed
17 unmodified lines181920212223222325242526272827282930313233342930313233343536373839404142434445464720 unmodified lines686970717273747576777879808182838485868788899091929369 unmodified lines17 unmodified lines## Where are Errors Handled?
Click's main error handling is happening in {meth}`Command.main`. Inthere it handles all subclasses of {exc}`ClickException` as well as thestandard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions. Thelatter are internally translated into an {exc}`Abort`.standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions.
The logic applied is the following:The table below lists every way a command can end, and what Click doesfor each. The middle column is the default. The last column applies when{meth}`Command.main` runs with ``standalone_mode=False``, which the nextsection describes.
1. If an {exc}`EOFError` or {exc}`KeyboardInterrupt` happens, reraise it as {exc}`Abort`.2. If a {exc}`ClickException` is raised, invoke the {meth}`ClickException.show` method on it to display it and then exit the program with {attr}`ClickException.exit_code`.3. If an {exc}`Abort` exception is raised print the string ``Aborted!`` to standard error and exit the program with exit code ``1``.4. If it goes through well, exit the program with exit code ``0``.| How the command ends | Standalone mode | ``standalone_mode=False`` || --- | --- | --- || It returns | Exit with code ``0`` | Return the value of {meth}`Command.invoke` || It called {meth}`Context.exit` | Exit with the given code | Return the given code || It raised a {exc}`ClickException` | Call {meth}`ClickException.show`, then exit with {attr}`ClickException.exit_code` | Propagate it || The user pressed ``Ctrl-C``, which raises a {exc}`KeyboardInterrupt` | Print a blank line, then ``Aborted!`` to standard error, and exit with code ``1`` | Print a blank line, then raise {exc}`Abort` with the original exception as its ``__cause__`` || The user pressed ``Ctrl-D``, which raises an {exc}`EOFError` | The same as ``Ctrl-C`` | The same as ``Ctrl-C`` || It raised an {exc}`Abort` | Print ``Aborted!`` to standard error, and exit with code ``1`` | Propagate it || The output pipe closed early, which raises an {exc}`OSError` with ``EPIPE`` | Silence the flush errors, and exit with code ``1`` | The same || It raised any other exception | Propagate it | Propagate it |
Click writes the message and exits once that handling is done. Aninterrupt arriving during this last step cannot change the exit code thetable gave. It can only cost the message.
## What if I Don't Want That?
Generally you always have the option to invoke the {meth}`Command.invoke`method yourself. For instance if you have a {class}`Command` you can20 unmodified lines standalone_mode=False,)```
This is also how you replace the ``Aborted!`` message. Standalone modeturns off every row of the table above, so catch the cases you want tokeep and write your own message for the rest:
```pythontry: command.main( ["command-name", "args", "go", "here"], standalone_mode=False, )except click.Abort: click.echo("Bye!", err=True) raise SystemExit(1)except click.ClickException as e: e.show() raise SystemExit(e.exit_code)```
## Which Exceptions Exist?
Click has two exception bases: {exc}`ClickException` which is raised forall exceptions that Click wants to signal to the user and {exc}`Abort`69 unmodified linesmodified:src/click/core.py+52 added-24 removed
97 unmodified lines98 99 raise RuntimeError(message)100 101 102+def _echo_aborted() -> None:103+ """Write the final abort message to standard error."""104+ echo(_("Aborted!"), file=sys.stderr)105+106+107 def _format_deprecated_label(deprecated: bool | str) -> str:108 """Return the parenthesized deprecation label shown in help text."""109 label = _("deprecated").upper()110 if isinstance(deprecated, str):1439 unmodified lines1550 1551 # Process shell completion requests and exit early.1552 self._main_shell_completion(extra, prog_name, complete_var)1553 1554+ # Every handler below takes the same two steps: propagate when1555+ # standalone mode is disabled, otherwise collect the message and the1556+ # exit code, and leave both to the teardown after the ``try``. The1557+ # teardown writes the message and exits, and the outermost handler1558+ # holds one policy for every interrupt arriving that late: the1559+ # message may be lost, the intended exit code still wins.1560+ report: cabc.Callable[[], None] | None = None1561+ exit_code = 11562+1563 try:1564 try:1565 with self.make_context(prog_name, args, **extra) as ctx:1566 rv = self.invoke(ctx)6 unmodified lines1573 # chained commands which all returned `None` -- so it's not1574 # even always obvious that `rv` indicates success/failure1575 # by its truthiness/falsiness1576 ctx.exit()1577+ except Exit as e:1578+ if not standalone_mode:1579+ # in non-standalone mode, return the exit code1580+ # note that this is only reached if `self.invoke` above raises1581+ # an Exit explicitly -- thus bypassing the check there which1582+ # would return its result1583+ # the results of non-standalone execution may therefore be1584+ # somewhat ambiguous: if there are codepaths which lead to1585+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to1586+ # tell the difference between the two1587+ return e.exit_code1588+1589+ exit_code = e.exit_code1590+ except Abort:1591+ if not standalone_mode:1592+ raise1593+1594+ report = _echo_aborted1595 except (EOFError, KeyboardInterrupt) as e:1596+ # The blank line closes the terminal's ``^C`` echo.1597 echo(file=sys.stderr)1598+1599+ if not standalone_mode:1565- raise Abort() from e1600+ raise Abort() from e1601+1602+ report = _echo_aborted1603 except ClickException as e:1604 if not standalone_mode:1605 raise1569- e.show()1570- sys.exit(e.exit_code)1606+1607+ report, exit_code = e.show, e.exit_code1608 except OSError as e:1572- if e.errno == errno.EPIPE:1573- sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1574- sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))1575- sys.exit(1)1576- else:1609+ if e.errno != errno.EPIPE:1610 raise1578- except Exit as e:1579- if standalone_mode:1580- sys.exit(e.exit_code)1581- else:1582- # in non-standalone mode, return the exit code1583- # note that this is only reached if `self.invoke` above raises1584- # an Exit explicitly -- thus bypassing the check there which1585- # would return its result1586- # the results of non-standalone execution may therefore be1587- # somewhat ambiguous: if there are codepaths which lead to1588- # `ctx.exit(1)` and to `return 1`, the caller won't be able to1589- # tell the difference between the two1590- return e.exit_code1591- except Abort:1611+1612+ sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1613+ sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))1614+1615+ if report is not None:1616+ report()1617+1618+ sys.exit(exit_code)1619+ except (EOFError, KeyboardInterrupt):1620 if not standalone_mode:1621 raise1594- echo(_("Aborted!"), file=sys.stderr)1595- sys.exit(1)1622 1623+ sys.exit(exit_code)1624+1625 def _main_shell_completion(1626 self,1627 ctx_args: cabc.MutableMapping[str, t.Any],1628 prog_name: str,2199 unmodified linesadded:tests/test_abort_interrupt.py+179 added
1+"""A second Ctrl-C while ``Command.main()`` reported an abort or an error used2+to escape as an unhandled traceback: the message and the exit both ran in3+``except`` clauses, outside every ``try`` that caught ``KeyboardInterrupt``.4+https://github.com/pallets/click/issues/38025+6+The fix holds one policy, the one the pager has followed since7+https://github.com/pallets/click/pull/351: a late interrupt must not replace8+the intended outcome. In standalone mode the collected exit code wins, for9+aborts, errors and success alike, and the message is best effort. Without10+standalone mode the interrupt propagates to the caller. Two settled contracts11+stay in place: the first interrupt reaches a non-standalone caller as12+``Abort`` (https://github.com/pallets/click/pull/2380), and the ``Aborted!``13+message stays as it is (declined in14+https://github.com/pallets/click/issues/1447 and15+https://github.com/pallets/click/issues/2584).16+"""17+18+import sys19+20+import pytest21+22+import click23+24+25+class RecordingStderr:26+ """A stderr stand-in that records what is written to it.27+28+ With ``interrupt_at=N``, the ``N``-th ``isatty()`` call raises29+ ``KeyboardInterrupt``. ``echo()`` calls ``isatty()`` before writing, which30+ is where the traceback in issue #3802 ended.31+ """32+33+ def __init__(self, interrupt_at=None):34+ self.text = ""35+ self.interrupt_at = interrupt_at36+ self.isatty_calls = 037+38+ def isatty(self):39+ self.isatty_calls += 140+41+ if self.isatty_calls == self.interrupt_at:42+ raise KeyboardInterrupt43+44+ return False45+46+ def write(self, value):47+ self.text += value48+ return len(value)49+50+ def flush(self):51+ pass52+53+54+def _interrupt_prompt(text):55+ """Stand in for ``input()`` when the user presses Ctrl-C at a prompt."""56+ raise KeyboardInterrupt57+58+59+def _prompting_command():60+ @click.command()61+ @click.option("--name", prompt="Name")62+ def cli(name):63+ click.echo(name)64+65+ return cli66+67+68+def _interrupting_command():69+ @click.command()70+ def cli():71+ raise KeyboardInterrupt72+73+ return cli74+75+76+def _exit_code(cli, stderr, monkeypatch):77+ """Run *cli* in standalone mode and return its exit code."""78+ monkeypatch.setattr(sys, "stderr", stderr)79+80+ try:81+ cli.main([], "cli")82+ except SystemExit as e:83+ return e.code84+ except KeyboardInterrupt:85+ pytest.fail("KeyboardInterrupt escaped Command.main()")86+87+ pytest.fail("Command.main() returned without exiting")88+89+90+@pytest.mark.parametrize(91+ ("source", "interrupt_at"),92+ [("prompt", None), ("prompt", 1), ("body", None), ("body", 1), ("body", 2)],93+)94+def test_interrupt_while_reporting_abort(monkeypatch, source, interrupt_at):95+ """Exit code 1 survives a second Ctrl-C; the message may not.96+97+ The counted ``isatty`` picks the window. A prompt converts the interrupt98+ to ``Abort`` itself, so the only window left in ``Command.main()`` is the99+ ``Aborted!`` message (``1``). An interrupt from the command body goes100+ through the conversion in ``Command.main()``, which writes a blank line101+ first (``1``), before the message (``2``).102+ """103+ if source == "prompt":104+ monkeypatch.setattr("click.termui.visible_prompt_func", _interrupt_prompt)105+ cli = _prompting_command()106+ else:107+ cli = _interrupting_command()108+109+ stderr = RecordingStderr(interrupt_at=interrupt_at)110+111+ assert _exit_code(cli, stderr, monkeypatch) == 1112+113+ if interrupt_at is None:114+ assert "Aborted!" in stderr.text115+116+117+def test_interrupt_while_reporting_error(monkeypatch):118+ """A Ctrl-C while Click writes an error keeps the error's exit code."""119+120+ class InterruptedReport(click.ClickException):121+ exit_code = 3122+123+ def show(self, file=None):124+ raise KeyboardInterrupt125+126+ @click.command()127+ def cli():128+ raise InterruptedReport("boom")129+130+ assert _exit_code(cli, RecordingStderr(), monkeypatch) == 3131+132+133+def test_late_interrupt_with_disabled_standalone_mode(monkeypatch):134+ """Without standalone mode, a late interrupt reaches the caller, not exit 1.135+136+ The patched ``Abort`` raises a second ``KeyboardInterrupt`` from its137+ constructor: it lands on the ``raise Abort() from e`` statement that138+ ``Command.main()`` only runs for non-standalone callers.139+ """140+141+ class InterruptedAbort(click.Abort):142+ def __init__(self):143+ raise KeyboardInterrupt144+145+ monkeypatch.setattr(click.core, "Abort", InterruptedAbort)146+ cli = _interrupting_command()147+ monkeypatch.setattr(sys, "stderr", RecordingStderr())148+149+ with pytest.raises(KeyboardInterrupt):150+ cli.main([], "cli", standalone_mode=False)151+152+153+def test_interrupt_while_exiting_after_success(monkeypatch):154+ """A Ctrl-C while a successful exit propagates keeps exit code 0.155+156+ The uniform policy: the run completed before the interrupt arrived, so the157+ intended outcome wins for success exactly as it does for aborts and158+ errors.159+ """160+161+ @click.command()162+ def cli():163+ click.echo("done")164+165+ real_exit = sys.exit166+ codes = []167+168+ def interrupted_exit(code=None):169+ codes.append(code)170+171+ if len(codes) == 1:172+ raise KeyboardInterrupt173+174+ real_exit(code)175+176+ monkeypatch.setattr(sys, "exit", interrupted_exit)177+178+ assert _exit_code(cli, RecordingStderr(), monkeypatch) == 0179+ assert codes == [0, 0]modified:CHANGES.md+3 added
1 unmodified line2 3 Unreleased4 5 - Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`6+- A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,7+ or while it exits, no longer escapes as an unhandled traceback. The command still8+ exits with the intended code; only the message may be lost. {issue}`3802`9 10 ## Version 8.5.011 12 Released 2026-08-241655 unmodified lines