0

I want to run a console command in my Java application which listens for incoming messages and logs to the console when it receives one. The console command runs fine when I execute it in the terminal. So I want to run the command and then do something when it outputs a line and after that keep on running and listen for other new messages. I tried this through the following code:

try {
    ProcessBuilder builder = new ProcessBuilder(PYTHON_PATH, YOWSUP_CLI_PATH, "demos", "-r", "-c", YOWSUP_CONFIG);
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = "";
    log.info("Started listening...");

    // It does nothing from here on
    while ((line = reader.readLine()) != null) {
        log.info(line);
    }
    log.info("Stopped listening.");
} catch (Exception e) {
    e.printStackTrace();
}

But when I run this code, it logs the "Started listening..." string, so I send a message to try it out but it doesn't log anything and just keeps on running without doing anything.

If I didn't explain something correctly just say so!

dylanvdb
  • 106
  • 18
  • 1
    Have a look at [this](http://stackoverflow.com/questions/19102989/java-is-there-a-way-to-run-a-system-command-and-print-the-output-during-executi/19103198#19103198), might also try using `ProcessBuilder#inheritIO` - I'm assuming you're trying to run a python command – MadProgrammer Dec 15 '15 at 01:57
  • @MadProgrammer Thanks! The '-u' parameter in my python command did the trick. – dylanvdb Dec 15 '15 at 02:07

2 Answers2

0

You can use rt.exec command like this:

try {               
            proc = rt.exec(command);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            int value=0;
            String line = null;
            while ((line = stdInput.readLine()) != null) {      
                System.out.println(line);
            }
            while ((line = stdError.readLine()) != null) {
                System.out.println(line);
            }
            proc.waitFor();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
GAVD
  • 1,977
  • 3
  • 22
  • 40
  • `ProcessBuilder` is generally preferred as it's more configurable, but the larger problem is python does some weird things on it's side, which some times prevents us from reading it's output, at least until it's exited – MadProgrammer Dec 15 '15 at 02:24
0

I fixed it using the "-u" parameter in my command, using this answer from MadProgrammer.

Pang
  • 9,564
  • 146
  • 81
  • 122
dylanvdb
  • 106
  • 18