在Java中調用Python接口可以通過以下幾種方法:
ProcessBuilder pb = new ProcessBuilder("python", "python_script.py");
Process p = pb.start();
import org.python.util.PythonInterpreter;
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('Hello from Python!')");
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String[] command = {"python", "python_script.py"};
Process process = Runtime.getRuntime().exec(command);
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("Exited with code " + exitCode);
}
}
這些方法可以讓你在Java中調用Python接口,并實現Java與Python的交互。