I've been using argparse
for a Python program that can -process
, -upload
or both:
parser = argparse.ArgumentParser(description='Log archiver arguments.')
parser.add_argument('-process', action='store_true')
parser.add_argument('-upload', action='store_true')
args = parser.parse_args()
The program is meaningless without at least one parameter. How can I configure argparse
to force at least one parameter to be chosen?
UPDATE:
Following the comments: What's the Pythonic way to parametrize a program with at least one option?
If you require a python program to run with at least one parameter, add an argument that doesn't have the option prefix (- or -- by default) and set
nargs=+
(Minimum of one argument required). The problem with this method I found is that if you do not specify the argument, argparse will generate a "too few arguments" error and not print out the help menu. If you don't need that functionality, here's how to do it in code:I think that when you add an argument with the option prefixes, nargs governs the entire argument parser and not just the option. (What I mean is, if you have an
--option
flag withnargs="+"
, then--option
flag expects at least one argument. If you haveoption
withnargs="+"
, it expects at least one argument overall.)If not the 'or both' part (I have initially missed this) you could use something like this:
Though, probably it would be a better idea to use subcommands instead.
Maybe use sub-parsers?
Now
--help
shows:You can add additional options to these sub-parsers as well. Also instead of using that
dest='subparser_name'
you can also bind functions to be directly called on given sub-command (see docs).Use append_const to a list of actions and then check that the list is populated:
You can even specify the methods directly within the constants.
For http://bugs.python.org/issue11588 I am exploring ways of generalizing the
mutually_exclusive_group
concept to handle cases like this.With this development
argparse.py
, https://github.com/hpaulj/argparse_issues/blob/nested/argparse.py I am able to write:which produces the following
help
:This accepts inputs like '-u', '-up', '--proc --up' etc.
It ends up running a test similar to https://stackoverflow.com/a/6723066/901925, though the error message needs to be clearer:
I wonder:
are the parameters
kind='any', required=True
clear enough (accept any of the group; at least one is required)?is usage
(-p | -u)
clear? A required mutually_exclusive_group produces the same thing. Is there some alternative notation?is using a group like this more intuitive than
phihag's
simple test?