Any ideas? public clas开发者_JS百科s Main {
public static void main(String[] args) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
engine.put("hello_str", "");
engine.eval("for i in range(10):");
engine.eval(" hello_str += str(i)");
Object x = engine.get("hello_str");
System.out.println("x: " + x);
}
}
error is
Exception in thread "main" javax.script.ScriptException: SyntaxError: mismatched input '' expecting INDENT in at line number 1 at column number 18 at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:170) at org.python.jsr223.PyScriptEngine.compileScript(PyScriptEngine.java:76) at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:33) at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247) at javaapplication2.Main.main(Main.java:23) Caused by: File "", line 1 for i in range(10): ^ SyntaxError: mismatched input '' expecting INDENT
Looks like you are trying to evaluate an incomplete statement in the lines:
engine.eval("for i in range(10):");
engine.eval(" hello_str += str(i)");
Here, I assume eval()
is trying to evaluate these one-by-one, and finding nothing after the for
is erroring out since that is an incomplete statement. Try this:
engine.eval("for i in range(10):\n hello_str += str(i)");
The newline is not necessary in this case, but it would be if you want to include several statements in the loop body, eg:
engine.eval("for i in range(10):\n hello_str += str(i)\n print i");
Also note that in the example above the amount of spacing after each new line should be equal. In fact, I would suggest assembling the script string completely before evaluating it. Or better yet, read it from a separate .py file.
精彩评论