栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Java:在Java中调用python文件执行

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java:在Java中调用python文件执行

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

一、Java内置Jpython库(不推荐) 1.1 下载与使用

可以在官网下载jar包,官网

或者使用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(String input) throws Exception{
        // 写入前清空
        clearInfoForFile("F:\python_project\input.txt");

        //创建写入流
        FileWriter writer=new FileWriter("F:\python_project\input.txt");

        // 写入
        writer.write(input + "rn");

        //关闭资源
        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;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/858524.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号