背景
当前有个项目使用java开启子进程执行shell命令, 在shell命令中调用执行python文件。但是执行的时候通过以下代码无法获取python脚本的实时输出内容。而是在python执行完毕以后统一输出,这个和我想要的效果不一样。先上答案:执行python命令的时候加一个-u就能解决。
原先:
python3 /home/xquantitativefinance/python/run-script/1692605527995/sleep.py
修改后:
python3 -u /home/xquantitativefinance/python/run-script/1692605527995/sleep.py
try{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
String packReadLine = "";
while (null != (packReadLine = bufferedReader.readLine()) || process.isAlive()) {
recorder.recordLog(packReadLine);
}
bufferedReader.close();
int packExitCode = process.waitFor();
recorder.setExeCode(packExitCode);
}catch(Exception e) {
LOGGER.error("获取进程输出内容异常", e);
}
测试python
# encodings: utf-8
import time
if __name__ == "__main__":
# 每两秒输出一个正在执行日志
for i in range(10):
print('正在执行')
time.sleep(2)