Looking to set a global default argument with argparse

Viewed 2081

I am writting a new script and would like for the -h or --help argument to be called by default when the script is called without any parameters. So for example if someone calls command_line_utility.py then I want it to print the output you would get with command_line_utility.py -h.

I have dug around in the docs and looked at some examples, but all of them were specifying default argument values and not actually having arg parse call a default argument.

# Setting up Main Argument Parser
    main_parser = argparse.ArgumentParser(description="A set of python web utility scripts")
    main_parser.add_argument("-v",'--version', action='version', version='kuws V0.0.1')

    # Setting up the main subparser
    subparsers = main_parser.add_subparsers(help="Available commands found below, for more info on a command use: python command_line_utility.py <command> -h or kuws <command> -h")


    """Code below handles 'redirects' command in the main script
    i.e. >python command_line_utility.py redirects or kuws redirects
    """
    redirects_parser = subparsers.add_parser('redirects', argument_default='-u',
        help='Allows you to trace redirects and get other information')

    redirects_parser.add_argument('-u', "--url", 
        help='usage: python main.py redirects -u <url>; Lets you see the trace for a url', nargs='?', dest="trace_url")

As it stands when I run the file nothing actually gets printed to the command line. No help text or errors or anything.

3 Answers

I'm afraid argparse doesn't have any built-in support for this, but you can identify this situation and print the help message:

import sys

if len(sys.argv)==1:
    parser.print_help(sys.stderr)
    sys.exit(1)

When using subparsers, a common scheme is using set_defaults(func=<function to be called>) and then calling this function (as explained in sub-commands).

You can simply define a first set_defaults(func=help) at first that will be overwritten with the functions of your command.

Note that you can also make the command required when you declare your subparsers (add_subparsers(..., required='True')) and thus, when the user invokes without a command, she will get an error with the usage.

Checking that len(sys.argv)==1 and in that case calling the print_help method of the parser as described in this answer to a similar question is a possible way to print the help message defined in the parser when no arguments are given.

Related