Java调用python代码的五种方式

你还在纠结怎么样在Java中调用python吗?我们在实际工程项目问题中,经常会碰到不同语言代码之间互调的问题,比如此处的Java调用python(常见Java调用python写的处理模型来完成数据处理等)。

目录

    • 1. 无参数调用
    • 2. 带参数调用
      • 2.1. 单行返回值
      • 2.2. 多行返回值
    • 3. Java中直接执行python语句
    • 4. 通过PythonInterpreter直接调用python脚本
    • 5. Java通过调用bat文件间接调用python

让我们来看看具体怎么操作吧!

1. 无参数调用

说明: Java调用不带参数的python代码执行
样例代码如下:

try {
	String exe = "python解释器所处的绝对路径";
	String py = "python代码文件绝对地址";
	Process process = Runtime.getRuntime().exec(exe + " " + py);
	//获取结果的同时设置输入流编码格式"gb2312"
	InputStreamReader isr = new InputStreamReader(process.getInputStream(),"gb2312");
	LineNumberReader input = new LineNumberReader(isr);
	String result = "";
	result = input.readLine();
	System.out.println(result);
	input.close();
	isr.close();
	process.waitFor();
} catch (InterruptedException | IOException e) {
	System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());
}

2. 带参数调用

带参调用可以将命令和参数写入String数组,然后作为执行参数执行。
基本语句如下:

String exe = "python解释器所处的绝对路径";
String py = "python代码文件绝对地址";
String pram = "单个传递参数,若参数为基本类型,转化为String;若为数组等类型,也是将其转换为String型";
String [] args = new String[] {exe, py, pram...};
Process process = Runtime.getRuntime().exec(args);

2.1. 单行返回值

说明: Java调用不带参数的python代码执行
样例代码如下:

try {
	String exe = "python解释器所处的绝对路径";
	String py = "python代码文件绝对地址";
	String pram = "单个传递参数,若参数为基本类型,转化为String;若为数组等类型,也是将其转换为String型";
	String [] args = new String[] {exe, py, pram...};
	Process process = Runtime.getRuntime().exec(args);
	//获取结果的同时设置输入流编码格式"gb2312"
	InputStreamReader isr = new InputStreamReader(process.getInputStream(),"gb2312");
	LineNumberReader input = new LineNumberReader(isr);
	String result = "";
	result = input.readLine();
	System.out.println(result);
	input.close();
	isr.close();
	process.waitFor();
} catch (InterruptedException | IOException e) {
	System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());
}

2.2. 多行返回值

说明: Java调用不带参数的python代码执行
样例代码如下:

try {
	String exe = "python解释器所处的绝对路径";
	String py = "python代码文件绝对地址";
	String pram = "单个传递参数,若参数为基本类型,转化为String;若为数组等类型,也是将其转换为String型";
	String [] args = new String[] {exe, py, pram...};
	ProcessBuilder builder = new ProcessBuilder(args);
    Process process = builder.start();
    BufferedReader success = new BufferedReader(new InputStreamReader(process.getInputStream(), "GB2312"));//获取字符输入流对象
    BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GB2312"));//获取错误信息的字符输入流对象
    String line = null;
    List<String> success_result = new ArrayList<>();
    List<String> error_result = new ArrayList<>();
    //记录输出结果
    while ((line = success.readLine()) != null) {
        success_result.add(line);
    }
    //记录错误信息
    while ((line = error.readLine()) != null) {
        error_result.add(line);
    }
    success.close();
    error.close();
    process.waitFor();

    System.out.println(success_result);
    System.out.println(error_result);
} catch (InterruptedException | IOException e) {
	System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());
}

3. Java中直接执行python语句

注意: 此方法在使用之前需要导入依赖环境,如在maven中导入如下依赖:

<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <!--python版本在这里指定(2.x或3.x等)-->
    <version>3.7.0</version>	
</dependency>

调用语句如下:

import org.python.util.PythonInterpreter
public class JavaRunPython {
    public static void main(String[] args) {
    	//调用python的解释器
        PythonInterpreter interpreter = new PythonInterpreter();
        //执行Python语句
        interpreter.exec("str = 'hello world!'; ");
        interpreter.exec("print(str);");
    }
}

4. 通过PythonInterpreter直接调用python脚本

注意: 此方法也需要导入1.3中依赖
Java调用代码如下:

import org.python.util.PythonInterpreter;
public class JavaPythonFile {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        //我在这里使用相对路径,注意区分
        interpreter.execfile("D:/code/test.py");
    }
}

test.py举例如下:

a = 1
b = 2
print(a +b)

5. Java通过调用bat文件间接调用python

hello.bat测试代码如下:

echo hello world!
D:
cd D:\code\
start python test.py
pause

Java调用代码如下:

try {
	StringBuilder sb = new StringBuilder();
	String batPath = "D:/hello.bat";
	Process process = Runtime.getRuntime().exec(batPath);
	InputStream in = process.getInputStream();
	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
	String line;
	while ((line = bufferedReader.readLine()) != null) {
		sb.append(line + "\n");
	}
	in.close();
	try {
		process.waitFor();
	} catch (InterruptedException e) {
		System.out.println(e);
	}
} catch (IOException e) {
	System.out.println(e);
}

如果大家有好的方法,欢迎交流评论!

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年8月23日
下一篇 2023年8月23日

相关推荐