Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > argparse: combine current option value with positional argument

Reply
Thread Tools

argparse: combine current option value with positional argument

 
 
Peter Otten
Guest
Posts: n/a
 
      02-01-2011
I'd like to capture the current value of an option --prefix=<whatever> along
with a positional value as it is seen by argparse.

Example:
python script.py -p1 alpha beta -p2 gamma -p3

should result in a list

[(1, "alpha"), (1, "beta"), (2, "gamma")]

Here's a working script that uses --name=<some-value> instead of of just
<some-value>:

$ cat tmp.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--prefix")
parser.add_argument("-n", "--name")

class Namespace(object):
def __init__(self):
self.pairs = []
self.prefix = None
def set_name(self, value):
if value is not None:
self.pairs.append((self.prefix, value))
name = property(None, set_name)

ns = Namespace()
parser.parse_args(namespace=ns)
print ns.pairs
$ python tmp.py -p1 -nalpha -nbeta -p2 -ngamma
[('1', 'alpha'), ('1', 'beta'), ('2', 'gamma')]

However, modifying the --name option to a positional with

parser.add_argument("name", nargs="*")

results in an error:

$ python tmp2.py -p1 alpha beta -p2 gamma
usage: tmp2.py [-h] [-p PREFIX] [name [name ...]]
tmp2.py: error: unrecognized arguments: gamma

Am I missing a simple way to avoid that?

Peter

PS: I've not yet "used the source"
 
Reply With Quote
 
 
 
 
rantingrick
Guest
Posts: n/a
 
      02-01-2011
On Feb 1, 6:59*am, Peter Otten <(E-Mail Removed)> wrote:
> I'd like to capture the current value of an option --prefix=<whatever> along
> with a positional value as it is seen by argparse.



Have you seen the handy optphart module yet? I believe its in alpha2
currently but very stable.

http://tinyurl.com/optphart
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
TypeError: __init__() takes exactly 1 positional argument (2 given) Gnarlodious Python 9 05-16-2011 05:08 AM
Positional Grouping Andy XML 0 01-10-2007 05:28 PM
XSLT embedding (positional grouping key?) problem. newbie I.M. Postor XML 2 09-27-2006 08:03 AM
optparse and negative numbers as positional arguments Tomi Silander Python 3 04-06-2005 02:42 PM
DVD Verdict reviews: LAST EXILE: POSITIONAL PLAY (VOLUME 2) and more! DVD Verdict DVD Video 0 04-29-2004 09:05 AM



Advertisments