Customizing code.InteractiveConsole



Hello

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
interpreter.

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?


Leo

========================================================================
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>'):
try:
print evaluate(source)
except MyError, e:
try:
se = SyntaxError(str(e), ('', 1, e.pos, source))
raise se
except:
self.showsyntaxerror()


if __name__ == '__main__':
MyConsole().interact()

=======================================================================
And here what it shows on the console:


leonhard@leovaio:~/mypy$ python cons.py
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.
(MyConsole)
abc >>> 1234
1234
abc >>> 12e4
File "<string>", line 1
12e4
^
SyntaxError: Unexpected Symbol e
abc >>>
.



Relevant Pages

  • Re: Compiler for BASIC BBC
    ... Difference between BASIC interpreter and the ABC. ... Nor is there any need to 'restore' a ...
    (comp.sys.acorn.programmer)
  • Re: How to determine what exceptions a method might raise?
    ... exceptions the interpreter can raise. ... is there an easy way in the interactive interpreter ...
    (comp.lang.python)
  • Re: How to take advantage of multi-tablers?
    ... My observations so far are that they play pretty ... ABC and I'm not sure the best way to take advantage of that. ... re-raise pre-flop more, continuation bet more, overbet, underbet, etc? ... Check raise them more. ...
    (rec.gambling.poker)
  • Re: Itcl and TIP#257
    ... magical multi-interp commands. ... Access to the object in every interpreter. ... would raise would be a huge pile of work, ...
    (comp.lang.tcl)