IPC (inter process communication) between python and java

前端 未结 6 1200
暖寄归人
暖寄归人 2020-12-31 04:18

First, a little explanation of why I\'m asking this question in the first place: I\'m writing a python program (with a wxPython gui) that needs to call a Java AWT p

相关标签:
6条回答
  • 2020-12-31 04:55

    Named pipes could be the answer for you. See: Create a temporary FIFO (named pipe) in Python?

    0 讨论(0)
  • 2020-12-31 04:58

    This is the opensource solution Google uses to do IPC between Java and Python. https://code.google.com/p/protobuf/

    Recommended.

    0 讨论(0)
  • 2020-12-31 05:00

    IPC using subprocess from in python

    IPC.java file here java code will receive number and send square of it.

    import java.util.Scanner;
    
    public class IPC {
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            String data="";
            while(scanner.hasNext()){
                // Receive data from Python code 
                data = scanner.nextLine();
    
                // Process data (calculate square)
                int x = Integer.parseInt(data);
                int square = x*x;
    
    
                // Send data to python code
                System.out.println(square);
            }
            scanner.close();
        }
    }
    

    IPC.py file

    import subprocess
    subprocess.run(["javac", "IPC.java"])
    proc = subprocess.Popen(["java", "IPC"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    for i in range(10):
        # Send to java code
        proc.stdin.write(b'%d\n' % i)
        proc.stdin.flush()
        proc.stdout.flush()
    
        # Receive data from java code
        output = proc.stdout.readline()
        print (output.rstrip())
    proc.communicate()
    
    0 讨论(0)
  • 2020-12-31 05:02

    I had a similar situation where I had to communicate between a Java process and a Linux process. I used named pipes.

    Try mkfifo() implementation in python.

    0 讨论(0)
  • 2020-12-31 05:09

    I attempted to code a solution using pipes but it seems that they just aren't well suited to sending multiple messages back and forth with potentially large data attached. Rather, they seem ideal for opening a "worker" style program that runs, responds, and dies.

    Looking into socket programming, I found a fantastic resource here: https://web.archive.org/web/20080913064702/http://www.prasannatech.net/2008/07/socket-programming-tutorial.html

    The tutorial presents TCP and UDP variants of a simple chat program written in 4 languages. I ended up using and modifying the TCP Java client and Python server.

    0 讨论(0)
  • 2020-12-31 05:10

    Use subprocess.Popen to start the Java process and establish pipes to communicate with it. For serializing and deserializing data efficiently in a language-neutral, platform-neutral, extensible way, take a look at Protocol Buffers (contributed to by Jon Skeet!).

    0 讨论(0)
提交回复
热议问题