« Back to Index

argparse cli flag examples

View original Gist on GitHub

Tags: #python

python argparse cli flags examples.py

import argparse


def main():
    """ArgumentParser adds -h/--help default (add_help=True).

    Documentation:
        https://docs.python.org/3.8/library/argparse.html#add-help

    Example:
        in the following example we'll see we must provide the -f/--foo flag,
        while provided value for -b/--bar flag is stored as integer and not a
        string (which would otherwise be the default behaviour). we see the
        -fb/--foobar flag is omitted and so it is assigned a default value,
        while -z/--baz is omitted and so the default value is None. finally the
        -bl/--boolean flag demonstrates the correct way to handle values that
        should be stored as True or False bool types (i.e. if the flag is
        provided, no value needed, then using action="store_true" will result
        in the value to be stored as True).

        $ python3 app.py -f 123 --bar 456 --boolean
        Namespace(bar=456, baz=None, boolean=True, foo='123', foobar='foobar')
    """

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

    # mandatory flag + all value types are converted to string
    parser.add_argument('-f', '--foo', required=True)

    # provide a default value for omitted flag
    parser.add_argument('-fb', '--foobar', default="foobar")

    # value type converted to integer
    parser.add_argument('-b', '--bar', type=int)

    # value type always converted to truthy boolean (unlikely what you want)
    parser.add_argument('-z', '--baz', type=bool, help="custom help")

    # properly handle storing of value as boolean (i.e. stores either True or False)
    #
    # the principle is to use either the store_true or store_false actions.
    #
    # if you use store_true, then when flag is omitted it's stored as False
    # if you use store_false, then when flag is omitted it's stored as True
    parser.add_argument('-bl', '--boolean', action="store_true")

    # parse the script's given arguments
    args = parser.parse_args()

    print(args)


main()