我在使用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
答案 0 :(得分:4)
使用-i
标志调用Python。
如果未指定脚本,则无论stdin是否为终端,都会导致Python以交互模式运行。指定脚本后,这会导致Python在执行脚本后进入交互模式。
答案 1 :(得分:1)
更新:这个答案完全错误,请参阅评论中的讨论
foreach($cart_array as $cart_value){
foreach($products_array[$cart_value->chemID]]["barrels"] as $products_value){
if($products_value->catID == $cart_value->catID){
$products_value->count=$cart_value->count;
}
}
}
#Set count=0 in all barrels in products_array
foreach($products_array as $value1){
foreach($value1["barrels"] as $value2){
if(!isset($value2->count)){
$value2->count = 0;
}
}
}
已经以交互模式运行。
python
(或-i
命令),则 python -i some_script.py
标志非常有用。它不适用于您的情况。
//仅此处输出打印到屏幕
Your issue is the block-buffering mode if the output is not a tty。通过-u
command-line flag to python
, to unbuffer its standard streams。或致电sys.stdout.flush()
after print
。