How to print only the contents of the help line of a specific ArgParse argument

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

I want to print the contents of the help line if the option was present on the command line. Not the full help text that Argument Parser can display through ArgumentParser.print_help.

So, something in these 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 execute X

+4
source share
2 answers

There is parser._option_string_actions, which is a mapping between the lines of parameters ( -dor --do_x) and Actionobjects . Action.helpcontains a help line.

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)
+3

parser._actions - Action. .

a=parser.add_argument(...)
...

If args.do_x:
      print a.help

argparse . a .

+2

Source: https://habr.com/ru/post/1657021/


All Articles