目录
Jython
简介
Jython(原 JPython),是一个用 Java 语言写的 Python 解释器。Jython 程序可以和 Java 无缝集成。除了一些标准模块,Jython 使用 Java 的模块。
Jython 几乎拥有标准的 Python 中不依赖于 C 语言的全部模块。比如,Jython 的用户界面将使用 Swing,AWT 或者 SWT。Jython 可以被动态或静态地编译成 Java 字节码。
Jython 还包括 jythonc,一个将 Python 代码转换成 Java 代码的编译器。这意味着 Python 程序员能够将自己用 Python 代码写的类库用在 Java 程序里。
引入Jython依赖
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
Java调用Python的方式
java中直接执行python语句
public void test() throws Exception {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
interpreter.exec("print days[1];");
}
java中调用本地python脚本
public void test2() throws Exception {
PythonInterpreter interpreter = new PythonInterpreter();
// 获取文件的输入流
InputStream in = getClass().getClassLoader().getResourceAsStream("add.py");
interpreter.execfile(in);
// 使用文件绝对路径
// interpreter.execfile("D:\\add.py");
// 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
PyFunction func = (PyFunction) interpreter.get("add",
PyFunction.class);
int a = 100, b = 100;
//调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
System.out.println("anwser = " + pyobj.toString());
}
# add.py 文件内容
def add(a, b):
return a + b
java中使用Runtime.getRuntime()执行脚本文件(推荐)
- 脚本函数中没有参数
public void test3() throws Exception {
Process proc;
proc = Runtime.getRuntime().exec("python F:\\ProjectFile\\IDEA\\JPython\\src\\test\\resources\\test2.py");// 执行py文件
//用输入输出流来截取结果
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
}
# test2.py
import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
2. 脚本函数中有参数
public void test4() throws Exception {
int a = 18;
int b = 23;
String[] args = new String[]{"python", "F:\\ProjectFile\\IDEA\\JPythonAndJMail\\src\\test\\resources\\test3.py", String.valueOf(a), String.valueOf(b)};
Process proc = Runtime.getRuntime().exec(args);// 执行py文件
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
}
# test3.py
import sys
def func(a,b):
return (a+b)
if __name__ == '__main__':
a = []
for i in range(1, len(sys.argv)):
a.append((int(sys.argv[i])))
print(func(a[0],a[1]))
Jython初学者必须会用的三种方式,更多高级用法参照Jython官网