argparse: combine current option value with positional argument

Discussion in 'Python' started by Peter Otten, Feb 1, 2011.

  1. Peter Otten

    Peter Otten Guest

    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" ;)
     
    Peter Otten, Feb 1, 2011
    #1
    1. Advertising

  2. Peter Otten

    rantingrick Guest

    On Feb 1, 6:59 am, Peter Otten <> 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
     
    rantingrick, Feb 1, 2011
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tomi Silander
    Replies:
    3
    Views:
    935
    Grant Edwards
    Apr 6, 2005
  2. I.M. Postor
    Replies:
    2
    Views:
    605
    I.M. Postor
    Sep 27, 2006
  3. Gnarlodious
    Replies:
    9
    Views:
    1,903
    Gnarlodious
    May 16, 2011
  4. Miki Tebeka

    argparse - option with optional value

    Miki Tebeka, May 17, 2012, in forum: Python
    Replies:
    1
    Views:
    305
    Miki Tebeka
    May 18, 2012
  5. Johannes Bauer
    Replies:
    0
    Views:
    164
    Johannes Bauer
    Nov 20, 2012
Loading...

Share This Page