Interaction between Java App and Python App

前端 未结 6 1283
余生分开走
余生分开走 2021-01-20 11:33

I have a python application which I cant edit its a black box from my point of view. The python application knows how to process text and return processed text. I have anoth

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 11:48

    I don't know nothing about Jython and the like. I guess it's the best solution if you can execute two programs without executing a new process each time the Java app needs to transform text. Anyway a simple proof of concept is to execute a separate process from the Java App to make it work. Next you can enhance the execution with all that tools.

    Executing a separate process from Java

    String[] envprops = new String[] {"PROP1=VAL1", "PROP2=VAL2" };
    Process pythonProc = Runtime.getRuntime().exec(
       "the command to execute the python app", 
        envprops, 
        new File("/workingdirectory"));
    
    // get an outputstream to write into the standard input of python
    OutputStream toPython = pythonProc.getOutputStream();
    
    // get an inputstream to read from the standard output of python
    InputStream fromPython = pythonProc.getInputStream();
    
    // send something
    toPython.write(.....);
    // receive something
    fromPython.read(....);
    

    Important: chars are NOT bytes

    A lot of people understimate this.

    Be careful with char to byte conversions (remember Writers/Readers are for chars, Input/OutputStreams are for bytes, encoding is necesary for convertir one to another, you can use OuputStreamWriter to convert string to bytes and send, InputStreamReader to convert bytes to chars and read them).

提交回复
热议问题