Passing data from Java process to a python script

青春壹個敷衍的年華 提交于 2020-04-30 06:42:31

问题


I call a external Python script as Java process and want to send data to this. I create a process and try to send a string. Later the python script should wait for a new input from Java, work with this data and wait again(while true loop).

Python Code (test.py):

input = input("")
print("Data: " + input)

Java Code:

Process p = Runtime.getRuntime().exec("py ./scripts/test.py");

BufferedWriter out = new BufferedWriter(new
        OutputStreamWriter(p.getOutputStream()));
BufferedReader stdInput = new BufferedReader(new
        InputStreamReader(p.getInputStream()));

System.out.println("Output:");
String s = null;
out.write("testdata");
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

The process and output of simple prints works, but not with input and BufferedWriter. Is it possible to send data to this python input with a Java process?

I read from other solutions:

  • create a Python listener and send messages to this script
  • import the external script to Jython and pass data

Are this better solutions to handle my problem?


回答1:


use Process class in java

what is process class ? this class is used to start a .exe or any script using java

How it can help you Create your python script to accept command line variables and send your data from java class to python script.

for Example:

        System.out.println("Creating Process"); 

        ProcessBuilder builder = new ProcessBuilder("my.py"); 
        Process pro = builder.start(); 

        // wait 10 seconds 
        System.out.println("Waiting"); 
        Thread.sleep(10000); 

        // kill the process 
        pro.destroy(); 
        System.out.println("Process destroyed"); 



回答2:


Later the python script should wait for a new input from Java

If this has to happen while the python process is still a subprocess of the Java process, then you will have to use redirection of I/O using ProcessBuilder.redirect*( Redirect.INHERIT ) or ProcessBuilder.inheritIO(). Like this:

Process p = new ProcessBuilder().command( "python.exe", "./scripts/test.py" )
        .inheritIO().start();

If the python process is going to be separate (which is not the case here, I think) then you will have to use some mechanism to communicate between them like client/server or shared file, etc.



来源:https://stackoverflow.com/questions/59766926/passing-data-from-java-process-to-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!