1

In my Java app I want to use Jython to interpret Python code.
So I initialise Jython as follows:

PySystemState.initialize();
PythonInterpreter jython = new PythonInterpreter();

Then I want to test it like this:

jython.eval("out = ''");
jython.eval("out += 'Test1\n'");
jython.eval("out += 'Test2\n'");
System.out.println(jython.get("out").toString());

However, the first eval line throws this error:

  File "<string>", line 1
    out = ''
       ^
SyntaxError: mismatched input '=' expecting EOF

When I try it with exec instead of eval I get this error:

  File "<string>", line 2
    '
    ^
SyntaxError: no viable alternative at character '''

Any ideas what I am doing wrong here?

PS: I am using jython-2.5.4-rc1

Matthias
  • 9,817
  • 14
  • 66
  • 125

2 Answers2

2

You'll need to ensure you have the following

  • Declare an out variable
  • Because you're using Java, escape special characters such as \\n
  • Use exec rather than eval

This will produce:

PythonInterpreter jython = new PythonInterpreter();
jython.set("out", new PyString());
jython.exec("out = ''");
jython.exec("out += 'Test1\\n'");
jython.exec("out += 'Test2\\n'");
System.out.println(jython.get("out").toString());
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You should use exec to execute statements. eval evaluates and returns a PyObject.

Erik Pilz
  • 3,836
  • 2
  • 17
  • 7
  • exec does not solve the problem, then I receive the following SyntaxError: no viable alternative at character ''' – Matthias Apr 02 '13 at 23:59