2011-02-10 9 views
7

Estaba probando optparse y esta es mi secuencia de comandos inicial.comprensión OptionParser

#!/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 bien, esto es lo que estoy tratando de hacer:

  1. Si hay discusión se da con la opción, se tomará el valor "default". es decir myScript.py -d solo mostrará el directorio actual o -m sin ningún argumento tomará el mes actual como argumento.
  2. Para el "--month" solamente 01 a 12 se admiten como argumento
  3. desea combinar más de una opción para realizar diferentes tareas, es decir myScript.py -d this_dir -m 02 va a hacer algo diferente que -d -m y como individuo.
  4. Se imprimirá "No se ha otorgado ninguna opción !!" SÓLO 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 de python, me encontré perdido en las páginas. Se agradece mucho su ayuda; gracias por adelantado. ¡¡Aclamaciones!!


Actualización: 16/01/11

Creo que todavía me falta algo. Esta es la cosa en mi script 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:

  1. ejecute el script sin ninguna opción, volverá option.mon [trabajo]
  2. ejecute el script con la opción -m, con el regreso option.mon [de trabajo]
  3. ejecute la secuencia de comandos con SOLAMENTE la opción -v, SÓLO devolverá option.vos [not w RABAJAR en absoluto]
  4. ejecuta el script con -m y optando -v, hará cosa distinta [sin embargo, para llegar al punto de]

Cuando ejecuto el script con opción sólo -m, está imprimiendo primero option.mon y luego option.vos, que no quiero en absoluto. Realmente aprecio si alguien puede ponerme en la dirección correcta. ¡¡Aclamaciones!!


tercera 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 la secuencia de comandos 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 solamente:

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

lo am Estoy haciendo mal? ¡¡Aclamaciones!!


cuarto Actualización:

Respondiendo a mí mismo: de esta manera puedo conseguir lo que estoy buscando, pero todavía no estoy impresionado sin embargo.

#!/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 manera de hacerlo? No se ve la "mejor manera" para mí. ¡¡Aclamaciones!!

Respuesta

1

Su solución parece razonable para mí. Comentarios:

  • No entiendo por qué se convierte month_abbr en una tupla; que debería funcionar bien sin la tuple()
  • me gustaría recomendar la comprobación de valor de mes no válido (raise OptionValueError si encuentra un problema)
  • si realmente desea que el usuario introduzca exactamente "01", "02", ... , o "12", puede usar el tipo de opción "elección"; ver option types documentation
0

Sólo para ilustrar las opciones-opción de add_argument de argparse.ArgumentParser() - Método:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import sys 
from argparse import ArgumentParser 
from datetime import date 

parser = ArgumentParser() 

parser.add_argument("-u", "--user", default="Max Power", help="Username") 
parser.add_argument("-m", "--month", default="{:02d}".format(date.today().month), 
        choices=["01","02","03","04","05","06", 
          "07","08","09","10","11","12"], 
        help="Numeric value of the month") 

try: 
    args = parser.parse_args() 
except: 
    parser.error("Invalid Month.") 
    sys.exit(0) 

print "The month is {} and the User is {}".format(args.month, args.user)