David542
David542

Reputation: 110113

Using the '--help' command in argparse

I am using the argparse library but for whatever reason I'm having difficult printing the -h argument. Here is the entire source I have:

# df.py
import argparse
parser = argparse.ArgumentParser(description='Dedupe assets in our library.')
parser.add_argument('--masters', nargs='?', default=None, type=int, help='Enter one or more ids.')

if __name__ == '__main__':
    print ('hi')

I was under the impression that entering in the --h flag via:

$ python df.py --help

Would automatically print the help stuff for the file using argparse but I seem to be making false assumptions. It seems like I also have to add in something like this into my code?

if '--help' in sys.argv: print (parser.parse_args(['-h']))

What is the 'proper' way to print out the help args when using the argparse library?

Upvotes: 2

Views: 682

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

You forgot to actually parse the arguments; if you put parser.parse_args() in after defining the parser, it would respond to -h/--help. Typically, you'd do something like:

args = parser.parse_args()

so that the args object can be used to access the parsed argument data.

I'll also note that the argument parsing should almost certainly be controlled by the if __name__ == '__main__': guard; if you're not being invoked as the main script, parsing the command line is unusual, to say the least. Idiomatic code would look something like:

# df.py
def main():
    import argparse  # Could be moved to top level, but given it's only used
                     # in main, it's not a terrible idea to import in main
    parser = argparse.ArgumentParser(description='Dedupe assets in our library.')
    parser.add_argument('--masters', nargs='?', type=int, help='Enter one or more ids.')
    args = parser.parse_args()

    print ('hi')

    # Do something with args.masters or whatever

if __name__ == '__main__':
    main()

Upvotes: 2

Related Questions