Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we call a python method from java? [duplicate]

Tags:

java

python

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.

like image 497
vikkyhacks Avatar asked May 09 '13 11:05

vikkyhacks


1 Answers

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!'
like image 193
The Dark Knight Avatar answered Sep 19 '22 14:09

The Dark Knight