java怎么调用python接口
在Java中调用Python接口可以通过以下几种方法:
- 使用Java的ProcessBuilder类来执行Python脚本。通过创建一个ProcessBuilder对象并设置要执行的Python脚本文件路径,然后调用start()方法执行该脚本。
ProcessBuilder pb = new ProcessBuilder("python", "python_script.py");
Process p = pb.start();
- 使用Jython库,Jython是一个在Java平台上实现的Python解释器,可以直接在Java代码中调用Python代码。
import org.python.util.PythonInterpreter;
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("print('Hello from Python!')");
- 使用Python的标准库subprocess在Java中调用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的交互。