要通过Java程序调用Python脚本,可以使用Runtime.getRuntime().exec()
方法或者ProcessBuilder
类。以下是两种方法的示例代码:
import java.io.*;
public class CallPythonScript {
public static void main(String[] args) {
try {
String pythonScriptPath = "/path/to/your/pythonScript.py";
String[] command = new String[]{"python", pythonScriptPath};
// 执行Python脚本
Process process = Runtime.getRuntime().exec(command);
// 读取脚本的输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待脚本执行完成
int exitCode = process.waitFor();
System.out.println("Python脚本退出状态码: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
确保将/path/to/your/pythonScript.py
替换为Python脚本的实际路径,并且你的环境变量中已经配置了Python的路径,这样才能通过python
命令来执行脚本。
import java.io.*;
import java.util.*;
public class CallPythonScript {
public static void main(String[] args) {
try {
String pythonScriptPath = "/path/to/your/pythonScript.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);
}
// 等待进程完成
int exitCode = process.waitFor();
System.out.println("Python脚本退出状态码: " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
同样,确保将/path/to/your/pythonScript.py
替换为Python脚本的实际路径。
以上两种方法,如果你的Python脚本需要接收命令行参数,可以简单地将参数添加到command
数组或ProcessBuilder
的参数列表中。例如:
String[] command = new String[]{"python", pythonScriptPath, "arg1", "arg2", "arg3"};
或者
ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath, "arg1", "arg2", "arg3");