~/Building a Simple Python REPL

Mar 15, 2020


A REPL is a language shell that reads user input, evaluates it, prints the result, and loops back. In Python, you can create a basic REPL with a simple loop and the eval function.

Here is an example:

1
2
3
4
5
6
7
8
9
while True:
    try:
        command = input('>>> ')
        if command in ('exit', 'quit'):
            break
        result = eval(command)
        print(result)
    except Exception as e:
        print('Error:', e)

This script will:

For more complex statements, use exec instead of eval. For example:

1
2
3
4
5
6
7
8
while True:
    try:
        command = input('>>> ')
        if command in ('exit', 'quit'):
            break
        exec(command)
    except Exception as e:
        print('Error:', e)

Be cautious: using eval or exec can be dangerous if you run untrusted code. See the Python docs on eval for security guidelines.

This is the simplest way to build a Python REPL.

Tags: [python]