argparse icon indicating copy to clipboard operation
argparse copied to clipboard

Question: is -- supported as an argument delimiter?

Open zhihaoy opened this issue 6 years ago • 3 comments

From https://www.reddit.com/r/cpp/comments/dzm7lg/argparse_argument_parser_for_modern_c_v20_released/f8c7erq?utm_source=share&utm_medium=web2x

It was not clear from the documentation, so I'd like to know if -- is supported as an argument delimiter?

-- is a convention for separating the list of arguments to the program from the list of arguments to be forwarded, an example:

./invoke sed --trace X=1 Y=2 Z=3 -- 's/foo/bar/g' fiddling.txt

Where invoke would:

  • Recognize sed as an optional argument.
  • Recognize --trace as an optional argument.
  • Recognize X=1, Y=2, and Z=3 as remaining arguments.
  • Recognize s/foo/bar/g and fiddling.txt as argument to pass to sed.

zhihaoy avatar Nov 22 '19 23:11 zhihaoy

Interestingly, Python argparse doesn't support this (https://bugs.python.org/issue9338). --trace has to be '*' or argparse.REMAINDER, but under those modes, Python argparse does not parse the -- pseudo argument at all.

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('myprog')
>>> parser.add_argument('--trace', nargs=argparse.REMAINDER)
>>> parser.add_argument('others', nargs='*')
>>> parser.parse_args(['sed', '--trace', 'X=1', 'Y=2', 'Z=3', '--', 's/foo/bar/g', 'fiddling.txt'])
usage: PROG [-h] [--trace ...] myprog [others [others ...]]
PROG: error: unrecognized arguments: -- s/foo/bar/g fiddling.txt

zhihaoy avatar Dec 05 '19 19:12 zhihaoy

parse_known_args() ?

praiskup avatar Jul 17 '21 08:07 praiskup

If you call parse_args with argv and argc you could probably use a modified argc, so that only the first n arguments are parsed.

darealshinji avatar Aug 04 '23 15:08 darealshinji