简体   繁体   中英

Pipe text to stdin of running python process

Let's say I have a python script called service.py running as a kind of daemon in the background, and I want to give it some information by piping text into its stdin:

> pgrep -f service.py
[pid of process]
> echo -e 'test\n' > /proc/[pid of process]/fd/0

My python script should take whatever is in its stdin and assign it to a variable inp :

import sys
while True: 
   inp = sys.stdin.readline()
   #do something with inp

But when i do the above, it just prints the stdin stream:

> python service.py 
test            

The effect is the same if I literally just have this in my script

import sys
inp = sys.stdin.readline() #sys.stdin.readline() never returns
                           #script never exits

What am I doing wrong?

you can use named pipe with mkfifo ( https://serverfault.com/questions/443297/write-to-stdin-of-a-running-process-using-pipe )

That leaves you with:

 mkfifo yourfifo cat > yourfifo & mypid=$! yourprogram < yourfifo 

Now you can sent data to your program with

 `echo "Hello World" > yourfifo` 

( https://askubuntu.com/questions/449132/why-use-a-named-pipe-instead-of-a-file )

the key is that stdin has to be known as pipe or named pipe this is why you can use mkfifo , see also How to write data to existing process's STDIN from external process? (python part) and How to write data to existing process's STDIN from external process? (os part)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM