Jython是一个使用相当可靠的语法的快速Java脚本的好工具。 实际上,当使用jmx为您的Java应用程序实现一些维护或监视脚本时,它的运行效果非常好。
如果您与其他具有python背景的团队合作,则将python集成到您的java应用程序是绝对有意义的。
首先,让我们使用独立版本导入jython interpeter。
group 'com.gkatzioura'
version '1.0-SNAPSHOT'apply plugin: 'java'sourceCompatibility = 1.5repositories {mavenCentral()
}dependencies {testCompile group: 'junit', name: 'junit', version: '4.11'compile group: 'org.python', name: 'jython-standalone', version: '2.7.0'
}
因此,最简单的方法就是在我们的类路径中执行python文件。 该文件将是hello_world.py
print "Hello World"
然后将文件作为输入流传递给干预者
package com.gkatzioura;import org.python.core.PyClass;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyObjectDerived;
import org.python.util.PythonInterpreter;import java.io.InputStream;/*** Created by gkatzioura on 19/10/2016.*/
public class JythonCaller {private PythonInterpreter pythonInterpreter;public JythonCaller() {pythonInterpreter = new PythonInterpreter();}public void invokeScript(InputStream inputStream) {pythonInterpreter.execfile(inputStream);}}
@Testpublic void testInvokeScript() {InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("hello_world.py");jythonCaller.invokeScript(inputStream);}
下一步是创建一个python类文件和另一个将导入该类文件并实例化一个类的python文件。
该类文件将是divider.py。
class Divider:def divide(self,numerator,denominator):return numerator/denominator;
导入Divider类的文件将是classcaller.py
from divider import Dividerdivider = Divider()print divider.divide(10,5);
所以让我们测试一下
@Testpublic void testInvokeClassCaller() {InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("classcaller.py");jythonCaller.invokeScript(inputStream);}
从这个例子中我们可以理解的是,解释器成功地从类路径中导入了文件。
使用解释器运行文件是可以的,但是我们需要充分利用python中实现的类和函数。
因此,下一步是创建一个python类,并使用java使用其功能。
package com.gkatzioura;import org.python.core.PyClass;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyObjectDerived;
import org.python.util.PythonInterpreter;import java.io.InputStream;/*** Created by gkatzioura on 19/10/2016.*/
public class JythonCaller {private PythonInterpreter pythonInterpreter;public JythonCaller() {pythonInterpreter = new PythonInterpreter();}public void invokeClass() {pythonInterpreter.exec("from divider import Divider");PyClass dividerDef = (PyClass) pythonInterpreter.get("Divider");PyObject divider = dividerDef.__call__();PyObject pyObject = divider.invoke("divide",new PyInteger(20),new PyInteger(4));System.out.println(pyObject.toString());}}
您可以在github上找到源代码。
翻译自: https://www.javacodegeeks.com/2016/10/embed-jython-java-codebase.html