进程的流标准输出

进程的流标准输出

本文介绍了来自 Scala 进程的流标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 scala Process 来启动一个 python 程序,并使用 ProcessLogger 从 python 程序中捕获标准输出.我看到python程序中的打印语句是在python程序完成后才打印出来的.有没有办法在执行时流式传输 python 打印语句?

I am using scala Process to kick off a python program and using ProcessLogger to capture the stdout from the python program. I see that the print statements in the python program are printed only after the python program completes. Is there a way to stream the python print statements as they are executed ?

import scala.sys.process.{ProcessLogger, _}

object TestProcessStdOut {
  def main(args: Array[String]) {
    var cmd = "python python_test.py";
    val process = Process(cmd).run(new ProcessLogger {
      override def out(s: => String) = println(s)

      override def buffer[T](f: => T) = ???

      override def err(s: => String) = ???
    })
  }
}

python_test.py

python_test.py

import time

print("print data 1")
time.sleep(2)
print("print data 2")
time.sleep(2)
print("print data 3")
time.sleep(2)

推荐答案

-u 告诉 python 不要在 scala 中缓冲你的输出会帮助你:

Tell python not to buffer your output in scala with -u will help you:

var cmd = "python -u python_test.py"

这篇关于来自 Scala 进程的流标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 16:50