Greedy parsing of argparse/positional arguments

J

Johannes Bauer

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

--
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 <[email protected]>
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top