1)编写mytest.py完成一个简单加法计算
# coding:utf8 #def 表示一个方法 adder def adder(a, b): return a+b #这里执行adder方法并打印出结果 print adder(1,2)
2)运行以上脚本方式如图
1+2 = 3 打印成功!
3)java调用python脚本的两种方式
Process process = Runtime.getRuntime().exec("python E:\\mytest.py"); InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line; while((line = input.readLine()) != null) System.out.println(line); input.close(); ir.close();
结果如下图展示:该方法目前没找到可以给python传参,但是支持运行python脚本中的三方类库
通过jython-standalone-2.7.0.jar调用python
PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("E:\\test.py"); PyFunction func = (PyFunction)interpreter.get("retHtml",PyFunction.class); PyObject pyobj = func.__call__(new PyInteger(2016),new PyInteger(2016)); System.out.println("retMsg = " + pyobj);