java调用python的接口
时间: 2023-09-20 22:06:01 浏览: 122
Java调用Python的接口可以使用Java的Runtime类或ProcessBuilder类来执行Python脚本。这两种方法都可以在Java中启动一个新的进程,并调用Python解释器来执行指定的Python脚本。
以下是使用Runtime类的示例代码:
```java
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("python /path/to/python/script.py");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}
```
使用ProcessBuilder类的示例代码:
```java
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("python", "/path/to/python/script.py");
Process pr = pb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
}
```
这些代码片段会启动Python解释器,并执行指定的Python脚本。执行结果将会输出到Java控制台。
阅读全文