How do I check for a particular subparser?
Asked Answered
E

1

6

How do I check for a particular subparser?

import argparse
if __name__ == "__main__":
    mainparser = argparse.ArgumentParser()
    submainadder = mainparser.add_subparsers(title='subcommands')
    parser_ut = submainadder.add_parser('unittest')
    stuff = mainparser.parse_args()
    # if 'unittest' was selected:
    #     do_things()
Earnestineearnings answered 29/4, 2015 at 8:31 Comment(2)
Maybe you find useful this link #17074188Lammond
Have you tried giving add_subparsers a dest='cmdname' parameter?Velda
D
2

Maybe something like this ?

import argparse

def do_things(args):
    print args
    # Do your stuff

mainparser = argparse.ArgumentParser()
submainadder = mainparser.add_subparsers(title='subcommands')
parser_ut = submainadder.add_parser('unittest')
parser_ut.set_defaults(func=do_things)

if __name__ == "__main__":
    stuff = mainparser.parse_args()
    stuff.func(stuff)

More explanations can be found here:

python argparse - add action to subparser with no arguments?

Doldrums answered 29/4, 2015 at 8:52 Comment(1)
dest='subcommand' you may also add the dest keyword to add_subparser and highlight its existence and particular usefulness hereEarnestineearnings

© 2022 - 2024 — McMap. All rights reserved.