我正在寻找一种方法来编写由java应用程序通过脚本执行的python运行日志。
假设我的脚本是:
import time
for x in range(120):
print("Running ", x)
time.sleep(1)
这是我当前的解决方案:
- 使用
java
触发脚本
String cmd = "python script.py";
var process = Runtime.getRuntime().exec(cmd, null, new File(sandboxPath));
- 将日志写入新文件:
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.py
和 strace
命令,输出正是我所期望的。
如果我做错了什么,有人可以纠正我,或者有其他方法来获取 python 日志吗?
提前致谢。
最佳答案
使用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();
}
关于java - 从终端执行linux命令和java运行时进程的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58203168/