A starter template for a Python Command Line program

A starter template for a Python Command Line program

There are several ways to create a command line program in Python.

This blog post presents a simple example 'template' based around the built-in optparse module (with OptionParser class). The optparse module has good documentation on how to set it up, but seems to lack a few examples of how to actually use it.

You can copy-paste this code and edit it to suit your particular command line program.


"""
main.py

TODO_DESCRIBE_WHAT_THIS_DOES.
"""

import sys
from optparse import OptionParser

# usage() - prints out the usage text, from the top of this file :-) and the options
def usage(parser):
    print(__doc__)
    parser.print_help()


# optparse - parse the args
parser = OptionParser(
    usage="%prog <TODO_ARGS> [options]",
    version="0.1.0"
)

parser.add_option(
    "-i", "--input", metavar="INPUT_FILE", help="read data from INPUT_FILE", dest="input_file"
)
parser.add_option(
    "-l",
    "--language",
    dest="target_language",
    metavar="TARGET_LANGUAGE",  # 'metavar' helps make 'help' messages refer to values and is used to build the help for this option.
    default="English",
    help="translate to the target output language TARGET_LANGUAGE. Example: English.",
)
parser.add_option(
    "-o",
    "--output",
    dest="output_dir",
    default=None,
    help="the output directory. By default is None, so output is to stdout (no files are output).",
)
parser.add_option(
    "-v", "--verbose",  action='store_true', help="turn on verbose mode", dest="is_verbose"
)

(options, args) = parser.parse_args()
if len(args) != 1:
    usage(parser)
    sys.exit(2)

first_arg = args[0]
target_language = options.target_language
path_to_output_dir = None
if options.output_dir:
    path_to_output_dir = options.output_dir



Running python main.py will output help text like:


main.py

TODO_DESCRIBE_WHAT_THIS_DOES.

Usage: main.py <TODO_ARGS> [options]

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -i INPUT_FILE, --input=INPUT_FILE
                        read data from INPUT_FILE
  -l TARGET_LANGUAGE, --language=TARGET_LANGUAGE
                        translate to the target output language
                        TARGET_LANGUAGE. Example: English.
  -o OUTPUT_DIR, --output=OUTPUT_DIR
                        the output directory. By default is None, so output is
                        to stdout (no files are output).
  -v, --verbose         turn on verbose mode

Comments