简体   繁体   中英

How to create a 2 way communication between Java and Python

I am pretty new to both Java and Python, although I have some experience in programming. For an assignement, I need to create a program which uses Java in some way. My project would use Java as an UX, and Python for signal processing and feature extraction, since it has some good tools for that. However, my question is how to establish communication between both programse. Maybe this question has been asked before, but since I do not know the best terms, I could not find answers.

In my Java Program, I can get the file path to a.csv file, send it to Python, and Python returns the original signals and processed signals. For that, I wrote:

private static void sendPython(String path, JTextField console)
    {
        String pathPython = "C:\\Users\\gonca\\Desktop\\untitled0.py";
        String [] cmd = new String[3];
        cmd[0] = "python";
        cmd[1] = pathPython;
        cmd[2] = path;
        Runtime r = Runtime.getRuntime();
        try
        {
            Process p = r.exec(cmd);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String s = "";
            while((s = in.readLine()) != null)
            {
                console.setText(s);
            }
        }
        catch (IOException e)
        {
            console.setText("Unable to run python script");
        }
        
    }

I was thinking of having the py script output the signals in separated lines, with values separated by "," or ";", and using the BufferedRead to read each line, separate the values and create a new ArrayList from the separated values. However, before starting working harder to do that, I would like to know if that is the best way to proceed, or is there a more efficient way to do it.

There are more ways to do that:

Solution 1:

Use the python library from java with System.loadLibrary , and call the python method. (here is an example using C/C++: Calling a python method from C/C++, and extracting its return value )

Solution 2:

Launch python as another process, and use D-Bus (or something similar) to communicate with it.

Since you have not mentioned how robust your application is I can think of a solution which can be used if you are planning for a higher level architecture.

  1. Create a python based web application (HTTP server) with all logic to process your files.
  2. Create a java app which can communicate via HTTP python server to get the CSV processed information.

Try to avoid Runtime execution of commands with in your codes that faces user as if it not is properly managed there is always a chance for security breach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM