Python: Junk received when readline() a process called with Popen() -
i need stream list output of file, getting correct data lot of junk @ end , don't understand doing wrong.
the (what thought simple) popen code is:
stream = [] p = popen(["python", "-u", "test.py"], stdout=pipe, bufsize=1) while p.poll() none: stream.append(p.stdout.readline()) print stream print 'returned: {0}'.format(p.returncode)
the output calling is:
the output running is:
['[index 0] current index position\n', '[index 1] current index position\n', '[index 2] current index position\n', '[index 3] current index position\n', '[index 4] current index position\n', 'exiting. ...\n', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] returned: -4
test.py is:
index = 0 while true: print '[index {0}] current index position'.format(index) index += 1 if index == 5: break import sys print 'exiting....' sys.exit(-4)
the problem here if-condition incorrect:
while p.poll() none: stream.append(p.stdout.readline())
this means "while process running, read line". that's not want. want "while there more output, read line". code wrote reads empty lines while process shutting down, that's empty strings come from.
what should instead this:
for line in p.stdout: stream.append(line)
this correctly stops reading lines when there no more output, , guaranteed read all of output. (theoretically, code exit loop before has processed of output if process produces output faster process it. can emulate adding time.sleep(0.1)
loop.)
Comments
Post a Comment