如何在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è)方法就類似于在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{
// 寫入前清空
clearInfoForFile("F:\\python_project\\input.txt");
//創(chuàng)建寫入流
FileWriter writer=new FileWriter("F:\\python_project\\input.txt");
// 寫入
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)文章
使用@TransactionalEventListener監(jiān)聽(tīng)事務(wù)教程
這篇文章主要介紹了使用@TransactionalEventListener監(jiān)聽(tīng)事務(wù)教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
idea打開(kāi)項(xiàng)目沒(méi)有項(xiàng)目目錄問(wèn)題及解決
這篇文章主要介紹了idea打開(kāi)項(xiàng)目沒(méi)有項(xiàng)目目錄問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
記一次Feign中實(shí)現(xiàn)傳實(shí)體Bean的問(wèn)題
這篇文章主要介紹了記一次Feign中如何傳實(shí)體Bean的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
解決idea中svn提交時(shí)performing vcs refresh時(shí)間很長(zhǎng)的問(wèn)題
這篇文章主要介紹了解決idea中svn提交時(shí)performing vcs refresh時(shí)間很長(zhǎng)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
springboot?自定義啟動(dòng)器的實(shí)現(xiàn)
本文主要介紹了springboot?自定義啟動(dòng)器的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Java?+?Selenium?+?OpenCV解決自動(dòng)化測(cè)試中的滑塊驗(yàn)證問(wèn)題
OpenCV是一個(gè)基于Apache2.0許可(開(kāi)源)發(fā)行的跨平臺(tái)計(jì)算機(jī)視覺(jué)和機(jī)器學(xué)習(xí)軟件庫(kù),可以運(yùn)行在Linux、Windows、Android和Mac?OS操作系統(tǒng)上,這篇文章主要介紹了Java?+?Selenium?+?OpenCV解決自動(dòng)化測(cè)試中的滑塊驗(yàn)證,需要的朋友可以參考下2022-07-07
java必學(xué)必會(huì)之方法的重載(overload)
java必學(xué)必會(huì)之方法的重載,介紹了方法的重載、構(gòu)造方法的重載,想要學(xué)好java方法的重載的朋友一定要好好閱讀這篇文章2015-12-12
idea中springboot整合mybatis找不到mapper接口的原因分析
這篇文章主要介紹了idea中springboot整合mybatis找不到mapper接口的原因分析及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01

