Java调用python的方式

Java调用python的方式

https://blog.csdn.net/qq_26591517/article/details/80441540

pom依赖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>java-python-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

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

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

PythonExecTest.java

package com.demo.java.python;

import org.python.util.PythonInterpreter;

/**
 * @Description 在java类中直接执行python语句
 * @author 
 * @date 2020-01-20 11:00
 * @version 1.0
 */
public class PythonExecTest {

    public static void main(String[] args) {

        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版本的语法
    }
}

2.在java中调用本地python脚本的函数

add.py

# !/usr/bin/python
# -*- coding: UTF-8 -*-

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

PythonTest.java

package com.demo.java.python;

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

/**
 * @Description 在java中调用本地python脚本
 * 注意:以上两个方法虽然都可以调用python程序,但是使用Jython调用的python库不是很多,
 * 如果你用以上两个方法调用,而python的程序中使用到第三方库,
 * 这时就会报错java ImportError: No module named xxx。
 * @author 
 * @date 2020-01-20 11:05
 * @version 1.0
 */
public class PythonTest {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("E:\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);
    }
}

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

numpydemo.py

# !/usr/bin/python
# -*- coding: UTF-8 -*-

import numpy as np

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

PythonRunTimeTest.java

package com.demo.java.python;

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

/**
 * @Description 使用Runtime.getRuntime()执行脚本文件(推荐)
 * @author 
 * @date 2020-01-20 11:08
 * @version 1.0
 */
public class PythonRunTimeTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("python E:\workspace\idea-project\demo-space\java-python-demo\src\main\resources\numpydemo.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();
        }
    }

}

4.使用Runtime.getRuntime()执行脚本文件(推荐)【传递参数】

paramdemo.py

# !/usr/bin/python
# -*- coding: UTF-8 -*-

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]))

PythonRunTimeParamTest.java

package com.demo.java.python;

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

/**
 * @Description 使用Runtime.getRuntime()执行脚本文件(推荐)【传递参数】
 * @author 
 * @date 2020-01-20 11:08
 * @version 1.0
 */
public class PythonRunTimeParamTest {
    public static void main(String[] args) {
        int a = 18;
        int b = 23;
        try {
            String[] path = new String[] { "python", "E:\paramdemo.py", String.valueOf(a), String.valueOf(b) };
            Process proc = Runtime.getRuntime().exec(path);// 执行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();
        }
    }

}

原文地址:https://www.cnblogs.com/code-red-memory/p/15030087.html