Greedy parsing of argparse/positional arguments

Johannes Bauer dfnsonfsduifb at gmx.de
Tue Nov 20 05:02:14 EST 2012


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$1 at speranza.aioe.org>



More information about the Python-list mailing list