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);
?
?
?
?
?
?
?
原文:http://zliguo.iteye.com/blog/2305245