Customizing code.InteractiveConsole

Leonhard Vogt leonhard.vogt at
Sat Aug 30 20:48:53 CEST 2008


I have subclassed code.InteractiveInterpreter for testing
an "interpreter" i have written myself.

The interpreter is a function (evaluate) that can raise
MyError exceptions. I want these to be reported with an
indication of the position (^) as in the python interactive

The code below does this, but I don't like the raise-catch
of the syntax error before using self.showsyntaxerror().
How could I improve this? Should I subclass from SyntaxError?

The other thing is that the ^ is shown to the left of the
faulty character, I could easily correct that, but why is this?


import code

class MyError(Exception):
     def __init__(self, msg, pos):
         Exception.__init__(self, msg)
         self.pos = pos

def evaluate(source):
     for (pos,c) in enumerate(source):
         if not c in "0123456789":
             raise MyError("Unexpected Symbol %s" % c, pos)
     return int(source)

class MyConsole(code.InteractiveConsole):
     def raw_input(self, prompt):
         return code.InteractiveConsole.raw_input(self, 'abc '+prompt)

     def runsource(self, source, filename='<stdin>'):
             print evaluate(source)
         except MyError, e:
                 se = SyntaxError(str(e), ('', 1, e.pos, source))
                 raise se

if __name__ == '__main__':

And here what it shows on the console:

leonhard at leovaio:~/mypy$ python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
abc >>> 1234
abc >>> 12e4
   File "<string>", line 1
SyntaxError: Unexpected Symbol e
abc >>>

More information about the Python-list mailing list