Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to easily create a Python REPL (Read-Eval-Print Loop) in Python itself. This can allow the user to interact with a running Python program, including typing in Python statements at the REPL prompt, defining functions, using and changing variables that were set before the interaction started, and those variables modified during the interaction, will persist in the memory of the program, for any use, even after the interaction is over, as long as the program continues to run.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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))

'''
Run the program with the command:

$ python code_interact.py

and then interact with it, including printing or changing or using the values of variables defined in the program.
'''

The program works on both Python 2.7 and 3.6.

More details and sample output here:

http://jugad2.blogspot.in/2016/11/creating-repl-is-easy-in-python.html