![](/img/trans.png)
[英]Python interactive shell not responding to input when run in subprocess
[英]When calling Python as a subprocess, can I force it to run in interactive mode?
我在使用 Scala 的 Mac 上,我想创建一个 Python 解释器作为我的程序与之交互的子进程。 我一直在使用 Process 和 ProcessIO,但 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在执行脚本后进入交互模式。
更新:此答案是完全错误的,请参阅评论中的讨论
python
已经以交互模式运行。
如果必须先运行脚本,例如python -i some_script.py
(或-c
命令),则-i
标志很有用。 它不适用于您的情况。
//只有在这里输出打印到屏幕上
如果输出不是tty,那么您的问题是块缓冲模式 。 将-u
命令行标志传递给python
,以取消缓冲其标准流 。 或在print
之后调用sys.stdout.flush()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.