.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使管道 在父端 行缓冲。



