NEWBIE: Tokenize command output
Tim Chase
python.list at tim.thechases.com
Thu May 11 11:45:17 EDT 2006
Lorenzo Thurman wrote:
> This is what I have so far:
>
> //
> #!/usr/bin/python
>
> 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
import os
cmd = 'ntpq -p'
p = os.popen(cmd)
starLines = [line for line in p.readlines() if
line.startswith("*")]
or you may optionally want to prune of the "\n" characters
in the process:
starLines = [line[:-1] for line in p.readlines() if
line.startswith("*")]
If there's only ever one, then you can just use
myLine = starLines[0]
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
> jitter
[cut]
> *caesar.cs.wisc. 128.105.201.11 2 u 635 1024 377 29.514 -0.231
> 0.077
>
>>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()[7]
HTH,
-tkc
More information about the Python-list
mailing list