http://download.csdn.net/detail/xingjiarong/9429266 Download the Jython package and add the Jython.jar to the project catalog
First, execute the Python statement directly in the Java class
import org.python.util.PythonInterpreter;publicclass FirstJavaScript { publicstaticvoidmain(String args[]) { 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, which is displayed in the console, which is called directly.
Second, call the function in native Python script in Java
First, create a python script named: my_utils.py
def adder(a, b): return a + b
Then build a Java class that you can use 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 voidMain (String args[]) {Pythoninterpreter interpreter =NewPythoninterpreter (); Interpreter.execfile ("c:\\python27\\programs\\my_utils.py"); pyfunction func = (pyfunction) interpreter.Get("Adder", Pyfunction.class); int a = ., B =2; Pyobject pyobj = func.__call__ (NewPyinteger (a),NewPyinteger (b)); System.out.println ("Anwser ="+ pyobj.tostring ()); }//Main}
The resulting result is: Anwser = 2012
C. Execute python script directly using Java
Create a script inputpy
#open files ‘hello‘ number=[3,5,2,0,6] number number.sort() number number.append(0) number number.count(0) number.index(5)
To create a Java class, call this script:
import org.python.util.PythonInterpreter;publicclass FirstJavaScript { publicstaticvoidmain(String args[]) { new PythonInterpreter(); interpreter.execfile("C:\\Python27\\programs\\input.py"); }// main}
The resulting results are:
View Plain
hello [3, 5, 2, 0, 6] [0, 2, 3, 5, 6] [0, 2, 3, 5, 6, 0] 2 3
Java Call Python method summary