jack-all-trades
jack-all-trades

Reputation: 282

sequentially send stdout from subprocess.Popen via socket

I know this has been anwered many times before, but I haven't find a working way to do this in my scenario... I hope you will help. I want to output the data from stdout and/or stderr from a Popen call in real time, to a socket connection, not to stdout. So sys.stdout.flush() don't work for me.

data=sok.recv(512) #the command to execute
p = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE stderr=subprocess.PIPE)

#this work.. but not how i spected, if the subprocess ends too fast, i only get the first line
while p.poll() is None:
    sok.send(p.stdout.readline())

#this only send the last line
for i in p.stdout.readline():
    sok.send(i)
    sys.stdout.flush() #why sys.stdout? i don't use it
    p.stdout.flush()   #same result

Upvotes: 2

Views: 1755

Answers (1)

Winston Ewert
Winston Ewert

Reputation: 45039

p.poll() indicates whether the process is executing. So it returns false as soon as the program exits. So that's not what you should be checking.

your code:

for i in p.stdout.readline():

reads a single line and then iterates over each letter in that line. Not what you wanted. Use:

for i in p.stdout.readlines():

which will return each line.

But that will read the entire file before producing any lines, probably not what you wanted.

So use:

for line in p.stdout:

Which should give you each line, line by line, until there is nothing more to read

Upvotes: 3

Related Questions