Execute Python with Java: Jython Stepping Notes

Common java calls python scripts

1. Implemented through the class library provided by Jython.jar
2. Open the process through Runtime.getRuntime() to execute the script file


1.Jython

When using Jpython, the version matters! Most of the pits come from this. Those who don't listen to this sentence have to take a detour

Operating environment: Python2.7 + Jython-standalone-2.7.0

<!--Maven依赖,jar包自行前往仓库下载-->
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.0</version>
</dependency>

1) Jython executes the Python statement

import org.python.util.PythonInterpreter;

public class HelloPython {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("print('hello')");
    }
}

2) Jython executes the Python script

import org.python.util.PythonInterpreter;

public class HelloPython {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("./pythonSrc/time.py");
    }
}

3) Jython executes the Python method to get the return value

PythonInterpreter interpreter = new PythonInterpreter();
interpreter = new PythonInterpreter(); 
interpreter.execfile("./pythonSrc/fibo.py"); 
PyFunction function = (PyFunction)interpreter.get("fib",PyFunction.class); 
PyObject o = function.__call__(new PyInteger(8));
System.out.println(o.toString());

fibo.py

 # Fibonacci numbers module  
def fib(n): # return Fibonacci series up to n  
    result = []  
    a, b = 0, 1  
    while b < n:  
        result.append(b)  
        a, b = b, a+b  ·
    return result 

2. Limitations of Jython

Jython is very slow when executing ordinary py scripts, and when it contains third-party libraries (requests, jieba...), there are many bugs, which are not easy to deal with. The reason is that the sys.path of python is inconsistent with the sys.path of Jython, and the processing of Jython is not very good.

When python executes:

['F:\\Eclipse for Java EE\\workspace\\Jython\\pythonSrc', 'F:\\Python27\\DLLs', 'F:\\Python27\\lib', 'F:\\Python27\\lib\\lib-tk', 'F:\\Python27', 'F:\\Python27\\lib\\site-packages', 'F:\\Python27\\lib\\site-packages\\unknown-0.0.0-py2.7.egg', 'F:\\Python27\\lib\\site-packages\\requests-2.18.4-py2.7.egg', 'F:\\Python27\\lib\\site-packages\\certifi-2018.1.18-py2.7.egg', 'F:\\Python27\\lib\\site-packages\\urllib3-1.22-py2.7.egg', 'F:\\Python27\\lib\\site-packages\\idna-2.6-py2.7.egg', 'F:\\Python27\\lib\\site-packages\\chardet-3.0.4-py2.7.egg', 'C:\\windows\\system32\\python27.zip', 'F:\\Python27\\lib\\plat-win']

When Jython executes:

['F:\\Maven\\repo\\org\\python\\jython-standalone\\2.7.0\\Lib', 'F:\\Maven\\repo\\org\\python\\jython-standalone\\2.7.0\\jython-standalone-2.7.0.jar\\Lib', '__classpath__', '__pyclasspath__/']

Regarding the path problem, we have two solutions. One is to manually add the third-party library path and call

        PySystemState sys = Py.getSystemState(); 
        System.out.println(sys.path.toString());
        sys.path.add("F:\\Python27\\Lib\\site-packages\\jieba"); 

The second is to put the third-party library folder in the same level directory of the executed .py script .
Then came the new problem, do you think the path is the final problem? More than that, maybe it's a Python version syntax problem, 2x, 3x, that causes various Modules not to exist when you use Jython to execute a .py script containing a third-party library. Originally, the blogger took the Jython path, and also downloaded the jieba third-party library. Later, there were a lot of errors when running: the jieba library seems to have transitional support for py3, and jython does not support this syntax format. I changed jieba one after another. Therefore, the blogger gave up Jython decisively after being devastated! Because you can't use the python of the third-party library, but there are no eggs!

Here comes the final method: simulating console execution

public class Cmd {

    public static void main(String[] args) throws IOException, InterruptedException {
        String[] arguments = new String[] { "python", "./pythonSrc/time.py", "huzhiwei", "25" };
        try {
            Process process = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            int re = process.waitFor();
            System.out.println(re);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

time.py

#!/usr/bin/python
#coding=utf-8

#定义一个方法
def my_test(name, age):
    print("name: "+str(name))
    print(age)  #str()防解码出错
    return "success"
#主程序
#sys.argv[1]获取cmd输入的参数
my_test(sys.argv[1], sys.argv[2])

Results of the

name: huzhiwei
25
0

Another two dollars~
The limitation of this method is also coming. It is very simple for python developers and prints the output directly, but a python module can only do one thing, which is very similar to an open interface from the Python side to the Java side. , much like Servlet, right? There are also advantages, no mistakes, and it runs fast! Students who are still hesitating, hurry up and switch to cmd~!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324606142&siteId=291194637