samedi 3 mars 2007

[Python]: optparse -- powerful command line option parser

I find optparse much better than getopt to get command line options.
The beast is explained here:

For example:

from optparse import OptionParser


parser.add_option("-f", "--file",dest="filename",help="a file to process")
parser.add_option("-r", "--repeat",dest="repeat",help="an integer")
parser.add_option("--dp",dest="directory",help="picture directory")


print options.filename
print options.repeat
print options.verbose

For flags, 'action' can be "store_true" or "store_false"

[Python]: find files of a certain type in a folder.

To search for .jpg files in the folder "myfoder" you can do:

import os,fnmatch

for fileName in os.listdir ( "myfolder" ):
if fnmatch.fnmatch ( fileName, '*.jpg' ):
print "Found fileName ",fileName