【问题标题】:Difference when executing linux command from terminal and java runtime process从终端和java运行时进程执行linux命令时的区别
【发布时间】:2019-10-02 14:03:57
【问题描述】:

我正在寻找一种方法来编写由 java 应用程序通过脚本执行的 python 运行日志。

假设我的脚本是:

import time

for x in range(120):
  print("Running ", x)
  time.sleep(1)

这是我目前的解决方案:

  1. 使用java触发脚本
String cmd = "python script.py";
var process = Runtime.getRuntime().exec(cmd, null, new File(sandboxPath));
  1. 将日志写入新文件:
String traceLogCmd = String.format("strace -p %s -s 9999 -e trace=write -o output.txt", process.pid());
Runtime.getRuntime().exec(traceLogCmd, null, new File(sandboxPath));

现在的问题是 output.txt 只有在 python 脚本执行完毕时才有内容,所以我不能 tailf 输出文件。

同时,如果我直接从终端执行python script.pystrace 命令,输出正是我所期望的。

如果我做错了什么或有其他方法获取 python 日志,有人可以纠正我吗?

提前致谢。

【问题讨论】:

    标签: java shell


    【解决方案1】:

    使用ProcessBuilder 而不是Runtime.exec()。更多详情:When Runtime.exec() won't

    以下代码将附加到脚本sb.append(line);StringBuilder 对象输出。将该内容写入文件并不难。

    Process p = new ProcessBuilder("sh", "-c", "python", "path-to-your-script").start();
    String result = getCommandResult(p.getInputStream());
    
    private static String getCommandResult(InputStream stream) throws IOException {
    
        StringBuilder sb = new StringBuilder();
        try (InputStreamReader isr = new InputStreamReader(stream);
             BufferedReader in = new BufferedReader(isr)) {
    
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString().trim();
    }
    

    【讨论】:

    • 试过这个并用log.info(line)替换sb.append(line),但没有任何记录
    • 查看我更新的帖子。出于测试目的,请打印到控制台line。如果代码在 while 循环中,则必须读取一些内容。
    • 似乎它甚至不在while循环中。我在 while 循环的开头记录了一个随机字符串,但没有打印出来
    最近更新 更多