
我有一個二進位文件,其標準輸出被重定向到python 腳本的標準輸入,我想知道是否有任何方法可以將python 腳本的標準輸出發送到二進位檔案的標準輸入,以獲得類似這樣的效果(請原諒)我可怕的ascii圖):
|->-binary -- python -->-|
/|\ \|/
|-<---<---<---<---<---<--|
我當前的 bash 程式碼只是binary | python3 pythonscript.py
.
謝謝!
答案1
您應該能夠使用命名管道來實現您想要的。您可以將每個行程的輸入和輸出重新導向到另一個行程或從另一個行程重新導向。
binary < npipe1 > npipe2
python3 pythonscript.py < npipe2 > npipe1
命名管道已經設定為:
mkfifo /dev/shm/npipe1
mkfifo /dev/shm/npipe2
命名管道被放置到共享記憶體目錄的位置,但該位置不是強制性的。
這是一個使用 bash 和 dash 腳本的簡單範例:
doug@s19:~/temp$ cat test-fifo-job-control
#! /bin/dash
#
# test-fifo-job-control Smythies 2023.09.03
# A simple example of using named pipes.
# See https://askubuntu.com/questions/1484568/two-way-pipe-in-bash
#
# If they do not already exist, then create the named pipes.
# Note: sometimes they might need to be deleted and recreated.
# i.e. if garbage was left in one, or both.
if [ ! -p /dev/shm/npipe1 ]
then
mkfifo /dev/shm/npipe1
fi
if [ ! -p /dev/shm/npipe2 ]
then
mkfifo /dev/shm/npipe2
fi
# Launch the first task
./test-fifo-part-1 < /dev/shm/npipe1 > /dev/shm/npipe2 &
#
# and supply the first input
echo 1000 >> /dev/shm/npipe1
#
# Now launch the second task
#./test-fifo-part-2 < /dev/shm/npipe2 > /dev/shm/npipe1
./test-fifo-part-2 < /dev/shm/npipe2 | tee /dev/shm/npipe1
#
# It'll go until stopped via ^C.
和:
doug@s19:~/temp$ cat test-fifo-part-1
#!/bin/bash
while :
do
# Note: No error checking
read next_number
echo "$next_number"
# Slow things down.
sleep 1
done
和:
doug@s19:~/temp$ cat test-fifo-part-2
#!/bin/bash
while :
do
# Note: No error checking
read next_number
next_number=$((next_number+1))
echo "$next_number"
# Slow things down.
sleep 1
done
會話範例:
doug@s19:~/temp$ ./test-fifo-job-control
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
^C
doug@s19:~/temp$
對於評論中的補充問題:
如果我使用 bash 腳本進行管道傳輸,而不是使用 python 程式碼中的某些內容,是否還有一種方法可以在不進入管道的情況下列印到標準輸出?
不是我給的簡單例子。請注意,我通常將這些東西與 C 程式一起使用,並將輸出直接寫入命名管道,從而使 stdout 可用於其他輸出。