Java calls Python script

Source: Internet
Author: User

This blog is designed to spit out the Java call today encountered by the Python script encountered in the pit, tossing for 3 hours finally can run through, the code is super short, but a lot of information on the Internet is copied to copy, very few can directly run through, especially for your Python file used in the third-party class library situation.

Let's start by saying why I'm calling Python code in Java because Python provides a rich library of classes in crawlers, but I already have a Java operations database and message middleware code that could take at least a week to implement in Python. In order to reduce the cost of time, so I decided to use Java to call the Python script using requests and so on, the following to share my solution to the process, I hope to meet similar problems of friends a little help.

Common Java-calling Python scripting methods
    • Implementation of the class library provided by Jython.jar
    • Execute script file with Runtime.getruntime () open process
Implementation of the class library provided by Jython.jar

With Jython.jar implementation, we need to introduce a jar package, specifically I wrote a demo, assuming your Python code is test.py:

def my_test (name, age): Print (    "name:" +name)    print ("Age:" +age)    return "Success"

Java calls the test.py code:

public static void Main (string[] args) {      Pythoninterpreter interpreter = new Pythoninterpreter ();        Interpreter.execfile ("e:\\workspace\\pycharm_workspace\\weixincrawer\\test.py");        pyfunction function = (pyfunction) interpreter.get ("My_test", pyfunction.class);        Pyobject pyobject = function.__call__ (New pystring ("Huzhiwei"), New pystring ("+");       System.out.println ("Anwser =" + pyobject.tostring ());      }

Output Result:

name: huzhiweiage: 25anwser = success

There is no problem here, we use the Function.call method to call the Python function in the parameters, using the Pyobject.tostring () method to get the return value of the My_test function in Python, But if you make the test.py a little bit, modify the following:

Import requestsdef my_test (name, age):    response = Requests.get ("http://www.baidu.com")    print ("Name:" +name)    print ("Age:" +age)    return "Success"

Without modifying the Java calling code, you will get the following exception information:

ImportError: No module named requests

Yes, that's what I'm talking about, because Jython can't cover all of the Python third-party libraries, so when we use the Requests class library in our Python file, it's obvious that the module error is not found. At this point we can execute the Python script file through the Runtime.getruntime () open process.

Execute script file with Runtime.getruntime () open process

In this way, you need to modify both the Python file and the Java calling code, and I'll modify it on top of the test.py:

Import Requestsimport sysdef my_test (name, age):    response = Requests.get ("http://www.baidu.com")    print ("URL: "+response.url"    print ("Name:" +name)    print ("Age:" +age)    return "Success" My_test (Sys.argv[1], sys.argv[ 2])

The biggest difference from the test.py code above is that the way we open the process here is actually operating on the Invisible DOS interface, so in Python code we need to get the arguments passed in the Java code in SYS.ARGV way.

Java Calling code section:

public static void Main (string[] args) {      string[] arguments = new string[] {"Python", "E:\\workspace\\pycharm_workspa ce\\weixincrawer\\test.py "," Huzhiwei "," + "};        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 ();        }      }

Result output:

url:http://www.baidu.com/name: huzhiweiage: 250

One thing to note here is that the process.waitfor () return value in Java code is 0 for the success of our call to the Python script, and the return value of 1 indicates the failure to invoke the Python script, which is exactly the opposite of the 0 and 1 definitions we see in the usual sense.

My Code:

#!/usr/bin/env python#-*-coding:utf-8-*-# @Date    : 2018-02-27# @Author  : zhangmingchengfrom PIL Import Imageimp ORT imagehashimport sysdef Get_hash (path):    image = Image.open (path)    h = str (imagehash.dhash (image))    print H    return H Get_hash (sys.argv[1])

Java

/** * Get image Dhash, delete image after fetch */@Overridepublic string Getdhash (String absolutepathname) {string dhash = ""; string[] arguments = new string[] {"Python", "/root/imagedhash/rest.py", Absolutepathname};try {process process = Runtim E.getruntime (). exec (arguments); BufferedReader in = new BufferedReader (New InputStreamReader (Process.getinputstream ())); String line = null;while (line = In.readline ())! = null) {Dhash = line;} In.close ();p rocess.waitfor ();} catch (Exception e) {e.printstacktrace ();} File File = new file (absolutepathname), if (File.exists () && file.isfile ()) {file.delete (); System.out.println (absolutepathname + "image dhash value =" + Dhash + ", delete image Success");} return Dhash;}

Transferred from: http://blog.csdn.net/hzw19920329/article/details/77509497

(go) Java invoke Python script

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.