無限に実行されるプログラムに入力を提供する方法は? [閉鎖]

無限に実行されるプログラムに入力を提供する方法は? [閉鎖]

無限に実行され、入力を受け取り、出力を投げるPythonプログラムがあります。実行中のPythonスクリプトに入力を提供するbashプログラムを作成したいと思います。それでは、プログラムの実行中にどのようにプログラムに入力を提供しますか?

ベストアンサー1

簡単な方法は、名前付きパイプを使用することです。

# Choosing a unique, secure name for the pipe left as an exercise
PIPE=/tmp/feed-data-to-program

# Create the named pipe
mkfifo "$PIPE"
# Start the Python program in the background
myprogram <"$PIPE" &
# Now grab an open handle to write the pipe
exec 3>"$PIPE"
# And we don't need to refer to the pipe by name anymore
rm -f "$PIPE"

# Later, the shell script does other work,...
# ...possibly in a loop?
while :; do
    ...
    ...
    # Now I've got something to send to the background program
    echo foo >&3
    ...
    ...
done

ファイルシステムに一時エントリを追加しないことをお勧めします。一部のシェルがzshこれを行う方法を提供していることを知っていますが、移植可能な方法はわかりません。

おすすめ記事