Interactive interpreter hooks

Robert Kern robert.kern at gmail.com
Mon Jun 3 09:19:33 EDT 2013


On 2013-06-03 08:55, Steven D'Aprano wrote:
> The sys module defines two hooks that are used in the interactive
> interpreter:
>
> * sys.displayhook(value) gets called with the result of evaluating the
> line when you press ENTER;
>
> * sys.excepthook(type, value, traceback) gets called with the details of
> the exception when your line raises an exception.
>
> Is there a way to hook into the interactive interpreter *before* it is
> evaluated? That is, if I type "len([])" at the prompt and hit ENTER, I
> want a hook that runs before len([]) is evaluated to 0, so that I get the
> string "len([])".

You will need to write your own REPL for this. Use the code.InteractiveConsole 
class:

   http://docs.python.org/2/library/code

I recommend source-diving to see what you need to override, but I suspect you 
can just wrap around the `runsource()` method.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list