How to constantly send STDOUT to my python TCP server?
Question:   1. i have simple python echo server which uses sockets , and echoes random numbers to clients .
  2. i have another program which prints every 2 second values to stdout.

If it was just a script i could have redirected like this 'stdout' | python script.py , and fetch it in the script like this `data = sys.stdin.read()`. But it's a server , and it wont work like this. 

Question: How to write such a python server, that it could listen/fetch values
which come to stdout on Debian, and pass them further. I am not asking for a
complete code. Just some ideas on getting stdout, considering the program is a
server.

**Continuosly coming values > stdout > server.py > send values further**


Answer: I think you need something similar to [Python
subprocess](http://docs.python.org/library/subprocess.html#replacing-shell-
pipeline). In that example, consider `dmesg` as your number generator, and the
`grep` as your socket server; however, you will just open a `PIPE` in the
socket server instead of spawning a shell command.

Assume you have two processes, the talker and server...

## talker.py

    
    
    import time
    import sys
    
    DELAY = int(sys.argv[1])
    ii = 1
    while 1:
        sys.stdout.write("Talking every %i seconds, blabbed %i times\n" % (DELAY, ii))
        sys.stdout.flush()
        ii += 1
        time.sleep(DELAY)
    

## server.py

    
    
    from subprocess import Popen, PIPE
    from os import kill
    import signal
    
    talkpipe = Popen(['python', 'talker.py', '3'],
        shell=False, stdout=PIPE)
    try:
        while True:
            line = talkpipe.stdout.readline()
            print "SERVER HEARD", line.strip()
    except KeyboardInterrupt:
        print "Killing child..."
        kill(talkpipe.pid, signal.SIGTERM)
    

Running this with `python server.py` yields...

    
    
    [mpenning@Bucksnort tmp]$ python server.py
    SERVER HEARD Talking every 3 seconds, blabbed 1 times
    SERVER HEARD Talking every 3 seconds, blabbed 2 times
    SERVER HEARD Talking every 3 seconds, blabbed 3 times
    SERVER HEARD Talking every 3 seconds, blabbed 4 times
    ^CTraceback (most recent call last):
      File "talker.py", line 11, in <module>
        time.sleep(DELAY)
    KeyboardInterrupt
    Killing child...
    [mpenning@Bucksnort tmp]$
    

