概述
术业有专攻,Java适合做企业级平台应用,或者云计算,大数据相关平台等。Python则擅长于小工具应用。让专业的人做专业的事情,让专业的工具做专业的领域;物尽其用,人尽其才。
在Javaer软件开发生涯里,难免会遇到一些让Java开发语言捉襟见肘的场景,比如写爬虫脚本,或做科学计算等。
此时我们或许会想到Python脚本语言,那如何让Java和Python两者取其优呢?即,如何结合两者的优势呢?
Javaer会想到调用Python脚本,只需要执行环境里安装有Python即可。
经过调研,Java应用调用Python有如下两种方式。
Runtime
根据有无入参
无入参
@Slf4j
public static void testPythonWithRuntime() {
Process proc;
try {
proc = Runtime.getRuntime().exec("python D:\\demo1.py");
// 用输入输出流来截取结果
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException | InterruptedException e) {
log.error("testPythonWithRuntime failed: ", e);
}
}
有入参
如果需要传入参数,则需要将参数转换为String:
public static void testPythonWithRuntime1() {
int a = 18;
int b = 23;
try {
String[] args = new String[]{"python", "D:\\demo.py", String.valueOf(a), String.valueOf(b)};
Process proc = Runtime.getRuntime().exec(args);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException | InterruptedException e) {
log.error("testPythonWithRuntime failed: ", e);
}
}
优缺点
优点:显而易见,无需额外引入任何依赖。
劣势:需将参数转换为String,如果不能转化呢?
Jython
官网:https://www.jython.org/
Jpython简介:
一种完整的语言,而不仅仅是一个Java翻译器或Python编译器,它是一个Python语言在Java中的完全实现。Jython也有很多从CPython中继承的模块库。最有趣的事情是Jython不像CPython或其他任何高级语言,它提供了对其实现语言的一切存取。所以Jython不仅给你提供了Python的库,同时也提供了所有的Java类。这使其有一个巨大的资源库。
Jython当前最新版为2.7.3,一个依赖包就有45M,可谓相当大的。
引入依赖:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.3</version>
</dependency>
可以直接在Java代码中写python语句,支持Python 2 和 3的语法:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a=[5,2,3,9,4,0];");
interpreter.exec("print(sorted(a));");// python 3.x 语法
interpreter.exec("print sorted(a);");// python 2.x 语法
调用脚本
当然也支持执行脚本,示例代码:
@Slf4j
public static void testPythonWithJython() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("E:\\saveAsPic.py");
// 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
PyFunction pyFunction = interpreter.get("add", PyFunction.class);
// 调用有参函数,必须先将参数转化为对应的Python类型
PyObject pyobj = pyFunction.__call__();
log.info("anwser is: " + pyobj);
}
优缺点
优点:
劣势:需安装执行环境,需引入依赖。
进阶
参考
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142220.html