[Tutor] Parsing os.popen(command) output

Kent Johnson kent37 at tds.net
Sun Sep 11 16:47:58 CEST 2005


Bill Burns wrote:
> Hi,
> 
> I'm parsing some output from a command that I execute with os.popen.
> 
> Here's the typical output from the command:
> [start output]
> TIFF Directory at offset 0x8
> 
>    Subfile Type: (0 = 0x0)
> 
>    Image Width: 12000 Image Length: 16800
> 
>    Resolution: 400, 400 pixels/inch
> 
>    Bits/Sample: 1
> 
>    Compression Scheme: CCITT Group 4
> 
>    Photometric Interpretation: min-is-white
> 
>    Samples/Pixel: 1
> 
>    Rows/Strip: 16800
> 
>    Planar Configuration: single image plane
> 
>    DocumentName: buzzsaw.com
> [end output]
> 
> I need to return the size (width & length) in inches of the Tiff. So I
> need the information on lines:
> 
> Image Width: 12000 Image Length: 16800
> Resolution: 400, 400 pixels/inch
> 
> Example: 12000 / 400 = 30 & 16800 / 400 = 42, so the Tiff is 30" x 42".
> 
> def getTiffWidthLength():
>      tmp = []
>      s = []
>      r = []
>      for line in os.popen(command).readlines():
>          if line.startswith('  Image Width:') or \
>             line.startswith('  Resolution:'):
>             tmp.append(line.strip(' \n'))
>      s.append(tmp[0])
>      r.append(tmp[1])
>      for wl in s:
>          size = p.findall(wl)
>      for i in r:
>          res = p.findall(i)
>      width = int(size[0]) / int(res[0])
>      length = int(size[1]) / int(res[1])
>      print (width, length)
> 
> if __name__ == '__main__':
>      getTiffWidthLength()
> [end code]

I would process the data as I find it rather than use all the helper lists. The data format is simple enough that str.split() can be used to extract it. I used float() instead of int() so it will get the correct answer when the dimensions are not whole inches. Something like this:

def getTiffWidthLength():
     for line in os.popen(command).readlines():
         if line.startswith('  Image Width:'):
            data = line.strip().split()
            rawWidth = float(data[2])
            rawLength = float(data[5])
         elif line.startswith('  Resolution:'):
            data = line.strip().split()
            wRes = float(data[1][1:])
            lRes = float(data[2])

     width = rawWidth / wRes
     length = rawLength / lRes
     print width, length

Kent



More information about the Tutor mailing list