Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #41802

Re: Required arguments in argparse: at least one of a group

X-Received by 10.224.185.201 with SMTP id cp9mr5324890qab.6.1364161305635; Sun, 24 Mar 2013 14:41:45 -0700 (PDT)
X-Received by 10.49.48.12 with SMTP id h12mr521530qen.8.1364161305612; Sun, 24 Mar 2013 14:41:45 -0700 (PDT)
Path csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!t2no14919937qal.0!news-out.google.com!k8ni11100qas.0!nntp.google.com!ca1no5436664qab.0!postnews.google.com!glegroupsg2000goo.googlegroups.com!not-for-mail
Newsgroups comp.lang.python
Date Sun, 24 Mar 2013 14:41:45 -0700 (PDT)
In-Reply-To <kikjpg$ch5$1@speranza.aioe.org>
Complaints-To groups-abuse@google.com
Injection-Info glegroupsg2000goo.googlegroups.com; posting-host=65.183.81.59; posting-account=h7ZmAgoAAAChnNHfIDF1M6YGHuonryl5
NNTP-Posting-Host 65.183.81.59
References <kikjpg$ch5$1@speranza.aioe.org>
User-Agent G2/1.0
MIME-Version 1.0
Message-ID <8ef40685-bcd1-4f5f-900c-2cb8d31c0950@googlegroups.com> (permalink)
Subject Re: Required arguments in argparse: at least one of a group
From rurpy@yahoo.com
Injection-Date Sun, 24 Mar 2013 21:41:45 +0000
Content-Type text/plain; charset=ISO-8859-1
Xref csiph.com comp.lang.python:41802

Show key headers only | View raw


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 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.')

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Required arguments in argparse: at least one of a group Marco <m.b@gmail.com> - 2013-03-23 17:04 +0100
  Re: Required arguments in argparse: at least one of a group Rob Day <robert.day@merton.oxon.org> - 2013-03-23 16:27 +0000
    Re: Required arguments in argparse: at least one of a group Marco <m.b@gmail.com> - 2013-03-24 21:02 +0100
  Re: Required arguments in argparse: at least one of a group rurpy@yahoo.com - 2013-03-24 14:41 -0700

csiph-web