How can I make argparse do somet开发者_开发问答hing like:
[ 'all' | [ pos1 [ pos2 [ pos3 ...]]]] --some --other --flags
where all
is a reserved word (making it a flag would not be ok if it doesn't need a -
prefix)
Second:
is it possible to have some aliases for named parameters like -h
and --help
meaning the same option? Maybe I should try with add_mutually_exclusive_group()
?
add_mutually_exclusive_group() is designed for exactly this - you are trying to add a mutually exclusive group.
In regards to the second part of your question, this should do what you want:
parser.add_argument('-f', '--foobar')
(Note: your question is a bit confusing - there are two questions there and the second question runs straight into another sentence about the first question. Not to mention the numerous typos... I'll try and help but the clearer you can make the question the clearer we can answer you.)
Update As far as I can tell mutually exclusive arguments must be required but positional arguments cannot be required. Therefore positional arguments cannot be mutually exclusive (presumably because otherwise the interpreter wouldn't be able to tell what was what). For your purposes I don't think this really matters as the code that interprets your arguments would be practically the same either way.
Assuming you could do it the way you are trying to then have to do something like this:
# all == True
# pos == ('this', 'that', 'theother')
if all == true:
do_some_stuff('all')
else:
do_some_other_stuff('positional arguments')
Whereas if you accept "all" as one of your positional arguments you would have to do this:
# pos = ('all', 'this, 'that', 'theother')
if pos[0] == 'all': #other parameters are ignored
do_some_stuff('all')
else:
do_some_other_stuff('positional arguments')
Unless you have some specific reason, I see no reason not to do it the latter way.
精彩评论