Java调用Python

常见的java调用python脚本方式有两种,下面给大家介绍一下:

  • 通过Jython.jar提供的类库实现
  • 通过Runtime.getRuntime()开启进程来执行脚本文件

这两种方法我都尝试过,个人推荐第二种方法,因为Python有时需要用到第三方库,比如requests,而Jython不支持。所以本地安装Python环境并且安装第三库再用Java调用是最好的方法。

下面通过两个小例子,分别是不带参数和带参数的,展示如何使用Java调用Python脚本:

不带参栗子

Python代码

#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File        :javaToPython.py
@Time        :2020/09/03 12:59:32
@Author      :hejiang
@Software    :vsCode
'''


def hello():

    print('Hello,Python')


if __name__ == '__main__':

    hello()

Java代码


package net.qmgf.proj.wbmining.fut.service.impl;


import java.io.BufferedReader;
import java.io.InputStreamReader;


/**
 * java调用Python
 *
 * @author He
 * @date 2020/9/3 13:01
 * @return
 **/
public class JavaToPython {
    public static void main(String[] args) {
        String[] arguments = new String[]{"python", "E:\\GIT\\gitee\\python-maiden\\7.数据处理\\PDF处理\\javaToPython.py"};

        try {
            Process process = Runtime.getRuntime().exec(arguments);
            // BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,
            //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            System.out.println(re);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

带参的栗子

Python代码

#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@File        :javaToPython.py
@Time        :2020/09/03 12:59:32
@Author      :hejiang
@Software    :vsCode
'''


import sys


def hello(name, age):

    print('name:'+name)

    print('age:'+age)


if __name__ == '__main__':

    hello(sys.argv[1], sys.argv[2])

java代码

package net.qmgf.proj.wbmining.fut.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;


/**
 * java调用Python
 *
 * @author He
 * @date 2020/9/3 13:01
 * @return
 **/
public class JavaToPython {
    public static void main(String[] args) {
        String[] arguments = new String[]{"python", "E:\\GIT\\gitee\\python-maiden\\7.数据处理\\PDF处理\\javaToPython.py", "lei", "23"};

        try {
            Process process = Runtime.getRuntime().exec(arguments);
            // BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,
            //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            System.out.println(re);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Tags: