Calling Python Functions from Java
Java Program
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
class PythonJava
{
PythonInterpreter interpreter = null;
public PythonJava()
{
PythonInterpreter.initialize(System.getProperties(),System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main( String gargs[] )
{
PythonJava ie = new PythonJava();
ie.execfile("general.py");
PyInstance hello = ie.createClass("General", "7");
int f=Integer.parseInt(hello.invoke("factorial").toString());
System.out.println("Factorial is "+f);
}
}
# general.py
class General:
def __init__(self,num):
self.num=int(num)
def factorial(self):
f=1
for i in range(1,self.num+1):
f=f*i
return f
Download the required JAR file
http://www.java2s.com/Code/Jar/j/Downloadjythoncompletejar.htm
Comments
Post a Comment