CLI Program Skeleton
This is skeleton code for a command-line interface (CLI) program.
I make these CLI programs fairly frequently as personal utilities and dislike re-writing this boilerplate. It may be amenable to a library, but I haven't put the time in to generalize it.
#! /usr/bin/env python
import os
import sys
import textwrap
from optparse import OptionParser
#
# NOTE TO SELF: usage() provided by James's custom library "phyles"
#
__program__ = "dosomething"
__version__ = '0.1'
def banner(width=70):
hline = "=" * width
print hline
print ("%s v.%s " % (__program__, __version__)).center(width)
print hline
def doopts():
program = os.path.basename(sys.argv[0])
usg = """\
usage: %s [-h | -t | -k | settings.cfg]
- Use the -t flag without a settings file name to set
up current directory with template files
- Use the -k flag without a settings file to skip
optional steps
"""
usg = textwrap.dedent(usg) % program
parser = OptionParser(usage=usg)
parser.add_option("-t", "--template", dest="template",
default=False, action="store_true",
help="set up current directory",
metavar="TEMPLATE")
parser.add_option("-k", "--skip-steps", dest="skip",
default=None, action="store_true",
help="skip optional steps")
parser.add_option("-m", "--minimize", dest="minimize",
default=False, action="store_true",
help="run minimize instead of anneal")
return parser
def usage(parser, msg=None, width=70):
err = ' ERROR '.center(width, '#')
errbar = '#' * width
hline = '=' * width
if msg is not None:
print '\n'.join(('', err, msg, errbar, ''))
print hline
print parser.format_help()
sys.exit(0)
def main():
banner()
parser = doopts()
(options, args) = parser.parse_args()
try:
texfile = args[0]
except IndexError:
usage(parser, 'No texfile specified.')
if __name__ == "__main__":
main()
