本文目录导读:

- 使用Runtime.exec()直接执行Python脚本
- 传递参数给Python脚本
- 使用ProcessBuilder的完整示例
- 使用Jython(Java Python集成)
- 使用Apache Commons Exec
- 实际应用案例:数据分析和结果返回
- 注意事项
我来为您介绍几种Java调用Python的经典案例:
使用Runtime.exec()直接执行Python脚本
基础示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class JavaCallPython {
public static void main(String[] args) {
try {
// 调用Python脚本
Process process = Runtime.getRuntime().exec("python3 /path/to/script.py");
// 读取Python输出
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待进程结束
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python脚本 (script.py)
# 简单的Python脚本
import sys
def main():
print("Hello from Python!")
print("Python version:", sys.version)
# 进行一些计算
result = sum(range(100))
print(f"Sum of 0-99: {result}")
if __name__ == "__main__":
main()
传递参数给Python脚本
Java代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class JavaCallPythonWithArgs {
public static void main(String[] args) {
try {
// 准备参数
String pythonScript = "/path/to/script_with_args.py";
String arg1 = "Hello";
int arg2 = 42;
// 构建命令
ProcessBuilder pb = new ProcessBuilder(
"python3", pythonScript, arg1, String.valueOf(arg2)
);
Process process = pb.start();
// 读取输出
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 读取错误输出
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
while ((line = errorReader.readLine()) != null) {
System.err.println("Error: " + line);
}
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python脚本 (script_with_args.py)
import sys
def main():
if len(sys.argv) != 3:
print("Usage: script.py <arg1> <arg2>")
sys.exit(1)
arg1 = sys.argv[1]
arg2 = int(sys.argv[2])
print(f"Arguments received: {arg1}, {arg2}")
print(f"Processing...")
result = arg2 * 2
print(f"Result: {result}")
if __name__ == "__main__":
main()
使用ProcessBuilder的完整示例
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class PythonCaller {
public static String executePython(String scriptPath, List<String> args) {
StringBuilder output = new StringBuilder();
try {
List<String> command = new ArrayList<>();
command.add("python3");
command.add(scriptPath);
if (args != null) {
command.addAll(args);
}
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true); // 合并错误输出
Process process = pb.start();
// 读取输出
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("Python script failed with exit code: " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return output.toString();
}
public static void main(String[] args) {
// 示例调用
String scriptPath = "/path/to/your_script.py";
List<String> scriptArgs = new ArrayList<>();
scriptArgs.add("data1");
scriptArgs.add("data2");
String result = executePython(scriptPath, scriptArgs);
System.out.println("Python output:");
System.out.println(result);
}
}
使用Jython(Java Python集成)
Jython允许在Java中直接运行Python代码。
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class JythonExample {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
// 执行Python代码
interpreter.exec("print('Hello from Jython!')");
interpreter.exec("import sys");
interpreter.exec("print('Python version:', sys.version)");
// 设置变量
interpreter.set("name", "World");
interpreter.exec("print('Hello, ' + name + '!')");
// 执行Python脚本文件
interpreter.execfile("/path/to/your_script.py");
// 获取Python变量
interpreter.exec("result = 42 * 2");
PyObject result = interpreter.get("result");
System.out.println("Result from Python: " + result);
interpreter.close();
}
}
使用Apache Commons Exec
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import java.io.ByteArrayOutputStream;
public class CommonsExecExample {
public static void main(String[] args) {
try {
String line = "python3 /path/to/script.py arg1 arg2";
CommandLine cmdLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
executor.setStreamHandler(streamHandler);
int exitValue = executor.execute(cmdLine);
String output = outputStream.toString();
String error = errorStream.toString();
System.out.println("Output: " + output);
System.out.println("Error: " + error);
System.out.println("Exit value: " + exitValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}
实际应用案例:数据分析和结果返回
Java代码
import java.io.*;
import java.nio.charset.StandardCharsets;
public class DataAnalysisCaller {
public static String analyzeData(String inputData) {
try {
// 创建临时文件存储输入数据
File inputFile = File.createTempFile("input_data_", ".json");
inputFile.deleteOnExit();
File outputFile = File.createTempFile("output_data_", ".json");
outputFile.deleteOnExit();
// 写入输入数据
try (FileWriter writer = new FileWriter(inputFile)) {
writer.write(inputData);
}
// 执行Python分析脚本
ProcessBuilder pb = new ProcessBuilder(
"python3",
"/path/to/analysis_script.py",
inputFile.getAbsolutePath(),
outputFile.getAbsolutePath()
);
Process process = pb.start();
// 读取Python脚本的错误输出(如果有)
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()));
String errorLine;
while ((errorLine = errorReader.readLine()) != null) {
System.err.println("Python Error: " + errorLine);
}
int exitCode = process.waitFor();
if (exitCode == 0) {
// 读取输出结果
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new FileReader(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
return result.toString();
} else {
throw new RuntimeException("Analysis failed");
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String inputData = "{\"values\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}";
String result = analyzeData(inputData);
System.out.println("Analysis result: " + result);
}
}
Python脚本 (analysis_script.py)
import json
import sys
import statistics
def analyze_data(input_file, output_file):
# 读取输入数据
with open(input_file, 'r') as f:
data = json.load(f)
values = data.get('values', [])
if not values:
result = {"error": "No data provided"}
else:
# 执行分析
result = {
"count": len(values),
"mean": statistics.mean(values),
"median": statistics.median(values),
"standard_deviation": statistics.stdev(values) if len(values) > 1 else 0,
"min": min(values),
"max": max(values),
"sum": sum(values)
}
# 写入输出结果
with open(output_file, 'w') as f:
json.dump(result, f, indent=2)
print("Analysis completed successfully")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: script.py <input_file> <output_file>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
analyze_data(input_file, output_file)
注意事项
- 性能考虑:每次调用都会启动新的Python进程,对于频繁调用可能影响性能
- 安全性:避免注入攻击,参数需要适当转义
- 错误处理:始终处理Python脚本的异常输出和退出码
- 路径问题:确保Python脚本路径和Python解释器路径正确
- 依赖管理:Python脚本需要的库必须在系统中安装
这些示例涵盖了从简单到复杂的Java调用Python的方法,您可以根据具体需求选择合适的方案。