Showing posts with label REPL. Show all posts
Showing posts with label REPL. Show all posts

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
1
>>> b
'hello'
>>> def repeat_string(s, n):
...     return s * n
...
>>> repeat_string(greeting, times)
'hello hello '
>>> repeat_string(greeting, a)
'hello '
>>> repeat_string(b, times)
'hellohello'
>>> a += 2
>>> a
3
>>> repeat_string(greeting, a)
'hello hello hello '
>>> repeat_string(b, a)
'hellohellohello'
>>>
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





Friday, March 1, 2013

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

By Vasudev Ram

repl.it is an online REPL (Read-Eval-Print-Loop) for multiple programming languages, including for Python. Some of the other supported languages are QBASIC, FORTH, Lua and Scheme and Ruby (it says "beta" for Ruby, but the other languages also may not have full support, e.g. see the excerpts below).

Here is a small test run of using repl.it with Python, that I just did:
Python 2.7.2 (default, Jul 20 2011, 02:32:18)
[GCC 4.2.1 (LLVM, Emscripten 1.5, Empythoned)] on linux2
   def foo(bar): 
..   print "in foo, bar =", bar 
..   
   foo(1)
in foo, bar = 1
   foo("ab")
in foo, bar = ab
   
   for i in range(4): 
..   foo(i) 
..   
in foo, bar = 0
in foo, bar = 1
in foo, bar = 2
in foo, bar = 3

   class Foo(): 
..   def bar(self): 
..     print "in Foo.bar()" 
..     
   
   foo = Foo()
   foo.bar()
in Foo.bar()
    

About repl.it.

For running Python, repl.it uses empythoned, which in turn uses emscripten.

Excerpts from the related tools' sites:

[ Empythoned is a build script that uses Emscripten to compile CPython for use in a browser. It attempts to compile the main interpreter as a single small executable and the whole standard library as dynamically loaded libraries.

The project is in its infancy. Right now the core interpreter works very well, but many of the libraries either don't work at all or contain various bugs. ]

[ Emscripten is an LLVM-to-JavaScript compiler. It takes LLVM bitcode - which can be generated from C/C++, using llvm-gcc or clang, or any other language that can be converted into LLVM - and compiles that into JavaScript, which can be run on the web (or anywhere else JavaScript can run).

Links to demos, tutorial, FAQ, etc: https://github.com/kripken/emscripten/wiki

Main project page: http://emscripten.org ]

- Vasudev Ram - Dancing Bison Enterprises



Saturday, August 4, 2012

Python's code.interact() - programmatically emulate the interpreter


By Vasudev Ram


The Python module named code (from the standard library) has a neat and potentially useful feature - it allows you to programmatically embed an REPL in a Python application.

It is more powerful than the Python REPL one-liner that I blogged about recently. For example, that REPL only allows Python expressions. This one allows Python statements, function definitions and invocations, and class definitions and method invocations. I tried all of those and they worked. Also, a syntax error does not cause an exit from this REPL, whereas the earlier one-liner exits on error.

Saw it via this tweet by Dan North (@tastapod).

To try it from your OS command prompt, use:
python -c "import code; code.interact(local=locals())"
This creates an instance of code.InteractiveConsole, a class from the code module, and runs it. The behavior closely emulates the interactive Python interpreter. Though I showed the use of it from the OS command prompt, it is more meant to be used from within a Python application, where it can potentially be quite useful, particularly if you can expose some of your application's API to the method. But it should probably be used with caution, in secure settings only.

- Vasudev Ram - Dancing Bison Enterprises

Saturday, July 28, 2012

Python REPL one-liner (Read-Eval-Print-Loop) by Raymond Hettinger and Cameron Laird

By Vasudev Ram


(Reformatted the stuff below a bit for clarity of the rendered HTML - no material changes made.)

@raymondh (Raymond Hettinger) tweeted:

Fun #python one-liner:
while True: request=raw_input('! '); result=eval(request); print repr(result)
# Read–eval–print_loop (REPL)

@Phaseit (Cameron Laird) replied:

@raymondh #python Why not compose all the evaluations?

I guess Cameron meant this:

while True: print repr(eval(raw_input('! ')))

Nice improvement - makes it a bit more functional) and shorter, without reducing clarity much.

To actually run it, the full command is:

python -c "while True: print repr(eval(raw_input('! ')))"

- Vasudev Ram - Dancing Bison Enterprises