Programming
python python-3.x argparse
Updated Wed, 07 Sep 2022 13:45:18 GMT

Looking to set a global default argument with argparse


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.




Solution

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)