Python script calls Java

 

During the development process, the need to use occasionally encountered when calling Java Python script, after all, Python has a natural advantage in areas such as reptiles, and scientific computing. Recently met at work need to call a Python program has been written in the Java program, so do some recording.

1 Two common ways to call Java Python script

Usually called by the following two:

• By calling Jython, which is achieved by providing a library Jython.jar

• Through the Java Runtime direct, Runtime class Runtime.getRuntime () to open the process, execute python script file

2 implementation calls by Jython

Introduction to Jython

Jython home page: http: //www.jython.org/

Jython is the Python language on the implementation of the Java platform, nature, Jython is written by Java, which is implemented on the JVM Python language. Therefore, you can call Python Jython directly in Java.

Jython Installation

Before installing Jython, you must ensure that local JDK already installed.

1. Jython official website to download the installation file corresponding version Installer and two separate Standalone jar jar file into a specific directory, such as C: jython2.7.0;

2. Go to the terminal, switch to the current directory for the installation of Jython jar file is located, execute java -jar jython_installer_2.7.0.jar, "Of course you can also directly enter the directory Double-click on the corresponding jar file to install";

3. The environment variable corresponding to the configuration respectively corresponding jar, lib directory to the CLASSPATH and Path:

-C: jython2.7.0jython.jar; was added to the CLASSPATH

-C: jython2.7.0; C: jython2.7.0Lib; was added to the Path

Run the command in a terminal jython, if the installation is successful, it will enter into Jython interactive environment, can execute Python commands and interact with the environment as Python. But you can also execute python script file by jython xxx.py command.

Jython Python script execution

  • Python statements directly embedded in Java

Less usage directly embedded Python statements in Java, and is not particularly meaningful.

import org.python.util.PythonInterpreter;

public class Main {

public static void main(String[] args) {

PythonInterpreter interpreter = new PythonInterpreter();

// execute Python statements

interpreter.exec("import sys");

interpreter.exec("print 'hello'");

interpreter.exec("print 2**100");

}

}

  • In Java implementation of Python scripting has been named xxx.py of good

Directly through the Python script written Jython packet calls, as required during execution of the program, can be roughly divided into the following situations:

1. The need to pass parameters to a Python script by the Java program does not need to acquire the return value line Python script, the script may be opened by means of the file stream directly, and executed using Jython interpreter.

import org.python.util.PythonInterpreter;

import java.io. *;

public class Main {

public static void main(String[] args) {

PythonInterpreter interpreter = new PythonInterpreter();

// execute Python script file

try {

InputStream filepy = new FileInputStream("C:xxx.py");

interpreter.execfile(filepy);

filepy.close();

} catch (Exception e) {

e.printStackTrace ();

}

}

}

2. Call Python program in Java, and also need to pass parameters received return value. Python program calls a method, it can be divided into two, one is called directly written in the Python function, and another function call Python scripts class.

- direct call function, passing the parameters achieved by PyFunction and get the return value

import org.python.core.*;

import org.python.util.PythonInterpreter;

public class Main{

public static void main(String[] args) {

PythonInterpreter inter = new PythonInterpreter();

// Specify file path Python function

String pythonFunc = "D:test.py";

inter.execfile(pythonFunc);

// Get the name of the function test

PyFunction pyf = inter.get("test", PyFunction.class);

// pass parameters to the function and returns the result acquires

PyObject res = pyf.__call__(Py.newInteger(2), Py.newInteger(3));

System.out.print(res);

inter.cleanup();

inter.close();

}

}

- called Java, Python object instance, using the method of Example PyObject Python Objects, Python object method call, passing parameters and receiving a return value cut.

import org.python.core.*;

import org.python.util.PythonInterpreter;

public class Main{

public static void main(String[] args) {

PythonInterpreter inter = new PythonInterpreter();

// python class path

String pythonClass = "D:test_class.py";

// python object name

String pythonObjName = "cal";

// python class name

String pythonClazzName = "Calculator";

inter.execfile(pythonClass);

// instantiate an object Python

inter.exec(PythonObjName + "=" + pythonClazzName + "()");

// Get the Python object is instantiated

PyObject pyObject = inter.get(pythonObjName);

// call the python object method, pass arguments and return values ​​received

PyObject res = pyObject.invoke("power", new PyObject[] {Py.newInteger(2), Py.newInteger(3)});

double power = Py.py2double(res);

System.out.print(power);

inter.cleanup();

inter.close();

}

}

Among them, the contents of test_class.py file is as follows:

import math

class Calculator(object):

def power(x, y):

return math.pow(x, y)

  • Implementation calls by Runtime.getRuntime (). Exec ()

Runtime class is a Java JVM run-time environment and related classes, by Runtime.getRuntime () you can get to the JVM run-time environment of the current. Most methods of Runtime are instance methods that should be used during each getRuntime () method is invoked at runtime. Runtime class using Python script to perform the method is very simple and crude, directly into the Python script in the current platform can execute the command. Java execute external commands, or by using the exec Runtime main class () method call is completed the platform shell, such as cmd in the windows, and the shell under linux, unix, macOS's.

Runtime execution by Python script, passing parameters to the script and get the output of Python scripts directly from the command.

public class Main{

public static void main(String[] args) {

String cmd = "python xxx.py argv1 argv2 ...";

Process proc = Runtime.getRuntime().exec(cmd);

InputStream is = proc.getInputStream();

DataInputStream dis = new DataInputStream(is);

String str = dis.readLine();

proc.waitFor();

System.out.println(str);

}

}

3 summary

The above two methods can achieve call Python script in Java programs, but when using Jython call, less efficient, will consume more resources, and when the script requires Python called third-party dependencies need in Jython install third-party packages. Runtime calls while using the script more dependent on the platform is running, as long as the current third-party platform installed corresponding dependencies, the script can be executed successfully, execution efficiency and direct the implementation of the Python script and there is no difference.

Of course, in the program continue to be nested calls will reduce the efficiency of the program, increasing the coupling of the complexity of the program, future expansion is not convenient, so do not suggest that you use frequently, and can be considered resolved by means of a corresponding micro services The problem.

The article there are many shortcomings, we hope that more exchanges, exhibitions.

Reference links

1. Five JVM-based scripting language https://coolshell.cn/articles/2631.html

2.Java call Python http://tonl.iteye.com/blog/1918245

Use 3.Java Runtime.exec () of https://blog.csdn.net/toneylyx/article/details/52623597

4.Why are there so many pythons https://www.oschina.net/translate/why-are-there-so-many-pythons

5.Jython www.jython.org

Guess you like

Origin www.cnblogs.com/zhigu/p/10935182.html