Pergunta

I'm trying to set up argparse on my python program but it's not working. The arguments I'm trying to process are as follows:

Either '--interactive' OR an integer for the first argument, one of these is required

Any one of either '--xml' OR '--html' OR '--text' OR '--console'. Again, it can be any one of these but one of them is required for the second argument

And finally for the third argument, a '--verbose' flag which is optional.

All of these arguments change variables to True, apart from the integer on the first argument.

This is the code I have at the minute:

import argparse

parser = argparse.ArgumentParser(description='Python Historical Event Calculator.',
                             prog='tempus.py')

inputs = parser.add_mutually_exclusive_group(required=True)
exports = parser.add_mutually_exclusive_group(required=True)

inputs.add_argument('integer', metavar='I', type=float,
               help='percentage to use')

inputs.add_argument('-i','--interactive', dest='bool_interactive', 
               action='store_true', help='enter interactive mode')

exports.add_argument('-x','--xml', dest='bool_xml', action='store_true',
               help='export output as xml')

exports.add_argument('--html', dest='bool_html', action='store_true',
               help='export output as html')

exports.add_argument('-t','--text', dest='bool_text', action='store_true',
               help='export output as plaintext')

exports.add_argument('-c','--console', dest='bool_con', action='store_true',
               help='export output to console')

parser.add_argument('-v','--verbose', dest='verbose', action='store_true',
               help='enter verbose/debug mode', required=False)

args = parser.parse_args()

But I have no idea if I'm on the right track with this though, can anyone help? Does this look about right or have I done it completely wrong?

Edit

I get this traceback when I pass any flag to it:

Traceback (most recent call last):
  File "C:\Users\Callum\Dropbox\Tempus\Feature Tests\argparsetest.py", line 9, in <module>
    help='percentage to use')
  File "C:\Python32\lib\argparse.py", line 1305, in add_argument
    return self._add_action(action)
  File "C:\Python32\lib\argparse.py", line 1528, in _add_action
    raise ValueError(msg)
ValueError: mutually exclusive arguments must be optional

Nenhuma solução correta

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top