package com.baidu.udf;
import java.io.*;
/**
* 在Java中执行Python脚本
*/
public class PythonExecutor {
/**
* 执行Python脚本并获取输出
*/
public static String executeScript(String pythonCode) throws Exception {
// 创建临时Python文件
File tempFile = File.createTempFile("temp_script_", ".py");
tempFile.deleteOnExit();
// 写入Python代码
try (FileWriter writer = new FileWriter(tempFile)) {
writer.write(pythonCode);
}
// 执行Python脚本
return executePython(tempFile.getAbsolutePath());
}
/**
* 执行Python脚本文件
*/
public static String executePython(String scriptPath) throws Exception {
ProcessBuilder pb = new ProcessBuilder("python3", scriptPath);
pb.redirectErrorStream(true);
Process process = pb.start();
// 读取输出
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
process.waitFor();
return output.toString().trim();
}
public static void main(String[] args) throws Exception {
// 方法1: 直接执行Python代码
String pythonCode = "print('Hello from Python!')";
String result = executeScript(pythonCode);
System.out.println("Result: " + result);
// 方法2: 执行已有的Python脚本
// String result = executePython("/path/to/your/script.py");
// System.out.println(result);
}
}