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

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Can the jython script return a value to the enclosing java program, received as the result of the eval() method?
0

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

1 Comment

exec does not solve the problem, then I receive the following SyntaxError: no viable alternative at character '''

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.