如何用java调用python程序
时间: 2024-05-11 22:18:54 浏览: 14
可以使用Java的ProcessBuilder类来调用Python程序。以下是一个简单的示例代码:
```
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PythonCaller {
public static void main(String[] args) throws IOException {
String pythonScriptPath = "/path/to/python/script.py";
// 构建进程
ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
// 读取输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待进程结束
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
其中,pythonScriptPath指向Python脚本的路径。注意,要在Python程序中使用print语句输出结果,才能在Java中读取到。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)