Skip to content
Myr

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

4 files+271 added−35 removed

modified:docs/exceptions.md+37 added-11 removed
modified:src/click/core.py+52 added-24 removed
97 unmodified lines
9899 raise RuntimeError(message)100101102def _echo_aborted() -> None:103 """Write the final abort message to standard error."""104 echo(_("Aborted!"), file=sys.stderr)105106107def _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 lines
15501551 # Process shell completion requests and exit early.1552 self._main_shell_completion(extra, prog_name, complete_var)15531554 # 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 = 115621563 try:1564 try:1565 with self.make_context(prog_name, args, **extra) as ctx:1566 rv = self.invoke(ctx)
6 unmodified lines
1573 # 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_code15881589 exit_code = e.exit_code1590 except Abort:1591 if not standalone_mode:1592 raise15931594 report = _echo_aborted1595 except (EOFError, KeyboardInterrupt) as e:1596 # The blank line closes the terminal's ``^C`` echo.1597 echo(file=sys.stderr)15981599 if not standalone_mode:1565 raise Abort() from e1600 raise Abort() from e16011602 report = _echo_aborted1603 except ClickException as e:1604 if not standalone_mode:1605 raise1569 e.show()1570 sys.exit(e.exit_code)16061607 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:16111612 sys.stdout = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stdout))1613 sys.stderr = t.cast(t.TextIO, _PacifyFlushWrapper(sys.stderr))16141615 if report is not None:1616 report()16171618 sys.exit(exit_code)1619 except (EOFError, KeyboardInterrupt):1620 if not standalone_mode:1621 raise1594 echo(_("Aborted!"), file=sys.stderr)1595 sys.exit(1)16221623 sys.exit(exit_code)16241625 def _main_shell_completion(1626 self,1627 ctx_args: cabc.MutableMapping[str, t.Any],1628 prog_name: str,
2199 unmodified lines
added:tests/test_abort_interrupt.py+179 added
1"""A second Ctrl-C while ``Command.main()`` reported an abort or an error used2to escape as an unhandled traceback: the message and the exit both ran in3``except`` clauses, outside every ``try`` that caught ``KeyboardInterrupt``.4https://github.com/pallets/click/issues/380256The fix holds one policy, the one the pager has followed since7https://github.com/pallets/click/pull/351: a late interrupt must not replace8the intended outcome. In standalone mode the collected exit code wins, for9aborts, errors and success alike, and the message is best effort. Without10standalone mode the interrupt propagates to the caller. Two settled contracts11stay in place: the first interrupt reaches a non-standalone caller as12``Abort`` (https://github.com/pallets/click/pull/2380), and the ``Aborted!``13message stays as it is (declined in14https://github.com/pallets/click/issues/1447 and15https://github.com/pallets/click/issues/2584).16"""1718import sys1920import pytest2122import click232425class RecordingStderr:26 """A stderr stand-in that records what is written to it.2728 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 """3233 def __init__(self, interrupt_at=None):34 self.text = ""35 self.interrupt_at = interrupt_at36 self.isatty_calls = 03738 def isatty(self):39 self.isatty_calls += 14041 if self.isatty_calls == self.interrupt_at:42 raise KeyboardInterrupt4344 return False4546 def write(self, value):47 self.text += value48 return len(value)4950 def flush(self):51 pass525354def _interrupt_prompt(text):55 """Stand in for ``input()`` when the user presses Ctrl-C at a prompt."""56 raise KeyboardInterrupt575859def _prompting_command():60 @click.command()61 @click.option("--name", prompt="Name")62 def cli(name):63 click.echo(name)6465 return cli666768def _interrupting_command():69 @click.command()70 def cli():71 raise KeyboardInterrupt7273 return cli747576def _exit_code(cli, stderr, monkeypatch):77 """Run *cli* in standalone mode and return its exit code."""78 monkeypatch.setattr(sys, "stderr", stderr)7980 try:81 cli.main([], "cli")82 except SystemExit as e:83 return e.code84 except KeyboardInterrupt:85 pytest.fail("KeyboardInterrupt escaped Command.main()")8687 pytest.fail("Command.main() returned without exiting")888990@pytest.mark.parametrize(91 ("source", "interrupt_at"),92 [("prompt", None), ("prompt", 1), ("body", None), ("body", 1), ("body", 2)],93)94def test_interrupt_while_reporting_abort(monkeypatch, source, interrupt_at):95 """Exit code 1 survives a second Ctrl-C; the message may not.9697 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()108109 stderr = RecordingStderr(interrupt_at=interrupt_at)110111 assert _exit_code(cli, stderr, monkeypatch) == 1112113 if interrupt_at is None:114 assert "Aborted!" in stderr.text115116117def test_interrupt_while_reporting_error(monkeypatch):118 """A Ctrl-C while Click writes an error keeps the error's exit code."""119120 class InterruptedReport(click.ClickException):121 exit_code = 3122123 def show(self, file=None):124 raise KeyboardInterrupt125126 @click.command()127 def cli():128 raise InterruptedReport("boom")129130 assert _exit_code(cli, RecordingStderr(), monkeypatch) == 3131132133def test_late_interrupt_with_disabled_standalone_mode(monkeypatch):134 """Without standalone mode, a late interrupt reaches the caller, not exit 1.135136 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 """140141 class InterruptedAbort(click.Abort):142 def __init__(self):143 raise KeyboardInterrupt144145 monkeypatch.setattr(click.core, "Abort", InterruptedAbort)146 cli = _interrupting_command()147 monkeypatch.setattr(sys, "stderr", RecordingStderr())148149 with pytest.raises(KeyboardInterrupt):150 cli.main([], "cli", standalone_mode=False)151152153def test_interrupt_while_exiting_after_success(monkeypatch):154 """A Ctrl-C while a successful exit propagates keeps exit code 0.155156 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 """160161 @click.command()162 def cli():163 click.echo("done")164165 real_exit = sys.exit166 codes = []167168 def interrupted_exit(code=None):169 codes.append(code)170171 if len(codes) == 1:172 raise KeyboardInterrupt173174 real_exit(code)175176 monkeypatch.setattr(sys, "exit", interrupted_exit)177178 assert _exit_code(cli, RecordingStderr(), monkeypatch) == 0179 assert codes == [0, 0]
modified:CHANGES.md+3 added
1 unmodified line
23Unreleased45- 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`910## Version 8.5.01112Released 2026-08-24
1655 unmodified lines