最近工作中需要在Java中调用Python代码,网上找了一些,汇总一下:
-
直接执行Python脚本代码
-
PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
-
执行python .py文件
- 直接执行python.py文件
-
PythonInterpreter interpreter = new PythonInterpreter(); InputStream filepy = new FileInputStream("D:\\demo.py"); interpreter.execfile(filepy); ///执行python py文件 filepy.close();
- 执行python.py文件中的方法
-
PythonInterpreter interpreter = new PythonInterpreter(); //由于python文件中引入了random,所以在运行脚本的时候需要提前将jyphon的lib路径加载进来 PySystemState sys = Py.getSystemState(); sys.path.add("D:\\soft\\jython\\jython2.5.2\\Lib"); interpreter.exec("import random"); interpreter.execfile("E:\\py_test\\pythonTest.py"); PyFunction func = (PyFunction) interpreter.get("add", PyFunction.class); int a = 2010, b = 2; PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b)); System.out.println("anwser = " + pyobj.toString());
- 使用Runtime.getRuntime()执行脚本文件
-
Process proc = Runtime.getRuntime().exec("python D:\\demo.py"); proc.waitFor();//等待执行脚本的子程序执行完毕后再继续执行后面的代码
-
注意:
1.前面三种方法需要导入jython包,
最后一种方法需要安装Python,配置Python的环境变量
2.在执行Python脚本文件的时候,如果引入了外部文件或者模块,需要提前将路径加载进来:sys.path.add("D:\\soft\\jython\\jython2.5.2\\Lib");
3.在用第三种方法调用python脚本中的方法的时候,如果函数参数过多,可以使用function.__call__(args, keywords);
参考:http://bbs.csdn.net/topics/390737063
https://zhidao.baidu.com/question/167261197.html