【发布时间】:2013-07-01 05:01:09
【问题描述】:
我想使用os.mkfifo 进行程序之间的简单通信。我在循环读取 fifo 时遇到问题。
考虑这个玩具示例,我有一个阅读器和一个编写器使用先进先出。我希望能够在循环中运行阅读器以读取进入 fifo 的所有内容。
# reader.py
import os
import atexit
FIFO = 'json.fifo'
@atexit.register
def cleanup():
try:
os.unlink(FIFO)
except:
pass
def main():
os.mkfifo(FIFO)
with open(FIFO) as fifo:
# for line in fifo: # closes after single reading
# for line in fifo.readlines(): # closes after single reading
while True:
line = fifo.read() # will return empty lines (non-blocking)
print repr(line)
main()
作者:
# writer.py
import sys
FIFO = 'json.fifo'
def main():
with open(FIFO, 'a') as fifo:
fifo.write(sys.argv[1])
main()
如果我运行 python reader.py 和之后的 python writer.py foo,将打印“foo”,但 fifo 将关闭,阅读器将退出(或在 while 循环内旋转)。我希望 reader 留在循环中,所以我可以多次执行 writer。
编辑
我使用这个 sn-p 来处理这个问题:
def read_fifo(filename):
while True:
with open(filename) as fifo:
yield fifo.read()
但也许有一些更简洁的方法来处理它,而不是重复打开文件......
相关
【问题讨论】: