Summarize java to call the python method

  • 2020-05-05 11:13:46
  • OfStack

This article shares java call python method for your reference, the specific content is as follows

1. Directly execute python statement

in the java class

import org.python.util.PythonInterpreter;
public class FirstJavaScript {
  public static void main(String args[]) {

    PythonInterpreter interpreter = new PythonInterpreter();

    interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
    interpreter.exec("print days[1];");

  }// main
}

The result of the call is Tue, shown in the console, which is called directly.

2. Call the function

from the native python script in java

Start by creating an python script, my_utils.py


def adder(a, b): 
  return a + b 

Then create an java class to test

java class code FirstJavaScript:


import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class FirstJavaScript {
  public static void main(String args[]) {

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("C:\\Python27\\programs\\my_utils.py");
    PyFunction func = (PyFunction) interpreter.get("adder",
        PyFunction.class);

    int a = 2010, b = 2;
    PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
    System.out.println("anwser = " + pyobj.toString());

  }// main
}

The result is: anwser = 2012

3. Directly execute python script

using java

Create script inputpy


 #open files 

 print 'hello' 
 number=[3,5,2,0,6] 
 print number 
 number.sort() 
 print number 
 number.append(0) 
 print number 
 print number.count(0) 
 print number.index(5)

Create the java class and call this script:


import org.python.util.PythonInterpreter;

public class FirstJavaScript {
  public static void main(String args[]) {

    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("C:\\Python27\\programs\\input.py");
  }// main
}

The result is:


hello 
[3, 5, 2, 0, 6] 
[0, 2, 3, 5, 6] 
[0, 2, 3, 5, 6, 0] 
2 
3 

These are the three java call python methods, I hope to help you learn.


Related articles: