fifoをPythonのstdinにリダイレクトする

fifoをPythonのstdinにリダイレクトする
$ mkfifo mypipe
$ echo "hello redirection" > mypipe
$ cat < mypipe
hello redirection

Pythonを使って上記のタスクを実行しようとすると問題があります。

# pyecho.py
with open("/dev/stdin", "r") as f:
    print(f.read())
$ python3 pyecho.py < mypipe

パイプに2回書き込まないと終了しません。

$ echo "hello redirection" > mypipe
$ echo "hello redirection" > mypipe

しかし、Pythonをループに入れると

# pyecho.py
while True:
    with open("/dev/stdin", "r") as f:
        print(f.read())

その後、最初の反復(2回の書き込みが必要)の後、期待どおりに動作します。

ベストアンサー1

おすすめ記事