在Java中调用Python的方法有多种,以下是几种常见的方式:
使用`Runtime`类执行Python脚本
try {
String command = "python path/to/python/script.py";
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
process.waitFor();
} catch (InterruptedException | IOException e) {
System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());
}
使用`ProcessBuilder`类执行Python脚本
ProcessBuilder pb = new ProcessBuilder("python", "path/to/python/script.py");
Process process = pb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
process.waitFor();
在Java类中直接执行Python语句
import org.python.util.PythonInterpreter;
public class JavaRunPython {
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a=5+2+3+9+4+0");
interpreter.exec("print(sorted(a))");
}
}
调用Python脚本中的函数
import org.python.core.PyObject;
import org.python.core.PyFunction;
import org.python.util.PythonInterpreter;
public class FirstJavaScript {
public static void main(String args[]) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("def adder(a, b): return a + b");
PyFunction add = interpreter.get("adder");
PyObject result = add.__call__(new PyInteger(1), new PyInteger(2));
System.out.println(result);
}
}
使用第三方库如Jython或PyJNIus
Jython:需要下载Jython的jar包,并在项目中引用。
PyJNIus:允许Python代码访问Java类,适用于Android开发等场景。
选择合适的方法取决于你的具体需求,例如是否需要与Python代码进行交互,或者是否需要在多个平台上运行代码。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/124243.html