Learning Python: Print 3 consecutives lines from a PIPE
i have the following code:
def cmds(cmd):
cmd= Popen(cmd, shell=True, stdout=PIPE)
lines = command.stdout.read().splitl开发者_JAVA技巧ines()
I have a command that outputs lines like this:
2011/03/30-201
CLIENT 3
Failed
23:17
0.0000
2011/03/31-3
CLIENT 2
Completed
00:47
1.0019
I want to read the first 3 lines for a block, then more 3 lines for next block and more 3 ... I do have no idea how to do this.
Untested:
def cmds(cmd):
infile = Popen(cmd, shell=True, stdout=PIPE).stdout
print infile.readline()
print infile.readline()
print infile.readline()
while True:
line = infile.readline()
if not line:
break
if line == '\n':
print infile.readline()
print infile.readline()
print infile.readline()
That has the advantage of working on arbitrarily huge files because it only stores the data it's currently working on and not the entire output of your command.
Well, if lines = command.stdout.read().splitlines()
produces a list of lines like this:
['2011/03/30-201', 'CLIENT 3', 'Failed', '23:17', '0.0000', '', '2011/03/31-3', 'CLIENT 2', 'Completed', '00:47', '1.0019']
You can just loop through it and print until you encounter a blank entry, then reset the counter. It's not very elegant, but it's the most naïve way of doing it:
lines = command.stdout.read().splitlines()
i = 0
for line in lines:
if line != '':
if i < 3:
print(line)
else:
i = 0
i += 1
精彩评论