Required arguments in argparse: at least one of a group

M

Marco

Is there the possibility using the argparse module to group two or more
arguments in order to have at least one of them required? For instance,
I would like to have not an error only in the following cases:

python finder.py --file myfile --dir mydir
python finder.py --pattern mypattern --dir mydir
python finder.py --file myfile --pattern mypattern --dir mydir

where --dir is required, and --file _or_ --parser have to be specified.
In other words, I want the parser prints an error message just in this case:

python finder.py --dir mydir

Thanks in advance, Marco
 
R

Rob Day

I don't know about argparse, but if you use docopt
(http://docopt.org/) then this is easy to do with something like:

"""Usage:

finder.py --file <myfile> --dir <mydir>
finder.py --pattern <mypattern> --dir <mydir>
finder.py --file <myfile> --pattern <mypattern> --dir <mydir>
"""
 
M

Marco

I don't know about argparse, but if you use docopt
(http://docopt.org/) then this is easy to do with something like:

"""Usage:

finder.py --file <myfile> --dir <mydir>
finder.py --pattern <mypattern> --dir <mydir>
finder.py --file <myfile> --pattern <mypattern> --dir <mydir>
"""

Thanks Rob, but I was looking for a solution in the stdlib
 
R

rurpy

Is there the possibility using the argparse module to group two or more
arguments in order to have at least one of them required? For instance,
I would like to have not an error only in the following cases:

python finder.py --file myfile --dir mydir
python finder.py --pattern mypattern --dir mydir
python finder.py --file myfile --pattern mypattern --dir mydir

where --dir is required, and --file _or_ --parser have to be specified.
In other words, I want the parser prints an error message just in this case:

python finder.py --dir mydir

How about something like:

p = argparse.ArgumentParser (description="...")
p.add_argument ('--dir', help="A dir (required).", required=True)
p.add_argument ('--pattern', help="A pattern. If not given, --file is required.")
p.add_argument ('--file', help="A filename. If not given, --pattern is required.")
args = p.parse_args()
if not args.file and not args.pattern:
p.error ('Either --pattern or --file is required.')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top