Domanda

I am testing the communication with a subprocess. I have to start a server, sending periodically data. The final target is a process that acquires meteo data and a plotting server. The sampling rate is of the order or minutes .... I wrote the these two fragments of code to understand the basics of ipc in python, but I am not even able to make them working. The syncronism is not an issue.

main process

import sys, time
from subprocess import Popen, PIPE

print 'starting'
proc = Popen (['python.exe',
    'C:\Documents and Settings\Administrator\Desktop\sub.py'], 
                stdin = PIPE, stdout = PIPE)
print 'launched'

w = 0
while True:
    w += 1 
    time.sleep (2)
    print 'writing', w
    proc.stdin.write (repr(w))
    proc.stdin.flush()
    print proc.stdout.read()

subprocess:

import sys, time

print 'reading'
v = 0
while True:
    v = sys.stdin.read()
    sys.stdout.write('ACK')
    sys.stdout.flush ()
    time.sleep (4)

The main process is blocking, apparently the sub is not reading-sending the ACK. where am I wrong ??? thanks

È stato utile?

Soluzione

The call to sys.stdin.read() blocks, as it is trying to read the entire stream, thus it can't return until the stream is closed.

Try using sys.stdin.readline() and add a newline when writing using sys.stdout.write() (in both processes), e.g. sys.stdout.write('ACK\n'). This should make sure the reading commands will block only until a single line is read.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top