Skip to main content
 首页 » 编程设计

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

2025年05月04日33飞鱼

我在 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。

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