1

I would like to get subset of parsed arguments and send them to another function in python. I found this argument_group idea but I couldn't find to reach argument groups. This is what I want to try to do:

import argparse
def some_function(args2):
    x = args2.bar_this
    print(x)

def main(): 
    parser = argparse.ArgumentParser(description='Simple example')
    parser.add_argument('--name', help='Who to greet', default='World')
    # Create two argument groups
    foo_group = parser.add_argument_group(title='Foo options')
    bar_group = parser.add_argument_group(title='Bar options')
    # Add arguments to those groups
    foo_group.add_argument('--bar_this')
    foo_group.add_argument('--bar_that')
    bar_group.add_argument('--foo_this')
    bar_group.add_argument('--foo_that')
    args = parser.parse_args()
    # How can I get the foo_group arguments for example only ?
    args2 = args.foo_group
    some_function(args2)
zwlayer
  • 1,752
  • 1
  • 18
  • 41
  • Argument groups only affect the help display. They do nothing in parsing. There's nothing built into argparse that would do the job. – hpaulj Mar 14 '19 at 15:21
  • https://stackoverflow.com/questions/38884513/python-argparse-how-can-i-get-namespace-objects-for-argument-groups-separately - My answer elaborates on Argument_Groups, the accepted answer is a variant on your accepted answer - using information from the parsers groups. – hpaulj Mar 14 '19 at 16:41
  • Other SO with custom `Action` or `Namespace` classes: https://stackoverflow.com/questions/34348568/can-i-convert-a-namespace-object-from-mutable-to-immutable, https://stackoverflow.com/questions/18668227/argparse-subcommands-with-nested-namespaces – hpaulj Mar 14 '19 at 16:45

1 Answers1

1

I don't know whether a simpler solution exists, but you can create a custom "namespace" object selecting only the keys arguments you need from the parsed arguments.

args2 = argparse.Namespace(**{k: v for k, v in args._get_kwargs()
                              if k.startswith("foo_")})

You can customize the if clause to your needs and possibly change the argument names k, e.g. removing the foo_ prefix.

rrobby86
  • 1,356
  • 9
  • 14
  • yup, I've also considered this but found it a bit dirty :) Anyway, if I don't get a better answer, I'll accept yours – zwlayer Mar 14 '19 at 10:43