java调用python脚本

如题所述

java调用python脚本是怎样的呢?下面就让我们一起来了解一下吧:
在日常生活中比较常见的java调用python脚本方法有两种,即:
1、通过Jython.jar提供的类库实现。
2、通过Runtime.getRuntime()开启进程来执行脚本文件。
不过第二种方法可能会更好一些,因为Python有时候也是需要用到第三方库的,例如requests,而Python并不支持。因此本地安装Python环境时需要再安装第三方库,然后使用Java调用即可。
参考范例:
Python代码示例:
def hello():
print(Hello,Python)
if __name__ == __main__:
hello()
Java代码示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HelloPython {
public static void main(String[] args) {
String[] arguments = new String[] {python, E://workspace/hello.py};
try {
Process process = Runtime.getRuntime().exec(arguments);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),
GBK));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
//java代码中的process.waitFor()返回值为0表示调用python脚本成功,
//返回值为1表示调用python脚本失败,这和通常意义上见到的0与1定义正好是相反的
int re = process.waitFor();
System.out.println(re);
} catch (Exception e) {
e.printStackTrace();
}
}
}
温馨提示:答案为网友推荐,仅供参考