How to invoke Python code in Java

Source: Internet
Author: User

Sometimes, we encounter such a problem: with a classmate to write code, a classmate will only write python, but not Java,

And you can only write Java is not good at Python, and find it difficult to use Java to rewrite each other's code, then you have to try to "call each other's code."

I'll take a few simple examples below to illustrate how to invoke Python code in Java.

This article only needs to be able to read:

    • Familiar with the basic syntax of Java
    • Know a little Python

The main contents are as follows:

    1. What is Jython?
    2. A Hellopython program
    3. Execute a python script in the JVM
    4. Call Python-written functions in Java only
    5. Scenarios with third-party modules: a handwriting recognition program

What is Jython?

Jython (formerly Jpython), is a Python interpreter written in the Java language.

In the absence of a third-party module, it is common to choose to use Jython to invoke Python code, which is an open-source jar package.

You can choose to download to the official website, if you cannot access it, please click here.

a Hellopython program
Import Org.python.util.PythonInterpreter;  Public class Hellopython {    publicstaticvoid  main (string[] args) {          New  pythoninterpreter ();        Interpreter.exec ("Print (' Hello ')");}    }

What is Pythoninterpreter? Its Chinese meaning is "python interpreter". We know that the Python program is executed by the interpreter, we create an "interpreter" object in Java, simulate the behavior of the Python interpreter, and execute the Python code directly in the JVM via exec ("python statement"). The output of the above code is: Hello

execute a Python script in the JVM
Interpreter.execfile ("d:/labs/mytest/hello.py");  

As above, change exec to execfile. It is important to note that this. py file cannot contain third-party modules because this "Python script" is ultimately executed in the JVM environment, and if there is a third-party module, the error will be:java importerror:no module named XXX

call Python-written functions in Java only

Complete a hello.py code first:

def Hello ():     return ' Hello '

Call this function in the Java code:

Importorg.python.core.PyFunction;ImportOrg.python.core.PyObject;ImportOrg.python.util.PythonInterpreter; Public classHellopython { Public Static voidMain (string[] args) {Pythoninterpreter interpreter=NewPythoninterpreter (); Interpreter.execfile ("D:/labs/hello.py"); Pyfunction pyfunction= Interpreter.get ("Hello", pyfunction.class);//The first parameter is the name of the desired function (variable), the second argument is the object type that is expected to be returnedPyobject pyobject = pyfunction.__call__ ();//calling FunctionsSystem.out.println (Pyobject); }}

The result of the above code execution is: Hello

Even if you just call a function, you must first load the. py file, and then get and call this function from the class defined in the Jython package.

If the function requires parameters, the parameter must first be converted to the corresponding "Python type" in Java, for example:

__call__ (newnew Pyinteger (b))

A, B is of type int in Java, as well as:pystring(String string), and PyList(Iterator<PyObject> iter) so on.

Refer to the official API documentation for details.

scenarios with third-party modules: A handwriting recognition program

This is a small program that I wrote with my roommate, the complete code here: Http://pan.baidu.com/s/1sl4l68H, a piece of code on the core Java is referenced on the interface.

Because a third-party NumPy module was used in a Python program, resulting in the inability to execute through Jython, and due to the limitations of individual levels that could not be fully rewritten in Java, this was an unwise choice. The following are purely personal ideas, not in-depth information. The idea is to simply execute a local program via Java (not necessarily. Py) and then interact with the data through a local file.

The core code is as follows:

ImportJava.io.*;classPycaller {Private Static FinalString Data_swap = "Temp.txt"; Private Static FinalString Py_url = System.getproperty ("User.dir") + "\\test.py";  Public Static voidWriteimagepath (String path) {PrintWriter pw=NULL; Try{PW=NewPrintWriter (NewFileWriter (NewFile (Data_swap)); } Catch(IOException e) {e.printstacktrace ();        } pw.print (path);    Pw.close (); }     Public StaticString Readanswer () {BufferedReader BR; String Answer=NULL; Try{br=NewBufferedReader (NewFileReader (NewFile (Data_swap)); Answer=Br.readline (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        returnanswer; }     Public Static voidexecpy () {Process proc=NULL; Try{ System.out.println (system.getproperty ( " User.dir") + "\\test.py"); proc = Runtime.getruntime (). EXEC ("python" + Py_url);        Proc.waitfor (); } Catch(IOException e) {e.printstacktrace (); } Catch(interruptedexception e) {e.printstacktrace (); }    }    //Test Code     Public Static voidMain (string[] args)throwsIOException, interruptedexception {writeimagepath ("D:\\labs\\mytest\\test.jpg");        execpy ();    System.out.println (Readanswer ()); }}

is actually executing a command-line instruction through Java.

How to invoke Python code in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.