我有一个无限运行的 python 程序,接受输入并抛出输出。我想编写一个 bash 程序,在 python 脚本运行时提供输入。那么,在程序运行时如何向程序提供输入呢?
答案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
最好避免在文件系统中添加临时条目,我知道有些 shellzsh
提供了一种方法来做到这一点,但我不知道可移植的方法。