Runtime.exec() in java hangs because it is waiting for input from System.in
<p>I have the following short python program "test.py"</p>

<pre><code>n = int(raw_input())
print n
</code></pre>

<p>I'm executing the above program from following java program "ProcessRunner.java"</p>

<pre><code>import java.util.*;
import java.io.*;

public class ProcessRunner {
    public static void main(String[] args) {
        try {
            Scanner s = new Scanner(Runtime.getRuntime().exec("python test.py").getInputStream()).useDelimiter("\\A");
            System.out.println(s.next());
        }

        catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
</code></pre>

<p>Upon running the command,</p>

<pre><code>java ProcessRunner
</code></pre>

<p>I'm not able to pass a value 'n' in proper format to Python program and also the java run hangs. What is the proper way to handle the situation and pass a value to 'n' dynamically to python program from inside java program?</p>

<p>If I understand you correctly you want your java program to pass any output from your python script to System.out and any input into your java program to your python Script, right?</p>

<p>Have a look at the following program to get an idea how you could do this. </p>

<pre><code>import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ProcessRunner {

    public static void main(String[] args) {
        try {
            final Process process = Runtime.getRuntime().exec("/bin/sh");

            try (
                    final InputStream inputStream = process.getInputStream();
                    final InputStream errorStream = process.getErrorStream();
                    final OutputStream outputStream = process.getOutputStream()
            ) {

                while (process.isAlive()) {
                    forwardOneByte(inputStream, System.out);
                    forwardOneByte(errorStream, System.err);
                    forwardOneByte(System.in, outputStream);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void forwardOneByte(final InputStream inputStream,
                                       final OutputStream outputStream)
    throws IOException {
        if(inputStream.available() &lt;= 0) {
            return;
        }

        final int b = inputStream.read();
        if(b != -1) {
            outputStream.write(b);
            outputStream.flush();
        }
    }
}
</code></pre>

<p><strong>Note</strong> This code is just a concept demo. It will eat up your cpu and will not be able to cope with bigger amounts of throughput.</p>

java python multithreading process runtime.exec