当调用Python作为子进程时,我可以强制它以交互模式运行吗



我在mac上使用Scala,我想创建一个Python解释器作为程序交互的子进程。我一直在ProcessIO中使用Process,但python坚持在非交互式模式下运行。所以它只在我关闭它的输入并终止进程后才执行任何操作。有没有办法强制它在交互模式下运行,这样我就可以保持Python进程的活力并与之交互?这个示例代码(我正在粘贴到Scala repl中)显示了问题:

import scala.sys.process._
import scala.io._
import java.io._
import scala.concurrent._
val inputStream = new SyncVar[OutputStream];
val process = Process("python").run(pio)
val pio = new ProcessIO(
    (stdin: OutputStream) => {
        inputStream.put(stdin)
    },
    (stdout: InputStream) => {
        while (true) {
            if (stdout.available > 0){
                Source.fromInputStream(stdout).getLines.foreach(println)
            }
        }
    },
    stderr => Source.fromInputStream(stderr).getLines.foreach(println),
    daemonizeThreads=true
    )
def write(s: String): Unit = {
    inputStream.get.write((s + "n").getBytes)
    inputStream.get.flush()
}
def close(): Unit = {
    inputStream.get.close
}
write("import sys")
write("try: print 'ps1:', sys.ps1")
write("except: print 'no ps1'")
close  // it's only here that output prints to the screen

使用-i标志调用Python。

当没有指定脚本时,无论stdin是否显示为终端,这都会导致Python在交互模式下运行。当指定脚本时,这会导致Python在执行脚本后进入交互模式。

最新更新