Skip to content

Allow passing exception classes for KeyboardInterrupt and EOFError in PromptSession #1884

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/prompt_toolkit/shortcuts/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,10 @@ class PromptSession(Generic[_T]):
:param input: `Input` object. (Note that the preferred way to change the
input/output is by creating an `AppSession`.)
:param output: `Output` object.
:param interrupt_exception: The exception type that will be raised when
there is a keyboard interrupt (control-c keypress).
:param eof_exception: The exception type that will be raised when there is
an end-of-file/exit event (control-d keypress).
"""

_fields = (
Expand Down Expand Up @@ -410,6 +414,8 @@ def __init__(
refresh_interval: float = 0,
input: Input | None = None,
output: Output | None = None,
interrupt_exception: type[BaseException] = KeyboardInterrupt,
eof_exception: type[BaseException] = EOFError,
) -> None:
history = history or InMemoryHistory()
clipboard = clipboard or InMemoryClipboard()
Expand Down Expand Up @@ -459,6 +465,8 @@ def __init__(
self.reserve_space_for_menu = reserve_space_for_menu
self.tempfile_suffix = tempfile_suffix
self.tempfile = tempfile
self.interrupt_exception = interrupt_exception
self.eof_exception = eof_exception

# Create buffers, layout and Application.
self.history = history
Expand Down Expand Up @@ -811,7 +819,7 @@ def _complete_like_readline(event: E) -> None:
@handle("<sigint>")
def _keyboard_interrupt(event: E) -> None:
"Abort when Control-C has been pressed."
event.app.exit(exception=KeyboardInterrupt, style="class:aborting")
event.app.exit(exception=self.interrupt_exception(), style="class:aborting")

@Condition
def ctrl_d_condition() -> bool:
Expand All @@ -826,7 +834,7 @@ def ctrl_d_condition() -> bool:
@handle("c-d", filter=ctrl_d_condition & default_focused)
def _eof(event: E) -> None:
"Exit when Control-D has been pressed."
event.app.exit(exception=EOFError, style="class:exiting")
event.app.exit(exception=self.eof_exception(), style="class:exiting")

suspend_supported = Condition(suspend_to_background_supported)

Expand Down
Loading