支持多行输入的 REPL 框架
约 224 字小于 1 分钟
2025-12-08
至此我们要开始写一些代码了。REPL (Read-Eval-Print Loop) 是一个交互式解释器,它允许用户输入代码并立即得到结果。在 pyec 中,我们提供了一个简单的 REPL,它之后可以让我们快速地看到输入的字符串经过变换做得到的结果。
PROMPT = "=>> "
PROMPT_CONTINUE = " >> "
def start() -> None:
lines: list[str] = []
while True:
try:
if line := input(
PROMPT if not lines else PROMPT_CONTINUE
): # read a line of input with prompt
lines.append(line)
else:
print("\n".join(lines))
lines.clear()
except KeyboardInterrupt: # handle Ctrl+C
print("<KeyboardInterrupt>")
except EOFError: # handle Ctrl+D
print("Ctrl-D detected, exiting REPL.")
exit(0)下面是一个基本的 REPL 工作过程。
在这个 REPL 实现中,我们接收多行输入,但是没有实现 Evaluation,仅仅是输出接收到的输入。当我们输入 Ctrl + C 时,会输出 <KeyboardInterrupt>。当输入 Ctrl + D 的时候,会触发 EOFError,程序就结束。
以下是运行效果:
$ uv run pyec
Hello jiefeic, this is PYEC! Type any command or Ctrl+D to exit.
=>> 123
>> 456
>>
123
456
=>> Ctrl-D detected, exiting REPL.