栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

与popen python一起使用时,输入命令似乎不起作用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

与popen python一起使用时,输入命令似乎不起作用

您需要从scala启动时开始读取所有行,然后以新行输入命令,并在获得以下两行输出之后:

from subprocess import Popen, PIPEwith Popen(["scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala:    for line in scala.stdout:        print(line)        if not line.strip(): break    while True:        command = input("Enter scala command >>> n")        scala.stdin.write(command+"n")        scala.stdin.flush()        for line in scala.stdout: if not line.strip():     break print(line)

运行示例:

Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).Type in expressions to have them evaluated.Type :help for more information.Enter scala command >>> 3+4scala> 3+4res0: Int = 7Enter scala command >>> 4 * 4scala> 4 * 4res1: Int = 16Enter scala command >>> 16 / 4scala> 16 / 4res2: Int = 4

为了使它能够通过使用不带缓冲区的bash运行,似乎可以解决输出问题:

from subprocess import Popen, PIPEwith Popen(["unbuffer", "-p","scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala:    for line in scala.stdout:        print(line)        if not line.strip(): break    while True:        command = input("Enter scala command >>> ")        scala.stdin.write(command+"n")        scala.stdout.flush()        for line in scala.stdout: if not line.strip():     break print(line)

如果您使用的是Mac Os x,则可能应该使用:

with Popen(["script", "-q", "/dev/null", "scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala:

从bash:

        print(line)## -- End pasted text --Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).Type in expressions to have them evaluated.Type :help for more information.Enter scala command >>> 4 + 2scala> 4 + 2res0: Int = 6Enter scala command >>> 4 * 12scala> 4 * 12res1: Int = 48Enter scala command >>> 100 // 25scala> 100 // 25res2: Int = 100Enter scala command >>>

有关外壳缓冲区问题的更多信息:

  • http://www.pixelbeat.org/programming/stdio_buffering/
  • https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517199.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号