argparse '--' not working?

Peter Otten __peter__ at web.de
Fri Nov 12 14:31:51 CET 2010


Neal Becker wrote:

> It is a 'standard' behaviour that a lone '--' terminates options. 
> argparse says:
> 
> If you have positional arguments that must begin with '-' and don’t look
> like negative numbers, you can insert the pseudo-argument '--' which tells
> parse_args that everything after that is a positional argument:

/If/ you have positonal arguments...
 
> But it doesn't seem to work:
> 
> import argparse
>     
> parser = argparse.ArgumentParser()
> parser.add_argument ('--submit', '-s', action='store_true')
> parser.add_argument ('--list', '-l', action='store_true')
> opt = parser.parse_args()
> 
> ./queue --submit -- test1.py -n
> usage: queue [-h] [--submit] [--list]
> queue: error: unrecognized arguments: -- test1.py -n

Unlike optparse in argparse you must declare positional arguments, too:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("-s", action="store_true")
[snip]
>>> parser.add_argument("whatever", nargs="*")
[snip]
>>> parser.parse_args(["-s", "yadda"])
Namespace(s=True, whatever=['yadda'])
>>> parser.parse_args(["--", "-s", "yadda"])
Namespace(s=False, whatever=['-s', 'yadda'])

Peter





More information about the Python-list mailing list