2

I have a problem concerning the reading of the stdout in python. I have to explain a bit what I am trying to do.

I have a Python program (foo); this calls a second python program (bar). bar will give back to stdout status details and other information to be logged. The foo now has to read this. In principle it works. I can grab the output of bar and send it to a log file without any problems. The problems start when I try to look for certain phrases in the output from bar (the status report).

I am reading the output with os.read(fn, n) from the stdout of bar. The problem is that os.read reads n bytes, but not a line; it can be more or less. I want it to read every line that is written to stdout by bar, these lines end with \n and are written either with print or with sys.stdout.write followed by a sys.stdout.flush().

foo calls bar using:

bar= subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
fd_in[0] = bar.stdout.fileno()
fd_in[1] = bar.stderr.fileno()

My code looks like this at the moment. bar writes:

print 'TAG INFO1 INFO2 INFO3'
#or
sys.stdout.write('TAG INFO1 INFO2 INFO3\n')
sys.stdout.flush()

I am reading in foo with

buf = os.read(fd_in[0], 256)

When I write this to a log file with:

int_logFile.write(buf)
int_logFile.flush()

everything is fine. But if I want to grab the first word of the output line like this:

tokens = buf.strip('\n').split(' ')

I end up in missery, because I do not get TAG, but I might have INFOx or something from a previous output nothing to do with my status messages.

So to sum it up I need to read the output of bar line by line in foo. Any ideas???

unwind
  • 391,730
  • 64
  • 469
  • 606
red_tiger
  • 1,402
  • 3
  • 16
  • 32

2 Answers2

2

Er, bar.stdout.readline()? Going all the way to file descriptors is rarely necessary.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • I do not belive this. I was trying all afternoon with `bar.stdout.readlines()` and was getting nowhere. Well good to know it is **That simple** ;-) – red_tiger Oct 18 '11 at 14:16
0

How about Popen.communicate? This will also let you send input to the process if you want to.

Aphex
  • 7,390
  • 5
  • 33
  • 54
  • Yes, but I want to receive the output from the process, which I also can with communicate, but then I am not quite shure if I will not only get the output when the process has finished, which will not do for my needs. The usage of `readline` does the trick for me at the moment. Thanks for the input though. – red_tiger Oct 19 '11 at 07:19