如何在Java中调用python文件执行详解(Python调用Java)

网友投稿 312 2022-08-08


如何在Java中调用python文件执行详解(Python调用Java)

目录一、java内置Jpython库(不推荐)1.1 下载与使用1.2 缺陷二、使用Runtime.getRuntime()执行脚本⽂件2.1 使用2.2 缺陷三、利用cmd调用python文件3.1 使用3.2 优化总结

一、Java内置Jpython库(不推荐)

1.1 下载与使用

可以在官网下载jar包,官网:http://ftp.cuhk.edu.hk/pub/packages/apache.org/

或者使用maven进行jar包下载

org.python

jython-standalone

2.7.0

执行代码样例:

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()执行脚本⽂件

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);// 执⾏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 参数 直接执行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);// 执⾏py⽂件

proc.waitFor();

} catch (Exception e) {

e.printStackTrace();

}

}

}

3.2 优化

考虑到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("正在执行");

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(Stringhttp:// input) throws Exception{

// 写入前清空

clearInfoForFile("F:\\python_project\\input.txt");

//创建写入流

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();

http:// 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;

}

}

总结


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java启动Tomcat的实现步骤(java代码启动tomcat)
下一篇:一文详解Java中的类加载机制(java中类加载过程)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~