JavaWeb调⽤python脚本(可传参)以下是个⼈在使⽤SSM 调⽤python脚本时遇到的问题及注意点,该案例可以下tomcat Web中访问调⽤python脚本。
public class DemoController{
/**
getPythonDemo2 中参数pyPath, args1, args2 可通过前端(AJAX)传过来
注意:(1)参数pyPath ,python脚本路径最好使⽤绝对路径,如果python(.py)脚本中也有⽂件路径读取,同样推荐使⽤绝对路径(2)该案例中,python脚本接受的参数 args1, args2是String类型,务必确认python脚本中使⽤的参数类型是否是String类型,根据需要进⾏相应的类型转换    */
/**
* 调⽤python
* 参数pyPath, args1, args2 可通过前端(AJAX)传过来
*/
@ResponseBody
@RequestMapping(value="/getPythonDemo.ajax")
public int getPythonDemo2(String pyPath, String args1, String args2){
DemoController demo = new DemoController ();  //实例化类
System.out.println("pyPath= "+pyPath);
System.out.println("args1= "+args1);
System.out.println("args2= "+args2);
int res =PythonDemo(pyPath, args1, args2);      //调⽤python的⽅法
return res;
}
/**
* 调⽤python脚本该⽅法⽀持python中的第三⽅库
* @param pyPath python脚本路径
* @param args1 参数1
* @param args2 参数2
*/
public String getPythonDemo(String pyPath, String args1, String args2){
Process proc;
String line = null;
List<String> lines = new ArrayList<String>();
try {
String[] args1 = new String[] { "python"
/
/ ,"/usr/local/tomcat/webapps/demo_console/WEB-INF/model/demo.py"      linux绝对路径
            //,"D:\\tomcat\\webapps\\wtpwebapps\\demo_console\\WEB-INF\\model\\demo.py"    windows绝对路径
,pyPath
,String.valueOf(args1)
,String.valueOf(args2)
};
proc = Runtime().exec(args1);  //该⽅法参数必须是String类型的
//⽤输⼊输出流来截取结果python转java代码
BufferedReader in = new BufferedReader(new InputStream(), "gbk"));  //gbk 避免汉字乱码
while ((line = in.readLine()) != null) {
System.out.println(line);
lines.add(line);  //把Python的print值保存了下来
}
in.close();
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Java调Python脚本结束");
String lineData = String();
return lineData;
}
}
Process proc = Runtime().exec(args1); 使⽤该⽅法调⽤python脚本或命令
Process exitValue 值说明:
  Process exitValue: 0      调⽤python脚本成功
  Process exitValue: 1      java调⽤python失败
  Process exitValue: 2      python脚本执⾏失败
demo.py 脚本:以下脚本可⽀持第三⽅库使⽤(未写相关案例)
#coding:utf-8
import pandas as pd
import numpy as np
import sklearn
import sys
def Add(a,b):
sum = a + b
print(sum)
if__name__ == "__main__":
a = []
for i in range(1, len(sys.argv)):        a.append(sys.argv[i])
Add(a[0],a[1])

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。