让JAVA执行Python命令和脚本

本文介绍了如何在Java程序中执行Python命令和脚本的三种方法:1) 使用Jython直接执行Python语句,需要安装Jython环境;2) 通过Jython调用本地Python脚本,实现函数交互;3) 利用Runtime.getRuntime().exec()执行Python脚本文件,适合包含第三方库的场景。详细步骤和代码示例帮助理解如何在Java和Python间进行交互。
摘要由CSDN通过智能技术生成

让JAVA执行Python命令和脚本

实际工程项目中可能会用到Java和python两种语言结合进行,这样就会涉及到一个问题,就是怎么用Java程序来调用已经写好的python脚本&&命令呢,一共有三种方法可以实现

1. 在java类中直接执行python语句

此方法需要引用 org.python包,需要下载安装Jython。在这里先介绍一下Jpython。下面引入百科的解释

Jython是一种完整的语言,而不是一个Java翻译器或仅仅是一个Python编译器,它是一个Python语言在Java中的完全实现。Jython也有很多从CPython中继承的模块库。最有趣的事情是Jython不像CPython或其他任何高级语言,它提供了对其实现语言的一切存取。所以Jython不仅给你提供了Python的库,同时也提供了所有的Java类。这使其有一个巨大的资源库。

建议下载最新版本的Jpython,因为可以使用的python函数库会比老版本的多些,目前最新版本为2.7。

<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.0</version>
</dependency>

以上准备好了,就可以直接在java类中写python语句了,具体代码如下:

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a=[5,2,3,9,4,0]; ");
interpreter.exec("print(sorted(a));");  //此处python语句是3.x版本的语法
interpreter.exec("print sorted(a);");   //此处是python语句是2.x版本的语法
## 控制台输出如下
Connected to the target VM, address: '127.0.0.1:62132', transport: 'socket'
[0, 2, 3, 4, 5, 9]
[0, 2, 3, 4, 5, 9]
Disconnected from the target VM, address: '127.0.0.1:62132', transport: 'socket'

Process finished with exit code 0

这种方式在服务器上部署后遇到如图问题:
在这里插入图片描述

原因:

部署服务器缺少jython环境,需要安装。

jython安装
  • 上传jython-installer-2.7.0.jar到服务器任意目录
  • 执行命令java -jar jython-installer-2.7.0.jar,注意需要图形化桌面
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-H9WmfJW8-1634207901834)(http://bed.thunisoft.com:9000/ibed/2021/08/27/CxwBBDQi8.png)]
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AuAjyp8r-1634207901837)(http://bed.thunisoft.com:9000/ibed/2021/08/27/CxwBaKag4.png)]
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fF58C7xe-1634207901840)(http://bed.thunisoft.com:9000/ibed/2021/08/27/CxwBtANOK.png)]
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-P7y0igAI-1634207901846)(http://bed.thunisoft.com:9000/ibed/2021/08/27/CxwCAok2y.png)]
  • 注意路径/root/jython2.7.0
代码调整
    public static void main(String[] args) {
        Properties props = new Properties();
        # 指定Jython安装路径
        props.put("python.home", "/root/jython2.7.0");
        props.put("python.console.encoding", "UTF-8");
        props.put("python.security.respectJavaAccessibility", "false");
        props.put("python.import.site", "true");
        Properties preprops = System.getProperties();
        PythonInterpreter.initialize(preprops, props, new String[0]);
        PythonInterpreter pyInterpreter = new PythonInterpreter();
        pyInterpreter.exec("import sys");
        pyInterpreter.exec("a=[5,2,3,9,4,0]; ");
        pyInterpreter.exec("print(sorted(a));");
        pyInterpreter.exec("print sorted(a);");

    }
  • 测试环境Windows10,已安装Jython
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9IGHOvgV-1634207901848)(http://bed.thunisoft.com:9000/ibed/2021/08/27/CxwNPGH6O.png)]

2. 在java中调用本地python脚本

首先在本地建立一个python脚本,命名为add.py,写了一个简单的两个数做加法的函数,代码如下:

def add(a,b):
    return a + b

python的功能函数已经写好,接下来我们写一个java的测试类(同样需要用到Jpython包),来测试一下是否可以运行成功。代码如下:

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
 
public class Java_Python_test {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\\add.py");
 
        // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
        PyFunction pyFunction = interpreter.get("add", PyFunction.class);
        int a = 5, b = 10;
        //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的“Python类型”
        PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); 
        System.out.println("the anwser is: " + pyobj);
    }
}

## 控制台输出如下
Connected to the target VM, address: '127.0.0.1:59748', transport: 'socket'
the anwser is: 15
Disconnected from the target VM, address: '127.0.0.1:59748', transport: 'socket'

Process finished with exit code 0

关于Jpython更多详细的信息可以参考官方的相关文档,官网地址点这里

注意:以上两个方法虽然都可以调用python程序,但是使用Jpython调用的python库不是很多,如果你用以上两个方法调用,而python的程序中使用到第三方库,这时就会报错java ImportError: No module named xxx。遇到这种情况推荐使用下面的方法,即可解决该问题。

3. 使用Runtime.getRuntime()执行脚本文件(推荐)

为了验证该方法可以运行含有python第三方库的程序,我们先写一个简单的python脚本,代码如下:

import numpy as np
 
a = np.arange(12).reshape(3,4)
print(a)

可以看到程序中用到了numpy第三方库,并初始化了一个3×4的一个矩阵。
下面来看看怎么用Runtime.getRuntime()方法来调用python程序并输出该结果,java代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Demo1 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("python D:\\demo1.py");// 执行py文件
            //用输入输出流来截取结果
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } 
    }
}



## 控制台输出如下
Connected to the target VM, address: '127.0.0.1:59748', transport: 'socket'
[[0 1 2 3 ]
[4 5 6 7 ]
[8 9 10 11 ]]
Disconnected from the target VM, address: '127.0.0.1:59748', transport: 'socket'

Process finished with exit code 0

可以看到运行成功了,但有的朋友可能会问了,怎么在python程序中函数传递参数并执行出结果,下面我就举一例来说明一下。
先写一个python的程序,代码如下:

import sys
 
def func(a,b):
    return (a+b)
 
if __name__ == '__main__':
    a = []
    for i in range(1, len(sys.argv)):
        a.append((int(sys.argv[i])))
 
    print(func(a[0],a[1]))

其中sys.argv用于获取参数url1,url2等。而sys.argv[0]代表python程序名,所以列表从1开始读取参数。
以上代码实现一个两个数做加法的程序,下面看看在java中怎么传递函数参数,代码如下:

int a = 18;
int b = 23;
try {
    String[] args = new String[] { "python", "D:\\demo2.py", String.valueOf(a), String.valueOf(b) };
    Process proc = Runtime.getRuntime().exec(args1);// 执行py文件
 
    BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    in.close();
    proc.waitFor();
} catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}

其中args是String[] { “python”,path,url1,url2 }; ,path是python程序所在的路径,url1是参数1,url2是参数2,以此类推。
最后结果如下:

## 控制台输出如下
Connected to the target VM, address: '127.0.0.1:59748', transport: 'socket'
41
Disconnected from the target VM, address: '127.0.0.1:59748', transport: 'socket'

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值