Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a python method from a java class?

I am using Jython within a Java project.

I have one Java class: myJavaClass.java and one Python class: myPythonClass.py

public class myJavaClass{
    public String myMethod() {
        PythonInterpreter interpreter = new PythonInterpreter();
        //Code to write
    }
 }

The Python file is as follows:

class myPythonClass:
    def abc(self):
        print "calling abc"
        tmpb = {}
        tmpb = {'status' : 'SUCCESS'}
        return tmpb

Now the problem is I want to call the abc() method of my Python file from the myMethod method of my Java file and print the result.

like image 555
Hasti Avatar asked Feb 21 '12 17:02

Hasti


People also ask

Can we call Python method from Java?

You can use Java Runtime. exec() to run python script, As an example first create a python script file using shebang and then set it executable.

Can we use Python in spring boot?

We can use our python implementation just as we would use a normal Spring service. That was just a simple example but it wouldn't be much different if we need to create more complex python classes that rely on external libraries, etc. We can also extend Java classes in Python.


1 Answers

If I read the docs right, you can just use the eval function:

interpreter.execfile("/path/to/python_file.py");
PyDictionary result = interpreter.eval("myPythonClass().abc()");

Or if you want to get a string:

PyObject str = interpreter.eval("repr(myPythonClass().abc())");
System.out.println(str.toString());

If you want to supply it with some input from Java variables, you can use set beforehand and than use that variable name within your Python code:

interpreter.set("myvariable", Integer(21));
PyObject answer = interpreter.eval("'the answer is: %s' % (2*myvariable)");
System.out.println(answer.toString());
like image 68
Niklas B. Avatar answered Sep 29 '22 19:09

Niklas B.