read-eval-print-loop

Home Feed
2025-12-19 UNIXpythonyoutube

A vanilla version of REPL is 10 lines of python. Session runs waiting for input unless user exits the shell. Any valid input after ">>> " is echoed back to the user.

While this works for newline and command line, there is an error here.

python 🔗
import sys
import readline

def main():
    while True:
        sys.stdout.write(">>> ")     
        sys.stdout.flush()

        command_line = input().strip()  # trim leading/trailing spaces  
        if not command_line:
            continue
        print(f"You entered: {command_line}")  # return the input back to user

if __name__ == "__main__":
    main()

Pressing ctrl+c returns the (intended) KeyboardInterrupt error but exits the shell instead of ignoring the malformed input.

KeyboardInterrupt error

We add this behavior in an exception block. If the shell gets crtl+c, it should inform the user of KeyboardInterrupt and conveniently wait for the next input ">>> ". Let's go one step further and add EOFError handling when shell sees ctrl+d.

The below change handles these exceptions:

python 🔗
    try:
        command_line = input().strip()  
        if not command_line:
            continue
        print(f"You entered: {command_line}") 

    except KeyboardInterrupt:
        print("\nKeyboardInterrupt")
        break

    except EOFError:
        print()
        continue    
added some ascii.