100 days of code: Day 18 - argparse

Last modified on 2020-06-26

Source: 100-days-of-code.

Using the built-in argparse module in Python is an easier and more elegant method for processing command line arguments to my programs. Its easy to add options and throws in --help for free. Yes!

I wrote a program to play with it - argparse_help.py - that uses a mix of required arguments, standalone options (boolean toggles for True and False), and options that require arguments …

import argparse

description = 'Parses command.'

def get_arguments():
    epilogue = 'Hope this helps.'
    parser = argparse.ArgumentParser(
    # argparse includes a built-in '-h', '--help' option that
    # auto-generates a helpful tip derived from my code
    # arguments treated as strings by default; specify `type=int`
    # if option requires an integer
    parser.add_argument('-n', '--number', help='some number', type=int)
    # option has argument OUTPUT
    parser.add_argument('-o', '--output', help='save data to OUTPUT')
    # standalone option (boolean type)
        '-v', '--verbose', help='increase output verbosity', 
    # positional argument (required - saved as a key-value pair)
    parser.add_argument('<source>', help='filename')
    # create a data object that contains a summary of all arguments
    # that the function has parsed
    arguments = parser.parse_args()
    return arguments

args = get_arguments()

# retrieving values
if args.verbose:
    print("Verbose mode: on")
    print("Verbose mode: off")
print(f"Output: {args.output}")
if args.number:
    if args.number > 10:
        print(f"Number: {args.number} (too high)")
        print(f"Number: {args.number}")

Run …

$ ./argparse_help.py 
usage: argparse_help.py [-h] [-n NUMBER] [-o OUTPUT] [-q] [-v] <source>
argparse_help.py: error: the following arguments are required: <source>

Whoops. Forgot to append the required source file. What else am I forgetting … better check --help

$ ./argparse_help.py -h
usage: argparse_help.py [-h] [-n NUMBER] [-o OUTPUT] [-q] [-v] <source>

Parses command.

positional arguments:
  <source>              filename

optional arguments:
  -h, --help            show this help message and exit
  -n NUMBER, --number NUMBER
                        some number
  -o OUTPUT, --output OUTPUT
                        save data to OUTPUT
  -q, --quiet           do not display output
  -v, --verbose         increase output verbosity

Run again with a few extras …

$ ./argparse_help.py -n 8 -v --output foobar.txt foo
Namespace(number=8, output='foobar.txt', verbose=True, **{'<source>': 'foo'})
Verbose mode: on
Output: foobar.txt
Number: 8

Hope this helps.

Happy hacking!