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:
http://python.org/doc/lib/module-optparse.html

For example:

from optparse import OptionParser

parser=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")
parser.add_option("-v",help="verbosemode",action="store_true",
dest="verbose",default=True)

(options,args)=parser.parse_args()

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

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