[英]Difference when executing linux command from terminal and java runtime process
我正在尋找一種編寫 python 運行日志的方法,該日志由 java 應用程序通過腳本執行。
假設我的腳本是:
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
命令,則 output 正是我所期望的。
如果我做錯了什么或有其他方法來獲取 python 日志,有人可以糾正我嗎?
提前致謝。
使用ProcessBuilder
而不是Runtime.exec()
。 更多細節: 當 Runtime.exec() 不會
下面的代碼將 append 到StringBuilder
object output 的腳本sb.append(line);
. 將該內容寫入文件並不難。
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.