[英]Difference when executing linux command from terminal and java runtime process
I'm looking a way to write running log of python which is executed by java app via script.我正在寻找一种编写 python 运行日志的方法,该日志由 java 应用程序通过脚本执行。
Let's say my script is:假设我的脚本是:
import time
for x in range(120):
print("Running ", x)
time.sleep(1)
Here is my current solution:这是我目前的解决方案:
java
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));
Now the problem is output.txt
only has content whenever the python script is done executing so that I cannot tailf
the output file.现在的问题是
output.txt
只有在 python 脚本执行完毕时才有内容,因此我无法tailf
文件。
Meanwhile if I execute python script.py
and strace
command dirrectly from terminal, the output is exactly what I expected.同时,如果我直接从终端执行
python script.py
和strace
命令,则 output 正是我所期望的。
Can someone correct me if I did something wrong or have a another way to get python log?如果我做错了什么或有其他方法来获取 python 日志,有人可以纠正我吗?
Thanks in advance.提前致谢。
Use ProcessBuilder
instead of Runtime.exec()
.使用
ProcessBuilder
而不是Runtime.exec()
。 More details: When Runtime.exec() won't更多细节: 当 Runtime.exec() 不会
The following code will append to StringBuilder
object output of the script sb.append(line);
下面的代码将 append 到
StringBuilder
object output 的脚本sb.append(line);
. . It would not be difficult to write that content to a file.
将该内容写入文件并不难。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.