在Java中调用Python脚本并传递参数可以通过以下几种方式实现:
使用`Runtime.exec`方法
```java
try {
String[] arguments = new String[] {
"python",
"path_to_your_python_script.py",
"arg1",
"arg2",
// ...
"argN"
};
Process process = Runtime.getRuntime().exec(arguments);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
使用`ProcessBuilder`类
```java
try {
ProcessBuilder processBuilder = new ProcessBuilder("python", "path_to_your_python_script.py", "arg1", "arg2", /* ... */);
Process process = processBuilder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
使用`jython`库(不推荐,因为可能不支持所有第三方库):
```java
import org.python.util.PythonInterpreter;
public class JavaCallPython {
public static void main(String[] args) {
try (PythonInterpreter interpreter = new PythonInterpreter()) {
interpreter.execfile("path_to_your_python_script.py");
interpreter.set("arg1", "value1");
interpreter.set("arg2", "value2");
// ...
interpreter.execfile("path_to_your_python_script.py");
}
}
}
使用`ProcessBuilder`传递参数(适用于Windows和Linux系统):
```java
try {
ProcessBuilder processBuilder = new ProcessBuilder("python", "path_to_your_python_script.py", "arg1", "arg2", /* ... */);
Process process = processBuilder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}