プログラム間の簡単な通信に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
and laterを実行するとpython writer.py foo
、「foo」が出力されますが、fifo は閉じられ、リーダーは終了します (またはwhile
ループ内でスピンします)。リーダーをループに留めておきたいので、ライターを何度も実行できます。
編集
このスニペットを使用して問題を処理します。
def read_fifo(filename):
while True:
with open(filename) as fifo:
yield fifo.read()
しかし、ファイルを繰り返し開くのではなく、もっとうまく処理する方法があるかもしれません...
関連している