Search code examples
pythonargparse

How to print just the content of the help string of a specific argument of ArgParse


Is there a way to access the help strings for specific arguments of the argument parser library object?

I want to print the help string content if the option was present on the command line. Not the complete help text that Argument Parser can display via ArgumentParser.print_help .

So something along those lines:

parser = argparse.ArgumentParser()

parser.add_argument("-d", "--do_x", help='the program will do X')

if do_x:
    print(parser.<WHAT DO I HAVE TO PUT HERE?>('do_x')

And this is the required behavior

$program -d

the program will do X


Solution

  • There is parser._option_string_actions which is mapping between option strings (-d or --do_x) and Action objects. Action.help attribute holds the help string.

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--do_x", action='store_true',
                        help='the program will do X')
    args = parser.parse_args()
    if args.do_x:
        print(parser._option_string_actions['--do_x'].help)
        # OR  print(parser._option_string_actions['-d'].help)