Java调用Python的方法

Java调用Python的方法

方法一:Runtime.getRuntime()

首先,add_test.py代码如下

def add(a,b):
   return a + b
res = add(3,4)

print(res)

Java代码:

package first;


import java.io.*;

public class invoke {
   public static void main(String[] args) throws IOException,InterruptedException {
       String executer = "python";
       String file_path = "D:\\add_test.py";// python绝对路径
       String[] command_line = new String[]{executer, file_path};
       Process process = Runtime.getRuntime().exec(command_line);
       BufferedReader in = new BufferedReader(newInputStreamReader(process.getInputStream()));
       String line;
       while ((line = in.readLine()) != null) {
           System.out.println(line);
       }
       in.close();
       process.waitFor();
    }
}

执行结果:

方法二:JEP调用python

安装JEP

JEP地址:https://github.com/ninia/jep

前置条件:

将JEP下载至自己的Windows机器,执行python

setup.py build install命令进行编译安装,build完成之后,JEP路径会出现jar包:

Install完成之后,Python对应的site-package路径也会有对应的jar包:

这里需要注意的一点是,python现在一般在安装时自动写了环境变量path和PYTHONHOME,但是如果你只安装了anaconda,使用的是conda python,请根据以下的帖子自行修改环境变量https://stackoverflow.com/questions/42512817/fatal-python-error-on-windows-10-modulenotfounderror-no-module-named-encodings,否则后续运行时会有如下报错:

JEP调用demo

先写一个简单的invoke_args.py 代码如下:

import numpy as np
import pandas as pd

df2 = pd.DataFrame(np.array([[1, 2, 3], [4,5, 6], [7, 8, 9]]))

def invokeNoArgs():
   print("hello")
print(df2)

Java调用Python代码如下:

package first;

import jep.Interpreter;
import jep.JepConfig;
import jep.JepException;
import jep.SubInterpreter;

public class invoke2 {
   public static void main(String[] args) throws JepException {
       JepConfig config = new JepConfig();
       config.addIncludePaths("C:\\Users\\IdeaProjects\\DailyLearning\\src\\python");
       try (Interpreter interp = new SubInterpreter(config)){
           interp.eval("from invoke_args import *");
           // test a basic invoke with no args
           Object result = interp.invoke("invokeNoArgs");
           if (result!=null){
                throw newIllegalStateException(
                        "Received " +result + "but expected null");
           }
       }
    }
}

注意把JEP添加到Java的Library Path中去,在IDEA中的对应操作如下:

执行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值