1, http://sourceforge.net/projects/jython/Download the Jython package, add the Jython.jar to the project directory
Example:
1. Excerpt from: http://blog.csdn.net/anbo724/article/details/6608632
1. Execute python statements directly in the Java class
- 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 is Tue, which is displayed in the console, which is called directly.
2. Call the functions in the 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 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\\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 resulting result is: Anwser = 2012
3. Execute the Python script directly using Java,
Create a 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 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 resulting results are:
- Hello
- [3, 5, 2, 0, 6]
- [0, 2, 3, 5, 6]
- [0, 2, 3, 5, 6, 0]
- 2
- 3
Share:
Calling the Python method in Java