Comprender OptionParser

Estaba probandooptparse Y este es mi guión inicial.

#!/usr/bin/env python

import os, sys
from optparse import OptionParser

parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"

parser.add_option("-d", "--dir", type="string",
                  help="List of directory",
                  dest="inDir", default=".")

parser.add_option("-m", "--month", type="int",
                  help="Numeric value of the month", 
                  dest="mon")

options, arguments = parser.parse_args()

if options.inDir:
    print os.listdir(options.inDir)

if options.mon:
    print options.mon

def no_opt()
    print "No option has been given!!"

Ahora, esto es lo que estoy tratando de hacer:

Si no se proporciona ningún argumento con la opción, tomará el valor "predeterminado". es decirmyScript.py -d solo listará el directorio actual o-m sin ningún argumento tomará el mes actual como argumento.Para el "--mes" solo se permiten 01 a 12 como argumentoQuiere combinar más de una opción para realizar diferentes tareas, es decirmyScript.py -d this_dir -m 02 hará algo diferente que -d y -m como individuo.Se imprimirá "¡No se ha dado ninguna opción!"SOLO si no se proporciona ninguna opción con el script.

¿Son factibles? Visité el sitio doc.python.org para obtener posibles respuestas, pero como principiante en python, me encontré perdido en las páginas. Apreciamos mucho su ayuda; gracias por adelantado. ¡¡Salud!!

Actualización: 16/01/11

Creo que todavía me falta algo. Esta es la cosa en mi guión ahora.

parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"

parser.add_option("-m", "--month", type="string",
                  help="select month from  01|02|...|12",
                  dest="mon", default=strftime("%m"))

parser.add_option("-v", "--vo", type="string",
                  help="select one of the supported VOs",
                  dest="vos")

options, arguments = parser.parse_args()

Estos son mi objetivo:

ejecuta el script sin ninguna opción, regresaráoption.mon [trabajando]ejecuta el script con la opción -m, con retornooption.mon [trabajando]ejecute el script con SOLO la opción -v, SOLO devolveráoption.vos [no funciona en absoluto]ejecutar el script con -m y -v optando, hará algo diferente [aún por llegar al punto]

Cuando ejecuto el script con solo la opción -m, se imprimeoption.mon primero y luegooption.vos, que no quiero en absoluto. Realmente aprecio si alguien puede ponerme en la dirección correcta. ¡¡Salud!!

3ra actualización

    #!/bin/env python

    from time import strftime
    from calendar import month_abbr
    from optparse import OptionParser

    # Set the CL options 
    parser = OptionParser()
    usage = "usage: %prog [options] arg1 arg2"

    parser.add_option("-m", "--month", type="string",
                      help="select month from  01|02|...|12", 
              dest="mon", default=strftime("%m"))

    parser.add_option("-u", "--user", type="string",
                      help="name of the user", 
              dest="vos")

    options, arguments = parser.parse_args()

    abbrMonth = tuple(month_abbr)[int(options.mon)]

    if options.mon:
        print "The month is: %s" % abbrMonth 

    if options.vos:
        print "My name is: %s" % options.vos 

    if options.mon and options.vos:
        print "I'm '%s' and this month is '%s'" % (options.vos,abbrMonth)

Esto es lo que devuelve el script cuando se ejecuta con varias opciones:

# ./test.py
The month is: Feb
#
# ./test.py -m 12
The month is: Dec
#
# ./test.py -m 3 -u Mac
The month is: Mar
My name is: Mac
I'm 'Mac' and this month is 'Mar'
#
# ./test.py -u Mac
The month is: Feb
My name is: Mac
I'm 'Mac' and this month is 'Feb'

Me gusta ver solo:

 1. `I'm 'Mac' and this month is 'Mar'` - as *result #3*  
 2. `My name is: Mac` - as *result #4*

¿Qué estoy haciendo mal? ¡¡Salud!!

4ta actualización:

Respondiéndome a mí mismo: de esta manera puedo obtener lo que estoy buscando, pero todavía no estoy impresionado.

#!/bin/env python

import os, sys
from time import strftime
from calendar import month_abbr
from optparse import OptionParser

def abbrMonth(m):
    mn = tuple(month_abbr)[int(m)]
    return mn

# Set the CL options 
parser = OptionParser()
usage = "usage: %prog [options] arg1 arg2"

parser.add_option("-m", "--month", type="string",
                  help="select month from  01|02|...|12",
                  dest="mon")

parser.add_option("-u", "--user", type="string",
                  help="name of the user",
                  dest="vos")

(options, args) = parser.parse_args()

if options.mon and options.vos:
    thisMonth = abbrMonth(options.mon)
    print "I'm '%s' and this month is '%s'" % (options.vos, thisMonth)
    sys.exit(0)

if not options.mon and not options.vos:
    options.mon = strftime("%m")

if options.mon:
    thisMonth = abbrMonth(options.mon)
    print "The month is: %s" % thisMonth

if options.vos:
    print "My name is: %s" % options.vos

y ahora esto me da exactamente lo que estaba buscando:

# ./test.py 
The month is: Feb

# ./test.py -m 09
The month is: Sep

# ./test.py -u Mac
My name is: Mac

# ./test.py -m 3 -u Mac
I'm 'Mac' and this month is 'Mar'

¿Es esta la única forma de hacerlo? No me parece la "mejor manera". ¡¡Salud!!