如何在Java中調(diào)用python文件執(zhí)行詳解
一、Java內(nèi)置Jpython庫(kù)(不推薦)
1.1 下載與使用
可以在官網(wǎng)下載jar包,官網(wǎng):http://ftp.cuhk.edu.hk/pub/packages/apache.org/
或者使用maven進(jìn)行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內(nèi)置的庫(kù)有限,而且很多庫(kù)不存在,會(huì)報(bào)no model的錯(cuò)誤,所以這里不推薦大家使用。
二、使用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文件存的絕對(duì)路徑 String path = "D:\\NLP.py"; // 傳入的參數(shù) String args = "今天過(guò)的很開(kāi)心"; try { proc = Runtime.getRuntime().exec(exe + ' ' + path + ' ' + args);// 執(zhí)?py?件 // ?輸?輸出流來(lái)截取結(jié)果 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中,會(huì)使用自己包中的其他python文件中的函數(shù),那么很有可能無(wú)法導(dǎo)入,但是不會(huì)報(bào)錯(cuò),只會(huì)返回一個(gè)null。
三、利用cmd調(diào)用python文件
3.1 使用
這個(gè)方法就類(lèi)似于在cmd中,使用 python file.py 參數(shù) 直接執(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文件存的絕對(duì)路徑 String path = "D:\\NLP.py"; // 傳入的參數(shù) String args = "今天過(guò)的很開(kāi)心"; try { proc = Runtime.getRuntime().exec(exe + " \c start " + path + ' ' + args);// 執(zhí)?py?件 proc.waitFor(); } catch (Exception e) { e.printStackTrace(); } } }
3.2 優(yōu)化
考慮到python是否正在進(jìn)行,或者是否調(diào)用python,可設(shè)置一些函數(shù)用于輔助:
這里沒(méi)有使用參數(shù),直接對(duì)文件進(jìn)行讀取,傳參可能會(huì)存在編碼問(wèn)題,Java默認(rèn)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("調(diào)用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(); } } // 輸入文件,參數(shù)為輸出字符串 public static void inputToFile(String input) throws Exception{ // 寫(xiě)入前清空 clearInfoForFile("F:\\python_project\\input.txt"); //創(chuàng)建寫(xiě)入流 FileWriter writer=new FileWriter("F:\\python_project\\input.txt"); // 寫(xiě)入 writer.write(input + "\r\n"); //關(guā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; } // 殺掉一個(gè)進(jìn)程 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("殺死進(jìn)程 " + name); } string_Temp = in.readLine(); } } catch (Exception e) { e.printStackTrace(); } } // 判斷進(jìn)程是否存在 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; } }
總結(jié)
到此這篇關(guān)于如何在Java中調(diào)用python文件執(zhí)行的文章就介紹到這了,更多相關(guān)Java調(diào)用python文件執(zhí)行內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java8接口中引入default關(guān)鍵字的本質(zhì)原因詳析
Default方法是在java8中引入的關(guān)鍵字,也可稱(chēng)為Virtual extension methods—虛擬擴(kuò)展方法,這篇文章主要給大家介紹了關(guān)于Java8接口中引入default關(guān)鍵字的本質(zhì)原因,需要的朋友可以參考下2022-01-01Spring Boot 簡(jiǎn)介(入門(mén)篇)
Spring Boot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來(lái)簡(jiǎn)化新Spring應(yīng)用的初始搭建以及開(kāi)發(fā)過(guò)程。下面通過(guò)本文給大家介紹spring boot相關(guān)知識(shí),需要的的朋友參考下吧2017-04-04Java實(shí)現(xiàn)Promise.all()的示例代碼
這篇文章主要介紹了Java實(shí)現(xiàn)Promise.all()的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08Java詳細(xì)分析sleep和wait方法有哪些區(qū)別
這篇文章主要介紹了Java中wait與sleep的講解(wait有參及無(wú)參區(qū)別),通過(guò)代碼介紹了wait()?與wait(?long?timeout?)?區(qū)別,wait(0)?與?sleep(0)區(qū)別,需要的朋友可以參考下2022-04-04SpringBoot應(yīng)用程序轉(zhuǎn)換成WAR文件詳解
其實(shí)一般使用SpringBoot使用打成jar包比較省事的,但也有很多童鞋是習(xí)慣使用WAR包的,下面這篇文章主要給大家介紹了關(guān)于SpringBoot轉(zhuǎn)換WAR的相關(guān)資料,需要的朋友可以參考下2022-11-11解決Maven本地倉(cāng)庫(kù)明明有對(duì)應(yīng)的jar包但還是報(bào)找不到的問(wèn)題
這篇文章主要介紹了解決Maven本地倉(cāng)庫(kù)明明有對(duì)應(yīng)的jar包但還是報(bào)找不到的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10JAVA WEB中Servlet和Servlet容器的區(qū)別
這篇文章主要介紹了JAVA WEB中Servlet和Servlet容器的區(qū)別,文中示例代碼非常詳細(xì),供大家參考和學(xué)習(xí),感興趣的朋友可以了解下2020-06-06java基于JDBC連接Oracle 11g Release2實(shí)例分析
這篇文章主要介紹了java基于JDBC連接Oracle 11g Release2的方法,實(shí)例分析了JDBC連接Oracle 11g Release2容易出現(xiàn)的異常與解決方法,需要的朋友可以參考下2015-06-06