Required arguments in argparse: at least one of a group

rurpy at rurpy at
Sun Mar 24 22:41:45 CET 2013

On 03/23/2013 10:04 AM, Marco wrote:
> 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 --file myfile --dir mydir
>    python --pattern mypattern --dir mydir
>    python --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 --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.')

More information about the Python-list mailing list