如何使用 Jython 执行 if 语句
How to execute if statement using Jython
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1:");
interp.exec(" print('in if statement!'");
}
}
我需要能够从 Java 程序执行 Python 代码,因此决定试用 Jython,但我对它不熟悉。我尝试执行上面的代码,但得到了错误:"Exception in thread "main" SyntaxError: ("mismatched input '' expecting INDENT", ('', 1, 9, 'if 2 > 1:\n'))"。知道这意味着什么,或者我如何使用 PythonInterpreter 执行 if 语句?
条件必须作为单个字符串输入,并且有一个额外的括号:
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1: print 'in if statement!'");
}
}
无需使用字符串逐行执行脚本,您可以调用解释器来 运行 文件。您所要做的就是提供 python 文件的文件路径,在此示例中,将 script.py
放在 src
文件夹中。
script.py
if 2 > 1:
print 'in if statement'
JythonTest.java
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("src/script.py");
}
}
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1:");
interp.exec(" print('in if statement!'");
}
}
我需要能够从 Java 程序执行 Python 代码,因此决定试用 Jython,但我对它不熟悉。我尝试执行上面的代码,但得到了错误:"Exception in thread "main" SyntaxError: ("mismatched input '' expecting INDENT", ('', 1, 9, 'if 2 > 1:\n'))"。知道这意味着什么,或者我如何使用 PythonInterpreter 执行 if 语句?
条件必须作为单个字符串输入,并且有一个额外的括号:
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("if 2 > 1: print 'in if statement!'");
}
}
无需使用字符串逐行执行脚本,您可以调用解释器来 运行 文件。您所要做的就是提供 python 文件的文件路径,在此示例中,将 script.py
放在 src
文件夹中。
script.py
if 2 > 1:
print 'in if statement'
JythonTest.java
import org.python.util.PythonInterpreter;
public class JythonTest {
public static void main(String[] args) {
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("src/script.py");
}
}