1. 程式人生 > 實用技巧 >Java呼叫Python指令碼(Window,Linux)

Java呼叫Python指令碼(Window,Linux)

1)Window安裝和環境配置

網上教程實在太多了,就不再敘述,自行百度

推薦教程:https://www.cnblogs.com/vilee/p/10029675.html

2)Linux安裝和環境配置

推薦教程:https://blog.csdn.net/key_world/article/details/110214288

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-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

ps:這裡需要註明的是,網上許多教程讓直接把python刪除掉,結果連yum命令也使用不了了,如下

1、刪除現有Python
[root@test ~]# rpm -qa|grep python|xargs rpm -ev --allmatches --nodeps ##強制刪除已安裝程式及其關聯
[root@test ~]# whereis python |xargs rm -frv ##刪除所有殘餘檔案 ##xargs,允許你對輸出執行其他某些命令
[root@test 
~]# whereis python ##驗證刪除,返回無結果 2、刪除現有的yum [root@test ~]# rpm -qa|grep yum|xargs rpm -ev --allmatches --nodeps [root@test ~]# whereis yum |xargs rm -frv

解決:解除安裝centos自帶python導致yum命令失效的方法

https://blog.csdn.net/loveideality/article/details/81215440

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 List<Python> pythonUtils(String keyWord){
 2     Process proc;
 3     String line = null;
 4     ArrayList<Python> list = new ArrayList();
 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 = new Python();
12         while ((line = in.readLine()) != null) {
13             String[] string1 = line.split("==");
14             for (int i = 0; i <string1.length ; i++) {
15                 String s = string1[i];
16                 //對獲取指令碼輸出的字串進行欄位分割取值
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 null31     } catch (InterruptedException e){
32         e.printStackTrace();
33         return null34     }catch (ArrayIndexOutOfBoundsException e){
35         e.printStackTrace();
36         return null37     }
38 }