来源URL:http://blog.csdn.net/zhongweijian/article/details/4742549
1.从http://www.jython.org/Project/installation.html下载jython安装文件,运行命令“Java -jar jython_installer-2.5.0.jar,jython即安装成功.
2.把jython安装目录加入到系统环境变量,在java工程中加入jython安装目录下的jython.jar即可在java中使用jython了。
下面是我的实例,一个是在java中运行test.py脚本,一个是直接在java中直接运行Python命令。
- import org.python.util.PythonInterpreter;
- import org.python.core.*;
- public class JythonTest {
- public static void main(String[] args) {
-
-
-
- PythonInterpreter interp =
- new PythonInterpreter();
- System.out.println("Hello, brave new world");
- interp.exec("import sys");
- interp.exec("print sys");
- interp.set("a", new PyInteger(42));
- interp.exec("print a");
- interp.exec("x = 2+2");
- PyObject x = interp.get("x");
- System.out.println("x: "+x);
- System.out.println("Goodbye, cruel world");
- }
- }