Dan*_*hov 7 io scala inputstream outputstream process
我开始并运行了一个 Scala 进程。
val dir = "/path/to/working/dir/"
val stockfish = Process(Seq("wine", dir + "stockfish_8_x32.exe"))
val logger = ProcessLogger(printf("Stdout: %s%n", _))
val stockfishProcess = stockfish.run(logger, connectInput = true)
Run Code Online (Sandbox Code Playgroud)
该进程读取和写入标准 IO(控制台)。如果进程已经启动,如何向进程发送字符串命令?
Scala 进程 API 具有 ProcessBuilder,它又具有一堆有用的方法。但是 ProcessBuilder 是在进程开始编写复杂的 shell 命令之前使用的。Scala 也有 ProcessIO 来处理输入或输出。我也不需要。我只需要向我的进程发送消息。
在 Java 中,我会做这样的事情。
String dir = "/path/to/working/dir/";
ProcessBuilder builder = new ProcessBuilder("wine", dir + "stockfish_8_x32.exe");
Process process = builder.start();
OutputStream stdin = process.getOutputStream();
InputStream stdout = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
new Thread(() -> {
try {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Stdout: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
Thread.sleep(5000); // it's just for example
writer.write("quit"); // send to the process command to stop working
writer.newLine();
writer.flush();
Run Code Online (Sandbox Code Playgroud)
它运作良好。我开始我的流程,从中获取 InputStream 和 OutputStream,并使用流与流程进行交互。
看来 Scala Process trait 没有提供写入它的方法。ProcessBuilder 在进程运行后就没有用了。而 ProcessIO 仅用于 IO 捕获和处理。
有什么方法可以写入 Scala 运行进程?
更新:
我不知道如何使用 ProcessIO 将字符串传递给正在运行的进程。我做了以下事情。
import scala.io.Source
import scala.sys.process._
object Sample extends App {
def out = (output: java.io.OutputStream) => {
output.flush()
output.close()
}
def in = (input: java.io.InputStream) => {
println("Stdout: " + Source.fromInputStream(input).mkString)
input.close()
}
def go = {
val dir = "/path/to/working/dir/"
val stockfishSeq = Seq("wine", dir + "/stockfish_8_x32.exe")
val pio = new ProcessIO(out, in, err => {})
val stockfish = Process(stockfishSeq)
stockfish.run(pio)
Thread.sleep(5000)
System.out.write("quit\n".getBytes)
pio.writeInput(System.out) // "writeInput" is function "out" which I have passed to conforming ProcessIO instance. I can invoke it from here. It takes OutputStream but where can I obtain it? Here I just pass System.out for example.
}
go
}
Run Code Online (Sandbox Code Playgroud)
当然它不起作用,我无法理解如何实现上面我的 Java 代码片段中的功能。如果有 Scala 代码的建议或片段可以解决我的问题,那就太好了。