Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Greedy parsing of argparse/positional arguments

Thread Tools

Greedy parsing of argparse/positional arguments

Johannes Bauer
Posts: n/a
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,

>> 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$(E-Mail Removed)>
Reply With Quote

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
Greedy and non greedy quantifiers Dan Kelly Ruby 4 01-19-2008 08:36 PM
Greedy quantifier - Java 0 07-11-2005 01:34 AM
RegEx: Is there such a thing as "non-greedy backwards"? Java 5 01-25-2005 04:07 PM
Regex again - non-greedy matching kaeli Java 3 05-07-2004 07:36 PM
greedy v. non-greedy matching Matt Garrish Perl Misc 4 02-16-2004 03:25 PM