在java中使用子进程调用python输出无法实时获取解决

背景

当前有个项目使用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)   
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值