java执行python脚本
时间: 2023-11-24 15:47:21 浏览: 76
java调用python脚本
5星 · 资源好评率100%
可以使用Java的ProcessBuilder类来执行Python脚本。具体步骤如下:
1. 创建ProcessBuilder对象,设置要执行的命令和参数,例如:
```
ProcessBuilder pb = new ProcessBuilder("python", "test.py");
```
其中,"python"是要执行的命令,"test.py"是要执行的Python脚本。
2. 设置工作目录(可选),例如:
```
pb.directory(new File("/path/to/script/directory"));
```
3. 启动进程并等待其完成,例如:
```
Process p = pb.start();
int exitCode = p.waitFor();
```
其中,p.waitFor()会阻塞当前线程,直到进程执行完成。
完整代码示例:
```
import java.io.*;
public class RunPythonScript {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("python", "test.py");
pb.directory(new File("/path/to/script/directory"));
Process p = pb.start();
int exitCode = p.waitFor();
System.out.println("Python script executed with exit code " + exitCode);
}
}
```
阅读全文