Tuesday, November 1, 2016

Creating an REPL is easy in Python

By Vasudev Ram

Read Eval Print Loop

It's easy to create a simple Python REPL (a Read-Eval-Print Loop) in Python - with code.interact(), that is, with the interact function from the code module in Python's standard library.

I wrote and interacted with a small Python program to illustrate it.

It sets a couple of variables, then calls code.interact(), at which point I interact with the program via the REPL session that interact() creates.

I can see and set the variables set earlier by the program, because I pass the locals() dict to interact().

I can define a function in the session, which can access the variables set before the session.

And any changes the session makes to the variables, via my assignments, persist in the program after the interactive session ends (upon typing Ctrl-Z) and the program continues.

All this is shown in the code and output below:
from __future__ import print_function
# Reference:
# https://docs.python.org/2.7/library/code.html
# https://docs.python.org/3.6/library/code.html
# code_interact.py
# Copyright 2016 Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: http://jugad2.blogspot.com
# Product store: https://gumroad.com/vasudevram

import code

a = 1
b = "hello"
print("Before code.interact, a = {}, b = {}".format(a, b))

banner="code.interact session, type Ctrl-Z to exit."
code.interact( banner=banner, local=locals())

print("After code.interact, a = {}, b = {}".format(a, b))
The output of the program:
$ python code_interact.py
Before code.interact, a = 1, b = hello
code.interact session, type Ctrl-Z to exit.
>>> greeting = "hello "
>>> times = 2
>>> a
>>> b
>>> def repeat_string(s, n):
...     return s * n
>>> repeat_string(greeting, times)
'hello hello '
>>> repeat_string(greeting, a)
'hello '
>>> repeat_string(b, times)
>>> a += 2
>>> a
>>> repeat_string(greeting, a)
'hello hello hello '
>>> repeat_string(b, a)
After code.interact, a = 3, b = hello
While on the topic of REPLs, check out these earlier posts:

repl.it, online REPL for many languages, and empythoned.

Codingbat, Progress Graphs and Michael Jordan

codepad.org, executable multi-language pastebin, in Python

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

FlyWheel - Managed WordPress Hosting

No comments: