Home >Backend Development >Python Tutorial >Call python method in java
1. Directly execute python statements in the java class
view plain
import javax.script.*;
import org.python.util.PythonInterpreter;
import java.io.*;
import static java.lang.System. *;
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 obtained in this way It is Tue, which is displayed on the console and is called directly.
2. Call the function in the native python script in java:
First create a python script named: my_utils.py
view plain
def adder(a, b):
return a + b
Then Create a java class for testing,
java class code FirstJavaScript:
view plain
import javax.script.*;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.io.*;
import static java.lang.System.*;
public class FirstJavaScript
{
public static void main( String ARGS []) {
pythonIninterPreter interpreter = new pythoninInterpreter ();
interpreter.execfile ("C: \ python27 \ my_utils.py"); This name y pyfunction func = (pyfunction) interpreter. get("adder",PyFunction.class);//adder python function name int a = 2010, b = 2;
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));// Pass value, a b
System.out.println("anwser = " + pyobj.toString());
}//main
}
The result is: anwser = 2012
3. Use java to directly execute the python script ,
Create the script inputpy
view plain
#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 a java class and call this script:
view plain
import javax.script.*;
import org.python.core .PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import java.io.*;
import static java.lang.System. *;
public class FirstJavaScript
{
public static void main(String args[])
{
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("C:\Python27\programs\input.py");
}//main
}
The result is:
view plain
hello
[3, 5, 2, 0, 6]
[0, 2, 3, 5, 6]
[0, 2, 3, 5, 6, 0]
2
3