Java调Python脚本实时输出print信息在Java中通过Runtime调用Python脚本时如果要实时输出脚本的print信息需要加上参数“-u”。否则Python默认会有输出缓存。python -h有说明测试脚本import sys import time looptime5 while looptime0: 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; ArrayListString cmd new ArrayListString(); cmd.add(python); cmd.add(-u); //!!!加上参数u让脚本实时输出!!! cmd.add(script/python/test.py); cmd.add(param1value1#param2value2) 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; }