Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   argparse: combine current option value with positional argument (http://www.velocityreviews.com/forums/t742922-argparse-combine-current-option-value-with-positional-argument.html)

Peter Otten 02-01-2011 12:59 PM

argparse: combine current option value with positional argument
 
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" ;)

rantingrick 02-01-2011 04:23 PM

Re: argparse: combine current option value with positional argument
 
On Feb 1, 6:59*am, Peter Otten <__pete...@web.de> 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


All times are GMT. The time now is 09:04 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57