Java调Python脚本实时输出print信息

📅 2026/7/28 15:46:10 👁️ 阅读次数 📝 编程学习
Java调Python脚本实时输出print信息

Java调Python脚本实时输出print信息

在Java中,通过Runtime调用Python脚本时,如果要实时输出脚本的print信息,需要加上参数“-u”。否则Python默认会有输出缓存。
python -h有说明:

测试脚本:

import sys import time looptime=5 while looptime>0: print "Hello World! " + str(looptime) print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) looptime -= 1 time.sleep(3)

Java代码:

public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); Process pro = null; ArrayList<String> cmd = new ArrayList<String>(); cmd.add("python"); cmd.add("-u"); //!!!==加上参数u让脚本实时输出==!!! cmd.add("script/python/test.py"); cmd.add("param1=value1#param2=value2") pro = runtime.exec(cmd.toArray(new String[0])); Thread oThread = printMessage(pro.getInputStream(), pro.getErrorStream()); oThread.join(); int status = pro.waitFor(); System.out.println("Script exit code is:"+status); } public Thread printMessage(final InputStream out, final InputStream err) { Thread thread = new Thread(new Runnable() { public void run() { Reader outReader = new InputStreamReader(out); BufferedReader outBf = new BufferedReader(outReader); Reader errReader = new InputStreamReader(err); BufferedReader errBf = new BufferedReader(errReader); String outLine = null, errLine = null; try { while ((outLine = outBf.readLine()) != null || (errLine = errBf.readLine()) != null) { if(outLine!=null) { outLine = OmpUtils.dateAsString("yyyy-MM-dd HH:mm:ss.S", new Date()) + ">>" + outLine + "\n"; System.out.print("[OUT]------>>"+ outLine); } if(errLine!=null) { errLine = OmpUtils.dateAsString("yyyy-MM-dd HH:mm:ss.S", new Date()) + ">>" + errLine + "\n"; System.out.print("[ERR]------>>"+ errLine); } outLine = errLine = null; } outBf.close(); errBf.close(); } catch (IOException e) { logger.error("Error when read", e); try { outBf.close(); errBf.close(); } catch (IOException e1) { logger.error("Error when close", e1); } } } }); thread.start(); return thread; }