[Tutor] Parsing os.popen(command) output

Bill Burns billburns at pennswoods.net
Sun Sep 11 16:25:55 CEST 2005


Hi,

I'm parsing some output from a command that I execute with os.popen.
This command (tiffinfo) displays information about Tiff images. The
solution I'm using does work, but I'm wondering there's a 'better' way
to do it.

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".

Here's how I'm doing it:
[start code]
import os
import re

filename = 'C:/Tiff Files/Large Tiffs/Nbm001.TIF'
command = 'tiffinfo "%s"' % (filename)
p = re.compile('\d+')

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]

Like I said, it does work but can it be improved upon?

Thanks for any help.

Bill







More information about the Tutor mailing list