// Java调用Python程序的示例代码
import java.io.*;
public class JavaCallPython {
public static void main(String[] args) {
// 定义要执行的Python脚本路径
String pythonScriptPath = "script.py";
// 定义传递给Python脚本的参数
String[] command = {"python", pythonScriptPath, "arg1", "arg2"};
try {
// 创建ProcessBuilder对象来启动Python进程
ProcessBuilder pb = new ProcessBuilder(command);
// 启动进程
Process process = pb.start();
// 获取Python脚本的标准输出和标准错误流
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// 读取Python脚本的标准输出
System.out.println("Here is the standard output of the command:\n");
String s;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// 读取Python脚本的标准错误
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
// 等待Python脚本执行完毕
int exitVal = process.waitFor();
System.out.println("Exit value: " + exitVal);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
java.io.*
用于处理输入输出流。String pythonScriptPath
指定了要执行的Python脚本文件路径。String[] command
数组包含了启动Python解释器和传递给Python脚本的参数。ProcessBuilder
创建进程,并通过pb.start()
启动它。BufferedReader
读取Python脚本的标准输出和标准错误流,并打印到控制台。process.waitFor()
等待Python脚本执行完毕,并获取退出状态码。以上代码展示了如何在Java中调用Python脚本,并处理其输出和错误信息。
下一篇:java set 转 list
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站