This article for everyone to share the Java invoke Python method for your reference, the specific contents are as follows
First, execute the Python statement directly in the Java class
Import Org.python.util.PythonInterpreter;
public class Firstjavascript {public
static void Main (String args[]) {
Pythoninterpreter interpreter = new Python Interpreter ();
Interpreter.exec ("days=" (' MoD ', ' Tue ', ' Wed ', ' Thu ', ' Fri ', ' Sat ', ' Sun '); ");
Interpreter.exec ("Print days[1];");
Main
}
The result of the call is Tue, displayed in the console, which is directly invoked.
Ii. invoking functions in native Python scripts in Java
First, create a python script named: my_utils.py
Def adder (A, B): return
A + b
Then create a 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 Python Interpreter ();
Interpreter.execfile ("c:\\python27\\programs\\my_utils.py");
pyfunction func = (pyfunction) interpreter.get ("Adder",
pyfunction.class);
int a =, b = 2;
Pyobject pyobj = func.__call__ (New Pyinteger (a), new Pyinteger (b));
System.out.println ("Anwser =" + pyobj.tostring ());
} Main
}
The result is: Anwser = 2012
Iii. using Java to execute Python scripts directly
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)
To create a Java class, call this script:
Import Org.python.util.PythonInterpreter;
public class Firstjavascript {public
static void Main (String args[]) {
Pythoninterpreter interpreter = new Pyth Oninterpreter ();
Interpreter.execfile ("c:\\python27\\programs\\input.py");
} Main
}
The results obtained are:
Hello
[3 5, 2, 0, 6] [0, 2, 3,
5, 6] [0, 2, 3, 5, 6
, 0]
2
The above is three kinds of Java invoke Python method, hope to be helpful to everybody's study.