Converting interactive shell output to plain text

Ethan Onweller :

I am trying to view the temperature table for my CPU on my Linux machine with Java. This bit of code will display the shell output for other commands, ls, cat file, but will not display watch sensors as it returns an interactive output. Is there a way I can convert it to plain text somehow?

Error: [/usr/bin/watch, sensors]

Error opening terminal: unknown.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class tempapp{

public static void main (String args[]) throws IOException, InterruptedException {
    //build command
    List<String> commands = new ArrayList<String>();
    commands.add("/usr/bin/watch");
    //args
    commands.add("sensors");
    System.out.println(commands);

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(new File("/home/ethano"));
    pb.redirectErrorStream(true);
    Process process = pb.start();

    //Read output
    StringBuilder out = new StringBuilder();
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null, previous = null;
    while ((line = br.readLine()) != null)
        if (!line.equals(previous)) {
            previous = line;
            out.append(line).append('\n');
            System.out.println(line);
        }

    //Check result
    if (process.waitFor() == 0){
        System.out.println("\n success");
        System.exit(0);
    }

    //weird termination
    System.err.println(commands);
    System.err.println(out.toString());
    System.exit(1);
    }
}
Bart van Oort :

All that watch does is call the command it is given (sensors in this case) once every two seconds. You can simply have your application emulate this behaviour by calling /usr/bin/sensors in a for-loop once every two seconds (or however many times you need), therefore omitting the need to read interactive shell output.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=215911&siteId=1