0

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?

2 Answers 2

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"); 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.