using pexpect to control python

Ben Last ben at
Wed Aug 25 10:49:44 CEST 2004

> From Maurice LING
> Another thing which I'm thinking previously is how can I embed a python
> interpreter (not compiler) that does line by line interpretation and
> execution, in a python program? I realized that python's language
> services has a compile package that can be invoked to compile python
> source into python bytecodes but that's provided that the codes are in a
> file. Perhaps what I'm interested may be how to embed and use the
> interactive mode of python interpreter in a python program?

Sounds to me like you're doing the sort of thing that a Python shell written
in python already does.  The codeop package provides a CommandCompiler()
class that will compile lines of Python from strings at runtime.  The exec
statement then executes the bytecode objects.  The
code.InteractiveInterpreter class shows how this can be used to build an
interpreter shell.  Take a look at
(source freely available, naturally!) for more examples.  Most of the stuff
you want is in the QuasiInterpreter class that inherits heavily from

Although you say "interpreter (not compiler)", the compile()/exec()
combination will work with individual lines (or rather, blocks), so don't
think of it as full source compilation.  That's not Pythonic :)


More information about the Python-list mailing list