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

No comments: