zwlayer
zwlayer

Reputation: 1824

How to get subset of argparse arguments in code

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)

Upvotes: 1

Views: 1029

Answers (1)

rrobby86
rrobby86

Reputation: 1474

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.

Upvotes: 1

Related Questions