Java 与 Python 数据交互
开发环境及工具:
java 环境 :JDK 1.8
Python环境:Python 3.7 (安装anaconda自带的python版本)
Anaconda环境: conda 4.5.11
Maven环境: Maven 3.6.3
开发工具:
IDEA 2020.3.2
Pycharm 2019.2
Postman
本文是以Spring Boot项目来完成Java与Python的数据操作的。
方法一 执行简单的Python代码
第一步 添加依赖
在pom.xml文件中加入以下内容,并联网下载。
<!--Jython--> <dependency><groupId>org.python</groupId><artifactId>jython-standalone</artifactId><version>2.7.2</version> </dependency>
第二步 编写Controller
TestController.java
@RestController
@RequestMapping("test")
public class TestController {@RequestMapping("hello")public void printHello(){PythonInterpreter interpreter = new PythonInterpreter();interpreter.exec("list = [5,2,3,9,4,6]");interpreter.exec("print(sorted(list))");}}
第三步 启动程序,发起请求
通过Postman发起请求,将下面请求路径相应的位置做下修改即可。
http://localhost:8899/test/test
输出结果:
方法二 Jython执行Python文件
第一步 编写Python文件
用记事本或者Pycharm等编写代码
add.py
def add(a,b):return (a+b)
第二步 编写Controller
@RequestMapping("showMsg")public void showMsg() {PythonInterpreter interpreter = new PythonInterpreter();interpreter.execfile("D:\\pythonPro\\add.py");// 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型PyFunction pyFunction = interpreter.get("add", PyFunction.class);int a = 15, b = 20;/*** 调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的"Python的类型"* Python 是一个弱类型语言,对数据类型会进行隐式转换,在Java中定义好类型再传入*/PyObject pyObject = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); //多个参数逗号拼接System.out.println("the answer is : " + pyObject);}
第三步 启动程序并访问
访问:
http://localhost:8899/test/showMsg
运行结果:
方法三 通过Runtime调用python脚本
第一步 编写test.py文件
import numpy as np
list2 = [[1,2,3],['a','b','c']]
print(np.array(list2))
查看当前python 安装的库:
pip list
这里用到了 numpy库,如果没有这个库可以手动安装:
pip3 install -i https://mirrors.aliyun.com/pypi/simple numpy
第二步 编写Controller
@RequestMapping("testpy")public void testpy() {Process process; //package java.lang; 这个包 不要导入错了try {// 模仿控制台运行py文件 python + 文件名process = Runtime.getRuntime().exec("python D:\\pythonPro\\test.py");// 用输入输出流来显示结果BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));String line = null; // 按行读取while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}// 记得关闭流bufferedReader.close();process.waitFor();} catch (IOException | InterruptedException e) {e.printStackTrace();}}
注:
process = Runtime.getRuntime().exec("python D:\\pythonPro\\test.py");
这里 python 不要漏掉了,是一条执行命令
漏掉会出现错误:
第三步 启动程序并访问
Postman访问
http://localhost:8899/test/testpy
输入结果:
四 参数传递
在实际的应用场景中,我们可能会在Python程序中传递参数。
第一步 修改一下 add.py文件
import sysdef add(num1,num2):return (num1+num2)if __name__ == '__main__':mylist = []for i in range(1, len(sys.argv)):mylist.append((int(sys.argv[i])))print(add(mylist[0],mylist[1]))
第二步 编写Controller
@RequestMapping("testArgs")public void testArgs(){int num1 = 15;int num2 = 52;try {/*** 其中args是String[] { “python”,path,url1,url2 };* path是python程序所在的路径,url1是参数1,url2是参数2,以此类推。*/String[] args = new String[] { "python", "D:\\pythonPro\\add.py", String.valueOf(num1), String.valueOf(num2) };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();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}
注意:后续我在Linux使用过程中,会出现目录找不到的错误信息。解决办法: 将 String[] { “python”,path,url1,url2 }; 中 python的路径改为绝对路径即可。
第三步 启动程序并访问
Postman访问
http://localhost:8899/test/testArgs
运行结果:
以上就是常用的java 与Python数据交互方式。