[argparse] mutually exclusive group with 2 sets of options

Francois Lafont francois.lafont at nospam.invalid
Tue Aug 6 19:18:17 EDT 2013


Hi,

On relfection, it's clear that:

1. the "(-a -b VALUE-B | -c -d VALUE-D)" syntax is not
implemented by the argparse module;

2. and get this syntax with "argparse + hacking" is not very clean.

So, finally I'll use the docopt module version 0.6.1.
For the inheritance of common options, I'll used something like
that (even if I prefer the oriented object side of the argparse
module):



[the main file]
#-----------------------------------
import importlib
import sys
from docopt import docopt

help_message ="""
Usage:
  my-script (-h | --help)
  my-script <command> [<args>...]

Options:
  -h, --help
        Show this help message and exit.

Available commands:
  command1  Description1...
  command2  Description2...

See 'my-script <command> -h' for more information on a specific command.
"""

if __name__ == '__main__':

    args = docopt(help_message, options_first=True)
    command = args['<command>']

    try:
        m = importlib.import_module('mymodule.' + command)
    except ImportError:
        print("Sorry, the %s command doesn't exist. See 'my-script -h'.") % (command,)
        sys.exit(1)

    args = docopt(m.help_message, options_first=False)
    m.run(args)
#-----------------------------------



[a file for each specific command, mymodule/command1.py etc.]
#-----------------------------------
import mymodule.common as common

help_message = """
Usage:
  my-script subcommand1 (-h | --help)
  my-script subcommand1 %s -w <warning> -c <critical>

Options:
%s
  -w <warning>, --warning=<warning>
        Some help.
  -c <critical>, --critical=<critical>
        Some help.
""" % (common.common_syntax, common.common_help,)


def run(args):
    pass
#-----------------------------------



[and a file for the common syntax, mymodule/common.py]
#-----------------------------------
common_syntax = """-H <host-address> -t <timeout>
      (--v2c -C <community> | -l <login> -x <passwd> -X <privpass> -L <protocols>)"""

common_help = """  -h, --help
        Show this help message and exit.
  -H <host-address>, --host=<host-address>
        Some help.
  -t <timeout>, --timeout=<timeout>
        Some help.
  --v2c
        Some help.
  -C <community>, --community=<community>
        Set the community password for SNMP V2c.
   # etc.
   # etc.
"""
#-----------------------------------

Thank you all.

-- 
François Lafont



More information about the Python-list mailing list