0

I am trying to catch on fly Process output like below:

new Thread() {
    public void run() {

        final ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "myexec.exe");

        p = builder.start();

        InputStream i = p.getInputStream();
        Reader r = new InputStreamReader(i, "US-ASCII");

        int ch = 32;

        do {
           System.out.print(ch);
        } while ((ch = r.read()) != -1);

    }
}.start();

As I see, while Process is running ch == null, when Process is terminated all missing chars are suddenly printed.

How can I read output during Process running?

mynameismarcin
  • 117
  • 1
  • 3
  • 10

2 Answers2

0

You need to spawn additional thread to consume data from stream and wait for process to complete in main thread:

...
p = builder.start();

new Thread() {
    public void run() {
        InputStream i = p.getInputStream();
        Reader r = new InputStreamReader(i, "US-ASCII");

        int ch = 32;

        do {
            System.out.print(ch);
        } while ((ch = r.read()) != -1);
    }
}.start();

// wait for process to complete while thread above consumes data
p.waitFor();
hoaz
  • 9,883
  • 4
  • 42
  • 53
0

ok i got the solution. myexec.exe was an executable python file produced by py2exe.

due to How to flush output of Python print? i put sys.stdout.flush() after every print function and problem disappeared

Community
  • 1
  • 1
mynameismarcin
  • 117
  • 1
  • 3
  • 10