Python CLI script template

Usually my little Python scripts start with simply using sys.argv[] and print(). But after refactoring they always end up with a structure like this, using the argparse and logging libraries. It’s about time to put this in some kind of copy/pastable template:

import argparse
import logging

DESC = '''
This command line tool does something with a file.

parser = argparse.ArgumentParser(description=DESC)
parser.add_argument("file", help="Some file to process")
parser.add_argument("output", nargs="?", help="Optional output file")
                             #nargs="+" for one or more positional arguments
parser.add_argument("-v", "--verbose", action="count", default=0,
                    help="Verbosity (-v, -vv, etc)")
parser.add_argument("-p", "--param", help="Some additional parameter")
parser.add_argument('--another', default="something", help="Optional parameter "
                                                           "with default value")
parser.add_argument('--flag', action="store_true", default=False,
                    help='Optional flag')

args = parser.parse_args()
loglevel = 30 - (args.verbose * 10)
logging.basicConfig(level=loglevel, format='%(levelname)s: %(message)s')

print(f"Do something with {args.file}")

if args.output:
  print(f"Write to {args.output}")

if args.param:
  print(f"With additional parameter {args.param}")

print(f"The other parameter is {args.another}")

if args.flag:
  print("The flag was set too.")

logging.debug("This is a debug message")"This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")

Paste this code in a file and have a play with it, especially using the different log levels by using -v, -vv etc. You’ll also notice that you automatically get a nice help (-h) message from argparse for free :-)