【问题标题】:Converting interactive shell output to plain text将交互式 shell 输出转换为纯文本
【发布时间】:2020-06-24 17:05:11
【问题描述】:

我正在尝试使用 Java 在我的 Linux 机器上查看我的 CPU 的温度表。这段代码将显示其他命令的 shell 输出,lscat file,但不会显示 watch sensors,因为它返回一个交互式输出。有没有办法可以将其转换为纯文本?

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);
    }
}

【问题讨论】:

    标签: java linux shell command-line


    【解决方案1】:

    watch 所做的只是每两秒调用一次给定的命令(在本例中为sensors)。您可以简单地让您的应用程序通过在 for 循环中每两秒调用一次 /usr/bin/sensors 来模拟此行为(或您需要的多次),因此无需读取交互式 shell 输出。

    【讨论】:

    • 在这里我试图让它变得比必要的更难。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多