NEWBIE: Tokenize command output

Steven Bethard steven.bethard at gmail.com
Thu May 11 16:17:40 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 '*'
[snip]
> From there, I need to tokenize the line using the spaces as delimiters. 

I use the subprocess module instead for better error reporting, but 
basically if you just iterate over the file object, you'll get the lines.

     import subprocess

     # open the process
     cmd = subprocess.Popen(['ntpq', '-p'], stdout=subprocess.PIPE)

     # iterate over the file object until we see a line-initial "*"
     line = None
     for line in cmd.stdout:
         if line.startswith('*'):
             break

     # make sure to catch the error if ntpq didn't produce any output
     assert line is not None

     # split the line into tokens (stolen from Tim Chase's answer
     (remote, refid, st, t, when,
      poll, reach, delay, offset, jitter) = line.split()

If you need to do this for each line that starts with a "*" instead of 
just the first, move the line.split() code inside the for-loop.

STeVe



More information about the Python-list mailing list