Greedy parsing of argparse/positional arguments

Discussion in 'Python' started by Johannes Bauer, Nov 20, 2012.

  1. Hi list,

    I have a problem with Python3.2's argparse module. The following sample:

    parser = argparse.ArgumentParser(prog = sys.argv[0])
    parser.add_argument("-enc", metavar = "enc", nargs = "+", type = str,
    default = [ "utf-8" ])
    parser.add_argument("pattern", metavar = "pattern", type = str, nargs = 1)
    parser.add_argument("filename", metavar = "filename", type = str, nargs = 1)
    args = parser.parse_args(sys.argv[1:])

    illustrates the problem: I want to be able to specify an encoding one or
    more times (multiple encodings possible), have a pattern and a filename
    as the last two arguments.

    This works as long as I don't specify '-enc' on the command line. If I
    do, for example

    ../foo -enc myencoding mypattern myfile

    The "-enc" greedy parser seems to capture ["myencoding", "mypattern",
    "myfile"], leaving nothing for "pattern" and "filename", yielding an error:

    ../foo: error: too few arguments

    How can I force positional arguments to take precedence over optional
    arguments? I could exclude them from the parsing altogether, but that
    would make them not appear in the help page (which I'd like to avoid).

    Best regards,
    Johannes

    --
    >> Wo hattest Du das Beben nochmal GENAU vorhergesagt?

    > Zumindest nicht öffentlich!

    Ah, der neueste und bis heute genialste Streich unsere großen
    Kosmologen: Die Geheim-Vorhersage.
    - Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$>
    Johannes Bauer, Nov 20, 2012
    #1
    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:
    880
    Grant Edwards
    Apr 6, 2005
  2. MisterWilliam
    Replies:
    1
    Views:
    305
    George Sakkis
    Jun 18, 2008
  3. Peter Otten
    Replies:
    1
    Views:
    475
    rantingrick
    Feb 1, 2011
  4. Dan Kelly

    Greedy and non greedy quantifiers

    Dan Kelly, Jan 17, 2008, in forum: Ruby
    Replies:
    4
    Views:
    137
    Robert Klemme
    Jan 19, 2008
  5. Matt Garrish

    greedy v. non-greedy matching

    Matt Garrish, Feb 16, 2004, in forum: Perl Misc
    Replies:
    4
    Views:
    155
    Matt Garrish
    Feb 16, 2004
Loading...

Share This Page