我正在使用scala Process来启动python程序并使用ProcessLogger从python程序中捕获stdout.我看到python程序中的print语句只在python程序完成后打印.有没有办法在执行时传输python print语句?
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) = ???
})
}
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud) import java.util.concurrent.Executors
import scala.concurrent.{ExecutionContext, Future}
object TestInheritableThreadLocal {
def main(args: Array[String]): Unit = {
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(2))
val tl: InheritableThreadLocal[String] = new InheritableThreadLocal[String]()
tl.set("InitialValue")
Future {
println("111 " + Thread.currentThread() + tl.get())
Future {
println("222 " + Thread.currentThread() + tl.get())
}
}
Thread.sleep(3000)
Future {
tl.set("NewInitialValue")
println("333 " + Thread.currentThread() + tl.get())
Future {
println("444 " + Thread.currentThread() + tl.get())
}
Thread.sleep(3000)
}
}
}
Run Code Online (Sandbox Code Playgroud)
产量
111 Thread[pool-1-thread-1,5,main]InitialValue
222 Thread[pool-1-thread-2,5,main]InitialValue
333 Thread[pool-1-thread-1,5,main]NewInitialValue
444 Thread[pool-1-thread-2,5,main]InitialValue
Run Code Online (Sandbox Code Playgroud)
我期待输出的最后一行中的"NewInitialValue",因为333 Thread产生了Thread 444,而tl是一个可继承的本地线程.
是什么导致了这个问题,如何解决?