
stdout이 python 스크립트의 stdin으로 리디렉션되는 바이너리가 있는데, python 스크립트의 stdout을 바이너리의 stdin으로 보내서 이와 같은 효과를 얻을 수 있는 방법이 있는지 궁금합니다. (실례합니다. 내 끔찍한 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$
댓글에 추가 질문이 있으신 경우:
Python 코드가 아닌 bash 스크립트를 사용하여 파이핑하는 경우 파이프로 이동하지 않고 stdout으로 인쇄할 수 있는 방법이 있습니까?
제가 제시한 간단한 예는 아닙니다. 나는 일반적으로 이 항목을 c 프로그램과 함께 사용하고 명명된 파이프에 직접 출력을 작성하므로 stdout을 다른 출력에 사용할 수 있도록 남겨둡니다.