在通过stdin库启动进程时,如何获得连接到stdout (以及与stdout和stderr连接的可读流)的某种可写流?下面是不起作用的代码(甚至不打印调试消息)
val p = Process("wc -l")
val io = BasicIO.standard(true)
val lines = Seq("a", "b", "c") mkString "\n"
val buf = lines.getBytes(StandardCharsets.UTF_8)
io withInput { w =>
println("Writing")
w.write(buf)
}
io withOutput { i =>
val s = new BufferedReader(new InputStreamReader(i)).readLine()
println(s"Output is $s")
}发布于 2018-11-30 13:49:19
你有几个问题。
首先,在您的代码段中,您从不将进程与io连接起来,也从不运行它。可以这样做:p run io。
第二,withInput & withOutput方法返回一个新的ProcessIO --它们不会改变实际情况,而且由于您没有将这些调用的返回分配给一个变量,所以您什么也不做。
下面的代码片段修复了这两个问题,希望它对您有用。
import scala.io.Source
import scala.sys.process._
import java.nio.charset.StandardCharsets
val p = Process("wc -l")
val io =
BasicIO.standard(true)
.withInput { w =>
val lines = Seq("a", "b", "c").mkString("", "\n", "\n")
val buf = lines.getBytes(StandardCharsets.UTF_8)
println("Writing")
w.write(buf)
w.close()
}
.withOutput { i =>
val s = Source.fromInputStream(i)
println(s"Output is ${s.getLines.mkString(",")}")
i.close()
}
p run io请不要怀疑地要求澄清。
PS:打印"Output is 3" -(感谢Dima指出错误)。
https://stackoverflow.com/questions/53557874
复制相似问题