I know jython allows us to call a java method from any java's classfile as if they were written for python, but is the reverse possible ???
I already have so many algorithms that written in python, they work pretty well with python and jython but they lack a proper GUI. I am planing to bring the GUI with the java and to keep the python library intact. I am not able to write a good GUI with jython or python and I cannot write a good algorithm with python. So the solution I found was to merge java's GUI and python's library. Is this possible. Can I call python's library from java.
Yes, that can be done . Normally this will be done by creating a PythonInterpreter
object and then calling the python class using that .
Consider the following example :
Java :
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
public class InterpreterExample
{
PythonInterpreter interpreter = null;
public InterpreterExample()
{
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[] )
{
InterpreterExample ie = new InterpreterExample();
ie.execfile("hello.py");
PyInstance hello = ie.createClass("Hello", "None");
hello.invoke("run");
}
}
Python :
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print 'Hello world!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With