java 调用python中的函数

使用Jython来实现:
py文件内容:
在这里插入图片描述
代码:

 public static void main(String[] args) {
 		//配置
        Properties props = new Properties();
        props.put("python.home", "path to the Lib folder");
        props.put("python.console.encoding", "UTF-8");
        props.put("python.security.respectJavaAccessibility", "false");
        props.put("python.import.site", "false");
        Properties preprops = System.getProperties();
        PythonInterpreter.initialize(preprops, props, new String[0]);
		
		//使用
        PythonInterpreter interpreter = new PythonInterpreter();
//        interpreter.exec("import sys");
//        interpreter.exec("sys.path.append('/usr/local/python3/lib/python3.6/site-packages')");
        interpreter.execfile("D:/a/py/testpy.py");//文件绝对路径
        PyFunction func = (PyFunction) interpreter.get("process", PyFunction.class);//调用的函数名
        PyObject pyobj = func.__call__(new PyInteger(1),new PyInteger(2));//参数,利用重载
        Logs.get().info("py返回结果------:" + pyobj.toString());
    }

在这里的配置信息如果不加上的话会报错,报错如下:
在这里插入图片描述
问题:
在这里说明一下因为Jython现在最新的版本貌似只是2.7.2版本,所以python3的一些函数他是不支持的,会出现“ModuleNotFoundError: No module named ‘XXX’ ”这个问题
所以我们在这里需要在java中手动指定一下py的sys,也就是注释掉的这两行

        interpreter.exec("import sys");
        interpreter.exec("sys.path.append('/usr/local/python3/lib/python3.6/site-packages')");//这个路径是py使用的配置路径

再推荐一下别的调用py的技术,
py4j
当然使用java自带的也是可以的,简单的一个例子:

Process process = Runtime.getRuntime().exec("python D:/a/py/testpy.py");

process.destroy();//销毁进程

这个自带的就是相当于java打开小黑框进行操作,所以最后要把它关闭,还有这里还有异常需要捕获(⊙o⊙)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值