Python argparse mutually exclusive arguments

How can I get argparse to do something like:

[ 'all' | [ pos1 [ pos2 [ pos3 ...]]]] --some --other --flags 

where all is a reserved word (which makes it a flag will not be normal if it does not need a prefix - )

Secondly: is it possible to have some aliases for named parameters, such as -h and --help , which means the same option? Maybe I should try with add_mutually_exclusive_group() ?

+4
source share
1 answer

add_mutually_exclusive_group () is just for this - you are trying to add a mutually exclusive group.

As for 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 here, and the second question directly in another sentence concerns the first question. Not to mention numerous typos ... I will try and help, but you can ask the question more clearly, how much clearer can we give you to answer.)

Update As far as I can tell, mutually exclusive arguments should be needed, but positional arguments are not required. Therefore, positional arguments cannot be mutually exclusive (presumably because otherwise the interpreter will not be able to say what exactly). For your purposes, I don’t think it really matters, because the code that interprets your arguments will be pretty much the same.

Assuming you can do it the way you are trying to do the following:

 # all == True # pos == ('this', 'that', 'theother') if all == true: do_some_stuff('all') else: do_some_other_stuff('positional arguments') 

If you accept "everything" as one of your positional arguments, you will need 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 a specific reason, I see no reason not to do this in the last way.

+4
source

Source: https://habr.com/ru/post/1335565/


All Articles