您需要从scala启动时开始读取所有行,然后以新行输入命令,并在获得以下两行输出之后:
from subprocess import Popen, PIPEwith Popen(["scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala: for line in scala.stdout: print(line) if not line.strip(): break while True: command = input("Enter scala command >>> n") scala.stdin.write(command+"n") scala.stdin.flush() for line in scala.stdout: if not line.strip(): break print(line)运行示例:
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).Type in expressions to have them evaluated.Type :help for more information.Enter scala command >>> 3+4scala> 3+4res0: Int = 7Enter scala command >>> 4 * 4scala> 4 * 4res1: Int = 16Enter scala command >>> 16 / 4scala> 16 / 4res2: Int = 4
为了使它能够通过使用不带缓冲区的bash运行,似乎可以解决输出问题:
from subprocess import Popen, PIPEwith Popen(["unbuffer", "-p","scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala: for line in scala.stdout: print(line) if not line.strip(): break while True: command = input("Enter scala command >>> ") scala.stdin.write(command+"n") scala.stdout.flush() for line in scala.stdout: if not line.strip(): break print(line)如果您使用的是Mac Os x,则可能应该使用:
with Popen(["script", "-q", "/dev/null", "scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala:
从bash:
print(line)## -- End pasted text --Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).Type in expressions to have them evaluated.Type :help for more information.Enter scala command >>> 4 + 2scala> 4 + 2res0: Int = 6Enter scala command >>> 4 * 12scala> 4 * 12res1: Int = 48Enter scala command >>> 100 // 25scala> 100 // 25res2: Int = 100Enter scala command >>>
有关外壳缓冲区问题的更多信息:
- http://www.pixelbeat.org/programming/stdio_buffering/
- https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe



