This is a demonstration of the Python code module, which allows for an interactive interpreter to be embedded into a Python program.
Convenience function to run a read-eval-print loop. This creates a new instance
of InteractiveConsole
and sets readfunc to be used as the
InteractiveConsole.raw_input()
method, if provided. If local is
provided, it is passed to the InteractiveConsole
constructor for use as
the default namespace for the interpreter loop. The interact() method of the
instance is then run with banner passed as the banner to use, if provided. The
console object is discarded after use.
code.interact
is useful for:
- Pre-loading
python
interactive interpreter. (flask-script does this.) - Embedding an interactive interpreter in a program, with an internal DSL.
- Quick interactive debugging (you probably want
pdb.set_trace()
).
Example:
$ python interact.py
>>> foo
'this is foo'
>>> bar
'this is bar'
>>> 6 * 7
42
>>>
$
Closely emulate the behavior of the interactive Python interpreter. This class
builds on InteractiveInterpreter
and adds prompting using the familiar
sys.ps1
and sys.ps2
, and input buffering.
code.InteractiveConsole
is useful when you want to customize the REPL:
- Changing the REPL behavior of the
python
interactive interpreter. - Embedding an interactive interpreter in a program, with an external DSL.
- Provide a scripting interface for an external DSL.
Example:
$ python console.py
> room
No one is in the room.
> enter John Mary Joseph
John enters the room.
Mary enters the room.
Joseph enters the room.
> exit Joseph
Joseph leaves the room.
> room
In the room: John, Mary
>
$
Non-interactive usage:
$ echo 'room' | python console.py
No one is in the room.
$
Non-interactive scripting (could update code to take files on sys.argv):
python console.py <<EOF
enter John Mary Joseph
exit Joseph
room
EOF
... produces output:
John enters the room.
Mary enters the room.
Joseph enters the room.
Joseph leaves the room.
In the room: John, Mary
Selected real-world use cases of code.InteractiveConsole
:
- interactive step interpreter for Cucumber-style steps, with behave
- send bytes interactively to test a network protocol driver
- command REPL for an instrument controller