Interprocess communication between Python and Java
For my Research work I need to communicate between Python and Java/Scala application.
The first idea was to use WebSockets. It is universal and flexible. Additionally communication is easy. There are many ways to implement it:
- ws4py - A WebSocket package for Python
- Python Tornado Web Server With WebSockets
- websocket-client 0.15.0
- Super simple websockets client/server using Python
Implementation would be easy, but we are using customized version of Python, which is included in GNAT Programming Studio. Some libraries (required for WebSockets) are excluded (because of legal reasons) and we wouldn't be able to redistribute it along with missing packages. Thus, we decide to implement interprocess communication through pipes.
From Python to Java
The communication is one direction: from Python app to Java app. Every message is one line of text (ultimately: json format). E.g.: "text\r\n". To close communication, we send message: "x\r\n".
This is sample Java app, which write received messages to file result.txt:
And here is sample Python app, which sends messages to Java app:
From Java to Python
We can also communicate in opposite direction: from Java app to Python app. To do that we just need to change reading to writing in Java app and writing to reading in Python app.
Change in Java app is simple: we just write to standard output.
In Python app we need to create stdout pipe and read instead of write:
In this scenario, both processes are managed by Python app. You can also do it in opposite direction and invoke Python app from Java app.