IPC (inter process communication) between python and java

前端 未结 6 1245
暖寄归人
暖寄归人 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 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()
    

提交回复
热议问题