Java【代码 07】Java执行Python代码的3类5种情况测试(Java源码+Python源码举例)

1.why

python拥有的某些库要比Java强大,也拥有一些比Java更擅长的领域,python可以搭建后端让Java调用接口,但某些时候我们用到的python代码可能并不多也许只有一个算法,此时就需要以下方法了。

2.核心依赖

毫无疑问【自然是python的Java执行器了】

xml 复制代码
<dependency>
	<groupId>org.python</groupId>
	<artifactId>jython-standalone</artifactId>
	<version>2.7.0</version>
</dependency>

3.使用

3.1类型一【直接执行python代码】

java 复制代码
public class ExecPythonCode {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("a=[5,2,3,9,4,0];");
        // 此处python语句是3.x版本的语法
        interpreter.exec("print(sorted(a));"); 
        // 此处是python语句是2.x版本的语法
        interpreter.exec("print sorted(a);"); 
        interpreter.close();
    }
}

3.2类型二【执行python文件后获取返回结果】

  1. 无参数的python文件执行
java 复制代码
public class ExecPythonFile {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime()
                    .exec("python D:\\PythonFile.py");
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  1. 带参数的python文件执行
python 复制代码
public class ExecPythonFileWithArgs {
    public static void main(String[] args) {
        int a = 18, b = 19;
        args = new String[] { "python","D:\\PythonFileWithArgs.py",
        String.valueOf(a), String.valueOf(b) };
        try {
            Process process = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  1. 【Windows环境】使用bat脚本执行python文件【我猜想也是有Linux环境的执行方法的】
java 复制代码
public class ExecPythonBat {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("cmd /c D:\\RunPythonFile.bat");
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3.3类型三【读取python文件内的函数进行执行】

java 复制代码
public class ExecPythonFileCode {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\\PythonFile.py");
        PyFunction function = interpreter.get("add", PyFunction.class);
        int a = 3, b = 12;
        PyObject pyObject = function.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println("The result is : " + pyObject);
        interpreter.close();
    }
}

4.python文件和执行脚本

文件一:PythonFile.py

python 复制代码
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
def add(a,b):
    return a+b;

文件二:PythonFileWithArgs.py

python 复制代码
import sys
 
def func(a,b):
    return (a+b)
 
if __name__ == '__main__':
    a = []
    for i in range(1, len(sys.argv)):
        a.append((int(sys.argv[i])))
    print(func(a[0],a[1]))

文件三:RunPythonFile.bat

powershell 复制代码
@echo off
cmd /k python E:\Anaconda3_Python\PythonFile.py
相关推荐
David爱编程5 分钟前
final 修饰变量、方法、类的语义全解
java·后端
椒哥7 分钟前
Open feign动态切流实现
java·后端·spring cloud
佳佳_15 分钟前
Lock4j 在多租户缓存插件中不起作用
spring boot·后端
RainbowSea16 分钟前
购买服务器 + 项目部署上线详细步骤说明
java·服务器·后端
Jacob023417 分钟前
很多数据分析师写对了 SQL,却忽略了这件更重要的事
后端·sql·数据分析
超浪的晨1 小时前
Java 单元测试详解:从入门到实战,彻底掌握 JUnit 5 + Mockito + Spring Boot 测试技巧
java·开发语言·后端·学习·单元测试·个人开发
艺杯羹4 小时前
MyBatis 之缓存机制核心解析
java·后端·spring·mybatis
Brookty4 小时前
【Java学习】匿名内部类的向外访问机制
java·开发语言·后端·学习
程序员爱钓鱼4 小时前
Go语言实战案例-快速排序实现
后端·google·go
程序员爱钓鱼4 小时前
Go语言实战案例-链表的实现与遍历
后端·google·go