1

I have the following lines to parse command line arguments:

...
parser = argparse.ArgumentParser(description="Arguments for Creation of delivery report")

parser.add_argument('tag', help="GIT Tag of the Release")    
parser.add_argument('--foo')    
parser.add_argument('--bar')

parsed_args = parser.parse_args(sys_args)
...

This properly works as intended with a call like:

python my_script.py tag123 --foo foo --bar bar

What I want to achieve is, that users of this script can pass additional "kwargs" as command line arguments, without needing me to define those in the parser via add_argument.

So a call to the script like this:

python my_script.py tag123 --foo foo --bar bar --a 1 --b 2

Should give me:

Namespace(tag='tag123', foo='foo', bar='bar', a='1', b='2')

Is there a way to achieve this?

Fyi: I do not know in advance what additional optional arguments will be given. So extending the parser is not an option. Consider the additional arguments as kind of **kwargs)

Igl3
  • 4,900
  • 5
  • 35
  • 69
  • I don‘t want them to be ignored but included in the Namespace returned from the parser if possible. If this is possible with builtin functionality of argparse, than this question is different from the one marked as duplicate. If not and i would need a workaround the question can be closed as duplicate. – Igl3 Jan 07 '19 at 14:52
  • You can use -- and then build your own interpertered e.g. `python my_script.py tag123 --foo foo --bar bar -- --a 1 --b 2` You will have `args=['1', '--a', 'b']` in your NameSpace and can then parse arguments from there. – Niek de Klein Jan 07 '19 at 15:22
  • `argparse` does not provide a way of parsing those unrecognized arguments. But you can parse that `extras` list yourself afterwards. A variant on question is handling a bunch of 'key=value' strings. I've seen SO questions like that. But again, the key is you have to parse them yourself. – hpaulj Jan 07 '19 at 18:10

0 Answers0