Skip to content

Improve REPL KI #3030

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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
36 changes: 36 additions & 0 deletions src/trio/_repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,42 @@ def runcode(self, code: types.CodeType) -> None:
# We always use sys.excepthook, unlike other implementations.
# This means that overriding self.write also does nothing to tbs.
sys.excepthook(sys.last_type, sys.last_value, sys.last_traceback)
# clear any residual KI
trio.from_thread.run(trio.lowlevel.checkpoint_if_cancelled)
# trio.from_thread.check_cancelled() has too long of a memory

if sys.platform == "win32":

def raw_input(self, prompt: str = "") -> str:
try:
return input(prompt)
except EOFError:
# check if trio has a pending KI
trio.from_thread.run(trio.lowlevel.checkpoint_if_cancelled)
raise

else:

def raw_input(self, prompt: str = "") -> str:
import fcntl
import termios
from signal import SIGINT, signal

interrupted = False

def handler(sig: int, frame: types.FrameType | None) -> None:
nonlocal interrupted
interrupted = True
# Fake up a newline char as if user had typed it at terminal
fcntl.ioctl(sys.stdin, termios.TIOCSTI, b"\n")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can't write to sys.stdin from a handler safely, I'm not sure if you can icotl to the .fileno() or not either, I think you need:

@disable_ki_protection
def _newline():
    # Fake up a newline char as if user had typed it at terminal
    fcntl.ioctl(sys.stdin, termios.TIOCSTI, b"\n")


class TrioInteractiveConsole:
    token = trio.lowlevel.current_trio_token()

    def handler(...):
        nonlocal interrupted
        interrupted = True
        token.run_sync_soon(_newline, idempotent=True)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I think I understand why, but won't a keyboard interrupt in the newline function blow up trio and end the repl? If so, Would suppressing the exception be sufficient?


prev_handler = trio.from_thread.run_sync(signal, SIGINT, handler)
try:
return input(prompt)
finally:
trio.from_thread.run_sync(signal, SIGINT, prev_handler)
if interrupted:
raise KeyboardInterrupt


async def run_repl(console: TrioInteractiveConsole) -> None:
Expand Down
Loading