Java调用python文件执行

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java调用python文件执行

小子挺不错   2022-06-03 我要评论

一、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>

执行代码样例:

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

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们