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包:

Java调用Python的方法_第1张图片

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

Java调用Python的方法_第2张图片

这里需要注意的一点是,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中的对应操作如下:

Java调用Python的方法_第3张图片

执行结果:

你可能感兴趣的:(运维)