NEWBIE: Tokenize command output
python.list at tim.thechases.com
Thu May 11 17:45:17 CEST 2006
Lorenzo Thurman wrote:
> This is what I have so far:
> import os
> cmd = 'ntpq -p'
> output = os.popen(cmd).read()
> The output is saved in the variable 'output'. What I need to do next is
> select the line from that output that starts with the '*'
Well, if you don't need "output" for anything else, you can
just iterate over the lines with
cmd = 'ntpq -p'
p = os.popen(cmd)
starLines = [line for line in p.readlines() if
or you may optionally want to prune of the "\n" characters
in the process:
starLines = [line[:-1] for line in p.readlines() if
If there's only ever one, then you can just use
myLine = starLines
Otherwise, you'll have to react accordingly if there are
zero lines or more than one line that begin(s) with an asterisk.
> remote refid st t when poll reach delay offset
> *caesar.cs.wisc. 22.214.171.124 2 u 635 1024 377 29.514 -0.231
>>From there, I need to tokenize the line using the spaces as delimiters.
> Can someone give me some pointers?
Again, you can use the one-line pythonizm of "tuple
unpacking" here (the split() method takes an optional
parameter for the delimiter, but defaults to whitespace):
remote, refid, st, t, when, poll, reach, delay, offset,
jitter = myLine.split()
If you just want one of them, you can do it by offset:
delay = myLine.split()
More information about the Python-list