Pregunta

Estoy escribiendo un guión que tiene 2 argumentos que se excluyen mutuamente, y una opción que sólo tiene sentido con uno de esos argumentos. Estoy intentando configurar argparse a fallar si se llama con el argumento de que no tiene sentido.

Para que quede claro:

-m -f tiene sentido

-s tiene sentido

-s -f debe lanzar errores

Sin argumentos están bien.

El código que tengo es:

parser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')
parser.add_argument('host', nargs=1,
            help="ip address to lookup")
main_group = parser.add_mutually_exclusive_group()
mysql_group = main_group.add_argument_group()
main_group.add_argument("-s", "--ssh", dest='ssh', action='store_true',
            default=False,
            help='Connect to this machine via ssh, instead of printing hostname')
mysql_group.add_argument("-m", "--mysql", dest='mysql', action='store_true',
            default=False,
            help='Start a mysql tunnel to the host, instead of printing hostname')
mysql_group.add_argument("-f", "--firefox", dest='firefox', action='store_true',
            default=False,
            help='Start a firefox session to the remotemyadmin instance')

Lo que no funciona, ya que escupe

 usage: whichboom [-h] [-s] [-m] [-f] host

en lugar de lo que cabe esperar:

 usage: whichboom [-h] [-s | [-h] [-s]] host

o algo por el estilo.

 whichboom -s -f -m 116

también no tirar ningún error.

¿Fue útil?

Solución

Sólo tienen los grupos de argumentos mezclados. En su código, sólo se asigna una opción para el grupo mutuamente excluyentes. Creo que lo que quiere es:

parser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')
parser.add_argument('host', nargs=1,
            help="ip address to lookup")
main_group = parser.add_mutually_exclusive_group()
mysql_group = main_group.add_argument_group()
main_group.add_argument("-s", "--ssh", dest='ssh', action='store_true',
            default=False,
            help='Connect to this machine via ssh, instead of printing hostname')
mysql_group.add_argument("-m", "--mysql", dest='mysql', action='store_true',
            default=False,
            help='Start a mysql tunnel to the host, instead of printing hostname')
main_group.add_argument("-f", "--firefox", dest='firefox', action='store_true',
            default=False,
            help='Start a firefox session to the remotemyadmin instance')

Se podía saltar todo el asunto grupo mutuamente excluyentes y añadir algo como esto:

usage = 'whichboom [-h] [-s | [-h] [-s]] host'
parser = argparse.ArgumentParser(description, usage)
options, args = parser.parse_args()
if options.ssh and options.firefox:
    parser.print_help()
    sys.exit()

Otros consejos

Añadir el argumento usage al crear el programa de análisis:

usage = "usage: whichboom [-h] [-s | [-h] [-s]] host"
description = "Lookup servers by ip address from host file"
parser = argparse.ArgumentParser(description=description, usage=usage)

Fuente: http://docs.python.org/dev/library/ # uso argparse.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top