文章主要保留代码,供以后查看
maven引入的jar包
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.5.2</version>
</dependency>
Java代码:
package com.test.python;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class JavaUsePython {
public static void main(String[] args) {
// TODO Auto-generated method stub
//调用Python语句
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
interpreter.exec("print days[1];");//会在console输出Tue
//执行Python中的函数
interpreter.execfile("C:\\Users\\Administrator\\Desktop\\pythonTest\\adder.py");
PyFunction func = (PyFunction) interpreter.get("adder", PyFunction.class);
int a = 2010, b = 2;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("anwser = " + pyobj.toString());
//调用脚本
interpreter.execfile("C:\\Users\\Administrator\\Desktop\\pythonTest\\input.py");
}
}