我想用os.mkfifo http://docs.python.org/2/library/os.html#os.mkfifo用于程序之间的简单通信。我在循环读取 fifo 时遇到问题。
考虑这个玩具示例,其中我有一个读取器和一个写入器使用 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
环形)。我希望读者留在循环中,这样我就可以多次执行作者。
Edit
我用这个片段来处理这个问题:
def read_fifo(filename):
while True:
with open(filename) as fifo:
yield fifo.read()
但也许有一些更简洁的方法来处理它,而不是重复打开文件......
Related
- 让 readline 在 FIFO 上阻塞 https://stackoverflow.com/questions/2406365/getting-readline-to-block-on-a-fifo
您无需重复重新打开该文件。您可以使用 select 来阻止,直到数据可用。
with open(FIFO_PATH) as fifo:
while True:
select.select([fifo],[],[fifo])
data = fifo.read()
do_work(data)
在此示例中,您不会读取 EOF。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)