0

Parsing an unknown number of positional arguments is possible by setting nargs to *.

Is there any way to parse an unknown number of named arguments with argparse?

For example:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("optionals", nargs="**")
>>> parser.parse_args(['--foo', 'FOO', '--bar', 'BAR'])
Namespace(optionals={'foo': 'FOO', 'bar': 'BAR'})

I can try and parse the resulting list that comes out of nargs='*' but that will prove to be inefficient with lots of edge-cases.

Bharel
  • 23,672
  • 5
  • 40
  • 80
  • There is `parser.parse_known_args` which will give you a list of all args that have not been parsed as well (but it does not e.g. remove the `"--"`). – Graipher Jan 30 '19 at 15:38
  • 2
    It's not clear what you are looking for. Could you please provide some specific examples that show inputs (command lines) and how you want to see the results. – DrM Jan 30 '19 at 15:38
  • 1
    Nope, `argparse` doesn't have a tool to do this for you. If you want to accept arbitrary pairs of flag and value do your own processing (eg. from `sys.argv`). – hpaulj Jan 30 '19 at 17:29
  • One could do this by parsing the arguments extracting all the options and then building a parser with all the options passed in and the using that parser. It is not a good idea but I had to at least say it was possible. – Dan D. Jan 30 '19 at 17:43
  • Lots of duplicates listed in https://stackoverflow.com/questions/54076485/argumentparser-parsing-optional-arguments-not-defined-in-parser?noredirect=1&lq=1 – hpaulj Jan 30 '19 at 18:37
  • @hpaulj Thank you for that. Most of the duplicates listed there were not so relevant to the main duplicate but the fourth one stating "Parse non-pre-defined argument" is quite close. You should post the fact that `argparse` doesn't have the means of doing it as an answer :-) – Bharel Jan 30 '19 at 22:16

0 Answers0