Java调用Python的方法

Java调用Python的方法Java调用Python的方法方法一:Runtime.getRuntime()首先,add_test.py代码如下defadd(a,b):returna+bres=add(3,4)print(res)Java代码:packagefirst;importjava.io.*;publicclassinvoke{publicstaticvoidmain(String[]args)throwsIOException,Inter…

大家好,欢迎来到IT知识分享网。

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();
    }
}

执行结果:

Java调用Python的方法

方法二:JEP调用python

安装JEP

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

前置条件:

Java调用Python的方法

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

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

Java调用Python的方法

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

Java调用Python的方法

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

Java调用Python的方法

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的方法

执行结果:

Java调用Python的方法

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/24056.html

(0)
上一篇 2023-08-30 20:45
下一篇 2023-08-31 15:00

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信