天天看点

java调用python脚本 并发_Java调用Python脚本

1)Window安装和环境配置

网上教程实在太多了,就不再叙述,自行百度

2)Linux安装和环境配置

linux环境部署,遇到的一些小问题:

Q1:./configure --prefix=/usr/local/python3.9 编译安装报错的话

A1:sudo yum install gcc-c++ 查看是否未安装合适的编译器

Q2:执行make出现编码问题

A2:在./configure操作前,先进行配置(etc/profile):

export LANGUAGE=en_US.UTF-8export LANG=en_US.UTF-8export LC_ALL=en_US.UTF-8

ps:这里需要注明的是,网上许多教程让直接把python删除掉,结果连yum命令也使用不了了,如下

1、删除现有Python

[[email protected]~]# rpm -qa|grep python|xargs rpm -ev --allmatches --nodeps ##强制删除已安装程序及其关联

[[email protected]~]# whereis python |xargs rm -frv ##删除所有残余文件 ##xargs,允许你对输出执行其他某些命令

[[email protected]~]# whereis python ##验证删除,返回无结果2、删除现有的yum

[[email protected]~]# rpm -qa|grep yum|xargs rpm -ev --allmatches --nodeps

[[email protected]~]# whereis yum |xargs rm -frv

解决:卸载centos自带python导致yum命令失效的方法

3)python脚本执行依赖

python脚本运行依赖,pip list查看所有依赖

$ wget https://bootstrap.pypa.io/get-pip.py

$ python get-pip.py

$ pip-V  #查看pip版本

$ pip install requests #requests包

$ pip install BeautifulSoup4 #BeautifulSoup4包

4)Java调用Python脚本代码

1 public ListpythonUtils(String keyWord){2 Process proc;3 String line = null;4 ArrayList list = newArrayList();5 try{6 String[] arg1 = new String[]{"python","E:\\python\\Amazon.py",keyWord};7 proc =Runtime.getRuntime().exec(arg1);8 //用输入输出流来截取结果

9 BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), "utf-8"));10 //创建对象要经try/catch里面,否则会无法接受到for输出每一个值

11 Python python = newPython();12 while ((line = in.readLine()) != null) {13 String[] string1 = line.split("==");14 for (int i = 0; i

17 String[] string2 = s.split(",");18 python.setShop(string2[0]);19 python.setName(string2[1]);20 python.setShop_yw(string2[2]);21 list.add(python);22 }23 }24 in.close();25 //脚本运行结果,0成功/1失败

26 int status =proc.waitFor();27 System.out.println("Process exitValue: " +status);28 } catch(IOException e) {29 e.printStackTrace();30 return null;31 } catch(InterruptedException e){32 e.printStackTrace();33 return null;34 }catch(ArrayIndexOutOfBoundsException e){35 e.printStackTrace();36 return null;37 }38 }