java web调用python_JavaWeb调用python脚本(可传参)

public classDemoController{/**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 intgetPythonDemo2(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 =demo.getPythonDemo(pyPath, args1, args2); //调用python的方法

returnres;

}/*** 调用python脚本 该方法支持python中的第三方库

*@parampyPath python脚本路径

*@paramargs1 参数1

*@paramargs2 参数2*/

publicString getPythonDemo(String pyPath, String args1, String args2){

Process proc;

String line= null;

List lines = new ArrayList();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.getRuntime().exec(args1); //该方法参数必须是String类型的//用输入输出流来截取结果

BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "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=lines.toString();returnlineData;

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值