如何在Java中調用python文件執(zhí)行詳解
一、Java內置Jpython庫(不推薦)
1.1 下載與使用
可以在官網下載jar包,官網:http://ftp.cuhk.edu.hk/pub/packages/apache.org/
或者使用maven進行jar包下載
<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.0</version> </dependency>
執(zhí)行代碼樣例:
PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("a=[5,2,3,9,4,0]; "); interpreter.exec("print(sorted(a));");
1.2 缺陷
Jython內置的庫有限,而且很多庫不存在,會報no model的錯誤,所以這里不推薦大家使用。
二、使用Runtime.getRuntime()執(zhí)行腳本?件
2.1 使用
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; publicclass Demo1 { publicstaticvoid main(String[] args) { Process proc; // 編譯器是python String exe = "python"; // py文件存的絕對路徑 String path = "D:\\NLP.py"; // 傳入的參數 String args = "今天過的很開心"; try { proc = Runtime.getRuntime().exec(exe + ' ' + path + ' ' + args);// 執(zhí)?py?件 // ?輸?輸出流來截取結果 BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); proc.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
2.2 缺陷
如果在你的python中,會使用自己包中的其他python文件中的函數,那么很有可能無法導入,但是不會報錯,只會返回一個null。
三、利用cmd調用python文件
3.1 使用
這個方法就類似于在cmd中,使用 python file.py 參數 直接執(zhí)行python文件一樣
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; publicclass Demo1 { publicstaticvoid main(String[] args) { Process proc; // 編譯器是python String exe = "cmd.exe"; // py文件存的絕對路徑 String path = "D:\\NLP.py"; // 傳入的參數 String args = "今天過的很開心"; try { proc = Runtime.getRuntime().exec(exe + " \c start " + path + ' ' + args);// 執(zhí)?py?件 proc.waitFor(); } catch (Exception e) { e.printStackTrace(); } } }
3.2 優(yōu)化
考慮到python是否正在進行,或者是否調用python,可設置一些函數用于輔助:
這里沒有使用參數,直接對文件進行讀取,傳參可能會存在編碼問題,Java默認UTF-8,cmd是GBK
package com.Lee.utils; import java.io.*; public class NLPUtils { // NLP處理 public static String NLP(String data) throws Exception{ try { inputToFile(data); } catch (Exception e){ e.printStackTrace(); } System.out.println("調用python程序"); Process pcs = null; String py = "python.exe"; try { if(processIsRun(py)) killProcess(py); System.out.println("start"); pcs = Runtime.getRuntime().exec("cmd.exe /c start F://python_project//NLP.bat"); pcs.waitFor(); if(processIsRun(py)){ System.out.println("正在執(zhí)行"); Thread.currentThread().sleep(30000); } System.out.println("end"); } catch (Exception e){ e.printStackTrace(); } String result = ""; try { System.out.println("out:" + outputFromFile()); result = outputFromFile(); } catch (Exception e){ e.printStackTrace(); } return result; } // 清空文件 public static void clearInfoForFile(String fileName) { File file =new File(fileName); try { if(!file.exists()) { file.createNewFile(); } FileWriter fileWriter =new FileWriter(file); fileWriter.write(""); fileWriter.flush(); fileWriter.close(); } catch (Exception e) { e.printStackTrace(); } } // 輸入文件,參數為輸出字符串 public static void inputToFile(String input) throws Exception{ // 寫入前清空 clearInfoForFile("F:\\python_project\\input.txt"); //創(chuàng)建寫入流 FileWriter writer=new FileWriter("F:\\python_project\\input.txt"); // 寫入 writer.write(input + "\r\n"); //關閉資源 writer.flush(); writer.close(); } // 讀取文件 public static String outputFromFile() throws Exception{ InputStreamReader isr = new InputStreamReader(new FileInputStream("F:\\python_project\\output.txt"), "GBK"); BufferedReader read = new BufferedReader(isr); String s = null; String result = ""; while((s = read.readLine()) != null) result += s; isr.close(); read.close(); return result; } // 殺掉一個進程 public static void killProcess(String name) { try { String[] cmd = {"tasklist"}; Process proc = Runtime.getRuntime().exec(cmd); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String string_Temp = in.readLine(); while (string_Temp != null) { // System.out.println(string_Temp); if (string_Temp.indexOf(name) != -1) { Runtime.getRuntime().exec("taskkill /F /IM " + name); System.out.println("殺死進程 " + name); } string_Temp = in.readLine(); } } catch (Exception e) { e.printStackTrace(); } } // 判斷進程是否存在 public static boolean processIsRun(String ProjectName) { boolean flag = false; try { Process p = Runtime.getRuntime().exec("cmd /c tasklist "); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream os = p.getInputStream(); byte b[] = new byte[256]; while (os.read(b) > 0) baos.write(b); String s = baos.toString(); if (s.indexOf(ProjectName) >= 0) { flag = true; } else { flag = false; } } catch (Exception e) { e.printStackTrace(); } return flag; } }
總結
到此這篇關于如何在Java中調用python文件執(zhí)行的文章就介紹到這了,更多相關Java調用python文件執(zhí)行內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決Maven本地倉庫明明有對應的jar包但還是報找不到的問題
這篇文章主要介紹了解決Maven本地倉庫明明有對應的jar包但還是報找不到的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10JAVA WEB中Servlet和Servlet容器的區(qū)別
這篇文章主要介紹了JAVA WEB中Servlet和Servlet容器的區(qū)別,文中示例代碼非常詳細,供大家參考和學習,感興趣的朋友可以了解下2020-06-06java基于JDBC連接Oracle 11g Release2實例分析
這篇文章主要介紹了java基于JDBC連接Oracle 11g Release2的方法,實例分析了JDBC連接Oracle 11g Release2容易出現的異常與解決方法,需要的朋友可以參考下2015-06-06