在我的 Java 应用程序中,我想使用 Jython 来解释 Python 代码。
所以我按如下方式初始化 Jython:
PySystemState.initialize();
PythonInterpreter jython = new PythonInterpreter();
然后我想像这样测试它:
jython.eval("out = ''");
jython.eval("out += 'Test1\n'");
jython.eval("out += 'Test2\n'");
System.out.println(jython.get("out").toString());
但是,第一个 eval 行会抛出此错误:
File "<string>", line 1
out = ''
^
SyntaxError: mismatched input '=' expecting EOF
当我尝试使用 exec 而不是 eval 时,我收到此错误:
File "<string>", line 2
'
^
SyntaxError: no viable alternative at character '''
知道我在这里做错了什么吗?
PS:我使用的是 jython-2.5.4-rc1
最佳答案
您需要确保具备以下条件
- 声明一个
out
变量 - 由于您使用的是 Java,因此请转义特殊字符,例如
\\n
- 使用
exec
而不是eval
这将产生:
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());
关于java - Jython SyntaxError(来自 Java 应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776099/