This is my first post to this list.

I wish to use Jython in my Java application to evaluate expressions on-the-fly.

I have successfully embedded Jython and can evaluate simple expressions.


I have a question about loops.

Consider this simple expression

a = 1
while a<10:
    a = a + 1

If I pass the entire string (all three lines of code) to the interpreter, it works fine.

PythonInterpreter interp = new PythonInterpreter();
interp.exec(sourceString);

However, if I pass each line separately, then it throws an exception when reading the while statement since it expects some code with indentation after the while statement. The error message is

("mismatched input '<EOF>' expecting INDENT", ('<string>', 3, 11, 'while a<10:\n'))


If I pass each line to the interpreter, then I can inform the user which line has error. If I pass the entire code as a string, then I only have the error message generated by python. If I can get the exact line number which has error, then I could tell that to the user. Alternatively, if I can send each line for execution, then I know the line number which has error. What should I do?


I have another question as well.

The PythonInterpreter object has all the local variables that have been assigned a value during execution. Is there a way I can get a list of all the local variables and their values? Currently, I am parsing the code myself to figure out all the variables that might have been assigned a value and then am asking the PythonInterpreter (Object value = interp.get(variableName)) to fetch the value corresponding to that variable.

Thanks,