在Java中调用Python脚本或方法,你可以使用以下几种方法:
1. 使用`ProcessBuilder`类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
ProcessBuilder pb = new ProcessBuilder("python", "path/to/your/python/script.py");
Process process = pb.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("Exit code: " + exitCode);
}
}
2. 使用Jython库:
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class Main {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("path/to/your/python/script.py");
PyObject pyObject = interpreter.get("MyClass");
PyObject result = pyObject.__call__();
System.out.println(result);
}
}
3. 使用`Runtime.getRuntime().exec`方法:
try {
String exe = "python解释器所处的绝对路径";
String py = "python代码文件绝对地址";
Process process = Runtime.getRuntime().exec(exe + " " + py);
InputStreamReader isr = new InputStreamReader(process.getInputStream(), "gb2312");
LineNumberReader input = new LineNumberReader(isr);
String result = input.readLine();
System.out.println(result);
input.close();
isr.close();
process.waitFor();
} catch (InterruptedException | IOException e) {
System.out.println("调用python脚本并读取结果时出错: " + e.getMessage());
}
请确保Python解释器已正确安装,并且你的Python脚本路径是正确的。如果需要调用Python类的方法,你可能需要使用Jython库,因为它允许Java代码直接调用Python代码。