将 Python 作为子进程调用时,是否可以强制它以交互模式运行? [英] When calling Python as a subprocess, can I force it to run in interactive mode?
问题描述
我在使用 Scala 的 Mac 上,我想创建一个 Python 解释器作为我的程序与之交互的子进程.我一直在使用 Process 和 ProcessIO,但 python 坚持在非交互模式下运行.因此,它只会在我关闭其输入并终止进程后执行任何操作.有没有办法强制它以交互模式运行,以便我可以保持 Python 进程的活动状态并与之交互?此示例代码(我将其粘贴到 Scala repl 中)显示了问题:
I'm on a mac using Scala, and I want to create a Python interpreter as a subprocess that my program interacts with. I've been using Process with a ProcessIO, but python insists on running in non-interactive mode. So it only does anything after I close down its input and kill the process. Is there a way to force it to run in interactive mode, so that I can keep the Python process alive and interact with it? This sample code (which I'm pasting into a Scala repl) shows the problem:
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.
Invoke Python with the -i
flag.
当未指定脚本时,这会导致 Python 以交互模式运行,无论 stdin 是否显示为终端.当指定脚本时,这会导致 Python 在执行脚本后进入交互模式.
When no script is specified, this causes Python to run in interactive mode whether or not stdin appears to be a terminal. When a script is specified, this causes Python to enter interactive mode after executing the script.
这篇关于将 Python 作为子进程调用时,是否可以强制它以交互模式运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!