Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #98336

argparse: use of double dash to separate options and positional arguments

From Amit Ramon <amit.ramon@gmail.com>
Newsgroups comp.lang.python
Subject argparse: use of double dash to separate options and positional arguments
Date 2015-11-06 12:07 +0200
Message-ID <mailman.71.1446804597.16136.python-list@python.org> (permalink)

Show all headers | View raw


Hello,

I'm trying to use argparse in a program that gets some options and
positional arguments. I want to collect all the positional arguments
in a single argument using the REMAINDER option to add_argument() as
shown bellow:

    parser = argparse.ArgumentParser(description='Test argparse')
    parser.add_argument('-v', '--verbose', action='store_true')
    parser.add_argument('cmd_args', nargs=argparse.REMAINDER)
    print parser.parse_args()

This works well unless the first positional argument starts with a
'-'.

For example, with the above code

    my_prog -v hello world

works well, but

    my_prog -v -x hello world

Fails with an error message 'error: unrecognized arguments: -x'.

If I invoke the program with a '--' at the end of the options (as I
understand is a common standard and a POSIX recommendation), as in:

    my_prog -v -- -x hello world

It works well again.

However, a few questions remain:

Firstly, as far as I can tell the use of '--' is not documented in the
argparse documentation (but the code of argparse clearly shows that it
is a feature).

Secondly, when using '--', this string itself is inserted into the
list of the collected positional arguments (in the above example in
the cmd_args variable):

$ ./my_prog -v -- -x hello world
Namespace(cmd_args=['--', '-x', 'hello', 'world'], verbose=True)

It's quiet easy to check for it and remove it if it exists, but it
still seems like it shouldn't be there - it is not really an argument,
just a delimiter.

Am I doing anything wrong, or is this a bug? I hope someone here can
shed some light on this.

Thanks,

Amit



-- 

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

argparse: use of double dash to separate options and positional arguments Amit Ramon <amit.ramon@gmail.com> - 2015-11-06 12:07 +0200

csiph-web