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

使用Python的交互式输入/输出

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

使用Python的交互式输入/输出

在Linux上针对此问题的两种解决方案:

第一个是使用文件将输出写入其中,并同时读取输出:

from subprocess import Popen, PIPEfw = open("tmpout", "wb")fr = open("tmpout", "r")p = Popen("./a.out", stdin = PIPE, stdout = fw, stderr = fw, bufsize = 1)p.stdin.write("1n")out = fr.read()p.stdin.write("5n")out = fr.read()fw.close()fr.close()

第二,正如JF Sebastian提供的那样,是使用fnctl模块使p.stdout和p.stderr管道不阻塞:

import osimport fcntlfrom subprocess import Popen, PIPE  def setNonBlocking(fd):    """    Set the file description of the given file descriptor to non-blocking.    """    flags = fcntl.fcntl(fd, fcntl.F_GETFL)    flags = flags | os.O_NonBLOCK    fcntl.fcntl(fd, fcntl.F_SETFL, flags)p = Popen("./a.out", stdin = PIPE, stdout = PIPE, stderr = PIPE, bufsize = 1)setNonBlocking(p.stdout)setNonBlocking(p.stderr)p.stdin.write("1n")while True:    try:        out1 = p.stdout.read()    except IOError:        continue    else:        breakout1 = p.stdout.read()p.stdin.write("5n")while True:    try:        out2 = p.stdout.read()    except IOError:        continue    else:        break


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

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

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