2

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?

encomiastical
  • 143
  • 13
  • Have you tried to debug your code to see if `inp` actually gets assigned to some value? Problem could be in the code of the `while` loop somewhere else. – Reaper Feb 07 '17 at 16:02
  • No, sys.stdin.readline() never returns, everything I put after never gets executed. – encomiastical Feb 07 '17 at 16:06
  • Possible duplicate of [How to write data to existing process's STDIN from external process?](http://stackoverflow.com/questions/5374255/how-to-write-data-to-existing-processs-stdin-from-external-process) – languitar Feb 07 '17 at 16:07
  • @languitar you're right, it is, thank you so much – encomiastical Feb 07 '17 at 16:15

1 Answers1

0

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)

Community
  • 1
  • 1
ralf htp
  • 9,149
  • 4
  • 22
  • 34
  • What about on Windows? – cowlinator Aug 24 '18 at 01:26
  • On Windows i do not know exactly, however it appears that it is more complex and limited. On windows (Named) pipes are only supported within an app container **Windows 10, version 1709:** *Pipes are only supported within an app-container; ie, from one UWP process to another UWP process that's part of the same app. Also, named pipes must use the syntax ".\pipe\LOCAL" for the pipe name.* source : https://learn.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-getnamedpipeclientprocessid – ralf htp Aug 24 '18 at 06:57
  • also see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365780(v=vs.85).aspx and **https://stackoverflow.com/questions/14574170/how-do-i-use-a-pipe-to-redirect-the-output-of-one-command-to-the-input-of-anothe** – ralf htp Aug 24 '18 at 08:02