Diego
Diego

Reputation: 832

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

Upvotes: 4

Views: 2172

Answers (3)

Ian Cleary
Ian Cleary

Reputation: 1

I don't have the reputation to comment, so adding an answer to expand upon @hpaulj's answer


parser = argparse.ArgumentParser(
    description="Example Description"
)

help_text = {}

# custom function to capture help text to display to user
def add_argument(argument, argument_type, help_string, default=None):
    global parser, help_text
    if default is not None:
        ret = parser.add_argument(
            argument,
            type=argument_type,
            help=help_string,
            default=default,
        )
    else:
        ret = parser.add_argument(
            argument,
            type=argument_type,
            help=help_string,
        )
    
    # starts with --, remove it
    if "--" == argument[0:2]:
        argument = argument[2:]
    # starts with -, remove it
    if "-" == argument[0]:
        argument = argument[1:]
    
    # capture help text
    help_text[argument] = ret.help
    return

add_argument(
    "file",
    argument_type=str,
    help_string="Path to file to parse",
)

add_argument(
    "--log_file",
    argument_type=str,
    help_string="Log file",
    default="LogFile.csv",
)


args = parser.parse_args()

print("")
print("------------------------------------------------------")
# print("\n\nArguements received are:")
# print(args)

print("---------------- Script Parameters -------------------")
for args_key in vars(args):
    print(f"\n{args_key}: {getattr(args, args_key)}\n({help_text[args_key]})")
print("------------------------------------------------------")
print("")

Upvotes: 0

hpaulj
hpaulj

Reputation: 231738

parser._actions is a list of the Action objects. You can also grab object when creating the parser.

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

If args.do_x:
      print a.help

Play with argparse in an interactive session. Look at a from such an assignment.

Upvotes: 3

falsetru
falsetru

Reputation: 369494

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)

Upvotes: 4

Related Questions