java - 将交互式 shell 输出转换为纯文本
问题描述
我正在尝试使用 Java 在我的 Linux 机器上查看我的 CPU 的温度表。这段代码将显示其他命令的 shell 输出,ls
, cat 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);
}
}
解决方案
所做的只是每两秒watch
调用一次给出的命令(在这种情况下)。你可以简单地让你的应用程序通过每两秒sensors
调用一次 for 循环来模拟这种行为(或者你需要多少次),因此不需要读取交互式 shell 输出。/usr/bin/sensors
推荐阅读
- html - Bootstrap 3中的最后一列居中
- python - 对使用 Pyspark mllib ALS/MatrixFactorizationModel 的用户子集的建议
- java - 如何忽略多个 JUnit 测试类?
- php - 如何修复 Laradock 上的 SQLSTATE[HY000] [2002] Connection denied (SQL: select * from `categories` where `enable` = 1)?
- file-upload - 是否可以将环境变量“GOOGLE_APPLICATION_CREDENTIALS”设置为 Flowground 中上传的 JWT 文件?
- list - 如何使用 python2 在列表中提取 2 或 3 位小数?
- html - 如何保持数据列表在下拉菜单中显示项目?
- codeigniter - Codeigniter count_all_results() 和 result() with group_by, join, where vs
- c# - c# DataGridView DataGridViewTextBoxCell中的FindTextLocation或文本索引
- azure - 使用应用程序网关的 azure api 管理转换 URL 标头