'argparse - How to handle parent parser behaviour?
I have a parent parser which defines a common flag --global which is globally available across subparsers.
parent (defines --global)
/ \
child1 child2
--global --global
I am handling the flags of child1 and child2 via set_dfault. Since both subparsers inherit --global I have to handle the flag in both subparser functions. How can I improve this? Can I define the behaviour of --global in parent once without repeating me?
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument("--global", action="store_true")
def handle_child1(xargs):
if xargs.global:
print("handle global")
print("do stuff from child 1")
def handle_child2(yargs):
if yargs.global:
print("handle global")
print("do stuff from child 2")
subparser = parser.add_subparsers()
child1 = subparser.add_parser("c1", parents=[parent])
subparse_x.set_defaults(func=handle_child1)
child2 = subparser.add_parser("c2", parents=[parent])
subparse_y.set_defaults(func=handle_child2)
As you can see I have to handle global in each subparser. Not idea. Of cause I could call a function handle_global from each subparser to make this a bit better. However is there a solution that just lets parent handle global?
Solution 1:[1]
If I understand what you are attempting to do you can handle the global attribute prior to sending the arguments to the correct sub-command function.
import argparse
def handle_global_flag():
print("handling --global")
def handle_child1(args):
print(args)
print("do stuff from child 1")
def handle_child2(args):
print(args)
print("do stuff from child 2")
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument("--global", action="store_true")
parser = argparse.ArgumentParser(add_help=False)
subparsers = parser.add_subparsers(dest="command")
child1 = subparsers.add_parser("c1", parents=[parent])
child1.set_defaults(func=handle_child1)
child2 = subparsers.add_parser("c2", parents=[parent])
child2.set_defaults(func=handle_child2)
args = parser.parse_args()
if args.command is not None:
if getattr(args, "global"):
handle_global_flag()
args.func(args)
else:
parser.print_help()
parser.exit()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex |
