Summary of Java calling Python program methods (the most complete and detailed)

Posted by ten31studios on Mon, 20 Dec 2021 07:56:52 +0100

How to call Python programs using Java

This article introduces how to call python methods in java for your reference.
The combination of Java and python may be used in actual engineering projects, which will involve a problem, that is, how to call the written Python script with Java program. There are three methods to implement. The specific methods are introduced to you:

1. Directly execute python statements in Java classes

This method needs to reference org Python package, you need to download Jpython. Let's first introduce Jpython. The following is an explanation of the introduction of Encyclopedia:

Jython is a complete language, not a Java translator or just a python compiler. It is a complete implementation of Python language in Java. Jython also has many module libraries inherited from CPython. The most interesting thing is that Jython, unlike CPython or any other high-level language, provides all access to its implementation language. So Jython not only provides you with Python libraries, but also provides all Java classes. This gives it a huge resource base.

Here, I suggest downloading the latest version of Jpython, because more python function libraries can be used than the old version. At present, the latest version is 2.7.
To download the jar package, click download Jython 2.7 0 - Standalone Jar
To download the installer, click download Jython 2.7 0 - Installer
If you use maven dependency addition, use the following statement

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

When you are ready, you can directly write python statements in java classes. The specific code is as follows:

import org.python.util.PythonInterpreter;

public class Main {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("a=[5,4,3,2,1]");
        interpreter.exec("print(sorted(a))");
    }
}

2. invoke the local python script in Java

First, create a python script locally, named add Py, write a simple function of adding two numbers. The code is as follows:

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

The python function has been written. Next, let's write a java test class (also using the Jpython package) to test whether it can run successfully. The code is as follows:

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");
 
        // The first parameter is the name of the function (variable) expected to be obtained, and the second parameter is the object type expected to be returned
        PyFunction pyFunction = interpreter.get("add", PyFunction.class);
        int a = 5, b = 10;
        //Call the function. If the function requires parameters, the parameters must be converted to the corresponding "Python type" in Java
        PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); 
        System.out.println("the anwser is: " + pyobj);
    }
}


be careful:
Although the above two methods can call python programs, there are not many python libraries called by Jpython. If you call the above two methods and use a third-party library in python programs, you will report an error java ImportError: No module named xxx. In this case, the following methods are recommended to solve the problem.

3. Use runtime Getruntime() execution script file (recommended)

In order to verify that this method can run programs containing python third-party libraries, we first write a simple python script with the following code:

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

You can see that the numpy third-party library is used in the program, and a 3 × A matrix of 4.
Let's see how to use runtime Getruntime () method to call the python program and output the result. The java code is as follows:

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

public class Demo1 {
    public static void main(String[] args) {
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("python D:\\IDEA\\spring4all\\JPython\\src\\main\\java\\demo1.py");//Execute Py file
            //Intercept the result with the input / output stream
            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();
        }
    }
}


You can see that the operation is successful, but some friends may ask how to pass parameters and execute results in python programs. Let me give an example to illustrate.
First write a python program with the following code:

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

Where sys Argv is used to obtain parameters url1, url2, etc. And sys Argv [0] represents the python program name, so the list reads parameters from 1.
The above code implements a program for adding two numbers. Let's see how to transfer function parameters in java. The code is as follows:

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

public class Demo2 {
    public static void main(String[] args) {
        int a = 18, b = 23;
        try {
            String[] args1 = new String[]{"python", "D:\\IDEA\\spring4all\\JPython\\src\\main\\java\\demo2.py", String.valueOf(a), String.valueOf(b)};
            Process proc = Runtime.getRuntime().exec(args1);//Execute PY file
            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 | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Where args is String [] {"Python", path,url1,url2}, Path is the path where the python program is located, url1 is parameter 1, url2 is parameter 2, and so on.
The final result is shown in the figure:

Finally, add:
There are two pythons on my computer at the same time, and I don't want to use the default one or modify the default Python interpreter. In this case, I can write a bat file, switch to the directory of the python through dos command in the bat file, and then run the py file

py file:

import time

print('hello!')
time.sleep(120)
print('bye!')

bat file:

@echo off
D:
cd D:\ProgramData\Anaconda3
start python D:\IDEA\spring4all\JPython\src\main\java\test.py
exit

Java program:

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

public class Demo3 {
    public static void main(String[] args) {
        Process proc;
        try {
            proc = Runtime.getRuntime().exec("cmd /c D:\\IDEA\\spring4all\\JPython\\src\\main\\java\\run.bat");
            //Intercept the result with the input / output stream
            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 | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

reference material

  1. http://blog.csdn.net/it_xiao_bai/article/details/79074988

Topics: Python Java crawler