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

了解Popen.communicate

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

了解Popen.communicate

.communicate()

写入输入(在这种情况下没有输入,因此它只是关闭子流程的stdin来指示子流程没有更多的输入),读取所有输出,然后等待子流程退出。

子进程中引发了EOFError异常

raw_input()
(它是预期数据,但得到了EOF(无数据))。

p.stdout.read()
永远挂起,因为它试图在孩子等待导致死锁的输入()的同时读取孩子的 所有 输出
raw_input()

为了避免死锁,您需要异步读取/写入(例如,通过使用线程或select)或确切地知道何时/多少读取/写入,例如:

from subprocess import PIPE, Popenp = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)print p.stdout.readline(), # read the first linefor i in range(10): # repeat several times to show that it works    print >>p.stdin, i # write input    p.stdin.flush() # not necessary in this case    print p.stdout.readline(), # read outputprint p.communicate("nn")[0], # signal the child to exit,         # read the rest of the output,          # wait for the child to exit

注意:如果读/写不同步,这是非常脆弱的代码;它陷入僵局。

谨防块缓冲的问题(这是通过使用解决“-u”标志,关闭缓存为标准输入,标准输出
的孩子
)。

bufsize=1
使管道 在父端 行缓冲。



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

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

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