真实项目:java调用python传参机器学习-RedHatlinux操作系统环境下

java调用python传参机器学习-RedHatlinux操作系统环境下

linux:java调用python并传参数机器学习实现

java调用python的方式有4种,详情参考—之桐—博主的
使用Java调用Python的四种方法在这里本人结合自身项目分享第三类调用脚本方法。
本人推荐项目逻辑是:java传递用户id给python脚本,python 连接mysql数据库,通过数据处理,算法运算,并模型训练得到结果,返回给springBoot处理。
本人亲测,希望对大家有帮助!

Runtime.getRuntime().exec()原理;

java文档 [1]给出了方法的使用和介绍:

  1. static Runtime getRuntime() ,public static Runtime getRuntime()
    Returns the runtime object associated with the current Java application. Most of the methods of class Runtime are instance methods and must be invoked with respect to the current runtime object.
    Returns:
    the Runtime object associated with the current Java application.从这个介绍中不难看出会得到一个包含用户信息的应用实例对象;
  2. public Process exec(String[] cmdarray)
    throws IOException
    Executes the specified command and arguments in a separate process.
    This is a convenience method. An invocation of the form exec(cmdarray) behaves in exactly the same way as the invocation exec(cmdarray, null, null).

Parameters:
cmdarray - array containing the command to call and its arguments.
Returns:
A new Process object for managing the subprocess
Throws:
SecurityException - If a security manager exists and its checkExec method doesn’t allow creation of the subprocess
IOException - If an I/O error occurs

       从上可以得到编译后创建一个进程调用系统shell命令集去处理参数,参数为[command,arguments]。  

项目代码

@Override
    public List getFile(String filename) throws IOException, InterruptedException {

        List<Article> list = new ArrayList<>();
        String param = filename;
        String[] command = new String[]{"/root/anaconda3/envs/myenv/bin/python", "/root/mysqlTest.py", param};
        final Process process = Runtime.getRuntime().exec(command);
//后续版本中多线程优化
        Reader reader = new InputStreamReader(process.getInputStream());
        BufferedReader bf = new BufferedReader(reader);
          String line = null;
        try {
            while ((line = bf.readLine()) != null) {
                System.out.print("result:"+line);
                //.在正则表达式中是一种特殊符号,为了让split识别出源字符串中的“.”,就需要进行转意义“\\.”
                String[] result1 = line.split("\\D+");
                for (int i = 1; i < result1.length; i++) {
                    list.add(javaToPythonMapper.getArticle(Integer.valueOf(result1[i])));
                }
            }
            reader.close();
            bf.close();
        
        

1,filename为方法传递的用户参数id。2,/root/anaconda3/envs/myenv/bin/python 为Redhat linux 64位系统下anaconda环境下python解释器的路径。
若使用自建环境需要永久激活。 注意:每次启动conda都会回到默认环境(bash)如果要永久激活,请配置.bashrc 并且关闭默认环境。

conda activate <environment_name> #environment_name 环境名称
vim .bashrc #文件最后一行添加conda activate <environment_name> ,ESC :wq保存
conda config --set auto_activate_base false #关闭默认环境(bash)
source .bashrc #刷新配置文件
which python #查看py解释器位置

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
myenv为conda 中自己创建的永久激活环境

3,/root/mysqlTest.py为linux下py文件的位置

import sys
import numpyas as np
import pandas  as pd
import pymysql 
import skit-learn
import skit-surprise
#第一种
dataforJava1 = sys.argv[0:1] # 获取到的Java传递的内容: Python文件绝对地址 + 参数
print("Java,I am Python  "+"your passage is : "+str(dataforJava1))
#第二种
dataforJava2 = sys.argv[1:] # 获取到的python的参数
print( str(dataforJava2[0]))代码片


df_dealed = pd.DataFrame(result_all)
# 保存成csv 这个编码是为了防止中文没法保存,index=None的意思是没有行号
        df_dealed.to_csv(csv_file,  index=None, header=None, encoding='gbk',float_format=None)
        #查询mysql数据库并处理数据
         mysql.search_and_save('SELECT * FROM usermark where not isnull(mark);','out1.csv' )

如上为py脚本获取java参数和输出计算文件的代码。由于项目中使用了numpy,pandas,pymysql,skit-learn,skit-surprise等库故截取部分代码显示。

运行结果部分
如图:部分运行结果生成了out1.csv结果集,其余结果以print()输出结果回到java字符流中返回接口。

在这里插入图片描述

apifox测试服务器接口,运行正常获得推荐数据。
文档
[1]https://docs.oracle.com/en/java/

  • 13
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值